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
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
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
// 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/.

//! ## [9.6 Agents](https://tc39.es/ecma262/#sec-agents)
//!
//! An _agent_ comprises a set of ECMAScript
//! # [execution contexts](https://tc39.es/ecma262/#sec-execution-contexts), an
//! execution context stack, a running execution context, an _Agent Record_,
//! and an _executing thread_. Except for the
//! # [executing thread](https://tc39.es/ecma262/#executing-thread), the
//! constituents of an agent belong exclusively to that agent.
//!
//! In Nova, the [`Agent Record`](Agent) is the main entry point into the
//! JavaScript virtual machine and its heap memory.
//!
//! ### Notes
//!
//! - This is inspired by and/or copied from Kiesel engine:
//!   Copyright (c) 2023-2024 Linus Groh

use ahash::AHashMap;

#[cfg(test)]
use crate::ecmascript::GlobalEnvironment;
#[cfg(feature = "shared-array-buffer")]
use crate::ecmascript::SharedArrayBuffer;
#[cfg(feature = "atomics")]
use crate::ecmascript::WaitAsyncJob;
#[cfg(feature = "weak-refs")]
use crate::ecmascript::{FinalizationRegistryCleanupJob, clear_kept_objects};
use crate::{
    ecmascript::{
        AbstractModuleMethods, Environment, ErrorHeapData, ExecutionContext, Function,
        GraphLoadingStateRecord, HostDefined, ModuleRequest, Object, OrdinaryObject,
        PrivateEnvironment, PrivateName, Promise, PromiseReactionJob, PromiseResolveThenableJob,
        PropertyKey, PropertyLookupCache, Realm, RealmRecord, Reference, Referrer, ScriptOrModule,
        SourceCode, SourceTextModule, String, Symbol, Value, ValueRootRepr,
        get_identifier_reference, initialize_default_realm, initialize_host_defined_realm,
        parse_script, script_evaluation, to_string, try_get_identifier_reference,
    },
    engine::{
        Bindable, GcScope, Global, HeapRootCollection, HeapRootData, HeapRootRef, NoGcScope,
        Rootable, Vm, bindable_handle,
    },
    heap::{
        ArenaAccess, CompactionLists, CreateHeapData, Heap, HeapIndexHandle, HeapMarkAndSweep,
        PrimitiveHeapAccess, WorkQueues, heap_gc,
    },
    ndt,
};

use core::{any::Any, cell::RefCell, ops::ControlFlow, ptr::NonNull};
use std::collections::TryReserveError;

/// Creation options for [`GcAgent`].
///
/// [`GcAgent`]: GcAgent
#[derive(Debug, Default)]
pub struct AgentOptions {
    /// Stops the Agent from performing any garbage collection.
    pub disable_gc: bool,
    /// Makes the Agent print its internal bytecode execution debug data into
    /// stderr.
    pub print_internals: bool,
    /// Controls the \[\[CanBlock]] option of the Agent Record. If set to true,
    /// calling `Atomics.wait()` will throw an error to signal that blocking the
    /// main thread is not allowed.
    pub no_block: bool,
}

/// Result of methods that may throw a JavaScript error.
pub type JsResult<'a, T> = core::result::Result<T, JsError<'a>>;

impl<'a, T: 'a> From<JsError<'a>> for JsResult<'a, T> {
    fn from(value: JsError<'a>) -> Self {
        JsResult::Err(value)
    }
}

/// A JavaScript [`Value`] thrown as an error.
///
/// [`Value`]: crate::ecmascript::Value
#[derive(Debug, Default, Clone, Copy, PartialEq)]
#[repr(transparent)]
pub struct JsError<'a>(Value<'a>);
bindable_handle!(JsError);

impl<'a> JsError<'a> {
    pub(crate) fn new(value: Value<'a>) -> Self {
        Self(value)
    }

    /// Get the thrown JavaScript [`Value`].
    ///
    /// [`Value`]: crate::ecmascript::Value
    pub fn value(self) -> Value<'a> {
        self.0
    }

    /// Convert the thrown JavaScript [`Value`] into a JavaScript [`String`].
    ///
    /// [`Value`]: crate::ecmascript::Value
    /// [`String`]: crate::ecmascript::String
    pub fn to_string<'gc>(self, agent: &mut Agent, gc: GcScope<'gc, '_>) -> String<'gc> {
        to_string(agent, self.0, gc).unwrap()
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(transparent)]
pub(crate) struct JsErrorRootRepr(ValueRootRepr);

impl Rootable for JsError<'_> {
    type RootRepr = JsErrorRootRepr;

    fn to_root_repr(value: Self) -> Result<Self::RootRepr, HeapRootData> {
        Value::to_root_repr(value.value()).map(JsErrorRootRepr)
    }

    fn from_root_repr(value: &Self::RootRepr) -> Result<Self, HeapRootRef> {
        Value::from_root_repr(&value.0).map(JsError)
    }

    fn from_heap_ref(heap_ref: HeapRootRef) -> Self::RootRepr {
        JsErrorRootRepr(Value::from_heap_ref(heap_ref))
    }

    fn from_heap_data(heap_data: HeapRootData) -> Option<Self> {
        Value::from_heap_data(heap_data).map(JsError)
    }
}

impl HeapMarkAndSweep for JsError<'static> {
    fn mark_values(&self, queues: &mut crate::heap::WorkQueues) {
        self.0.mark_values(queues);
    }

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

/// Failure conditions for internal method's Try variants.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TryError<'a> {
    /// The method threw an error.
    Err(JsError<'a>),
    /// The method cannot run to completion without calling into JavaScript.
    ///
    /// > Note 1: methods can and are encouraged to delegate any JavaScript
    /// > tail calls to the caller (such as getter, setter, or Proxy trap call
    /// > at the end of a \[\[Get]] or \[\[Set]] method). This variant should
    /// > be used when the method would need to perform additional work after
    /// > the JavaScript call is done.
    ///
    /// > Note 2: Returning this error indicates that the entire operation will
    /// > be rerun from start to finish in a GC-capable scope. The Try method
    /// > variant must therefore be undetectable; it cannot perform mutations
    /// > that would affect how the normal variant runs.
    GcError,
}
bindable_handle!(TryError);

/// Helper function turning an Option into a [`TryResult`]. If the value is
/// `Some` then the result is `Continue`, otherwise it is [`TryError::GcError`].
///
/// [`TryResult`]: crate::ecmascript::TryResult
/// [`TryError::GcError`]: crate::ecmascript::TryError::GcError
pub(crate) fn option_into_try<'a, T: 'a>(value: Option<T>) -> TryResult<'a, T> {
    match value {
        Some(value) => TryResult::Continue(value),
        None => TryError::GcError.into(),
    }
}

/// Convert a JsResult into a TryResult.
///
/// This is useful when an abstract operation can throw errors but cannot call
/// into JavaScript, and is called from a Try method. The AO returns a JsResult
/// but the caller wants to convert it into a TryResult before returning.
pub fn js_result_into_try<'a, T: 'a>(value: JsResult<'a, T>) -> TryResult<'a, T> {
    match value {
        Ok(value) => TryResult::Continue(value),
        Err(err) => TryResult::Break(TryError::Err(err)),
    }
}

/// Convert a `TryResult<T>` into a [JsResult] of an `Option<T>`.
///
/// This is useful when a method that may trigger GC calls into a Try method
/// and wants to rethrow any errors and use the result if available.
pub fn try_result_into_js<'a, T: 'a>(value: TryResult<'a, T>) -> JsResult<'a, Option<T>> {
    match value {
        TryResult::Continue(value) => JsResult::Ok(Some(value)),
        TryResult::Break(TryError::GcError) => JsResult::Ok(None),
        TryResult::Break(TryError::Err(err)) => JsResult::Err(err),
    }
}

/// Convert a `TryResult<T>` into an `Option<JsResult<T>>`.
///
/// This is useful when a method that may trigger GC calls into a Try method
/// and wants to use the result if available, error or not.
pub fn try_result_into_option_js<'a, T: 'a>(value: TryResult<'a, T>) -> Option<JsResult<'a, T>> {
    match value {
        TryResult::Continue(value) => Some(JsResult::Ok(value)),
        TryResult::Break(TryError::GcError) => None,
        TryResult::Break(TryError::Err(err)) => Some(JsResult::Err(err)),
    }
}

impl<'a, T: 'a> From<JsError<'a>> for TryResult<'a, T> {
    fn from(value: JsError<'a>) -> Self {
        TryResult::Break(TryError::Err(value))
    }
}

impl<'a, T: 'a> From<TryError<'a>> for TryResult<'a, T> {
    fn from(value: TryError<'a>) -> Self {
        TryResult::Break(value)
    }
}

macro_rules! try_result_ok {
    ($self:ident) => {
        impl<'a> core::convert::From<$self<'a>> for TryResult<'a, $self<'a>> {
            fn from(value: $self<'a>) -> Self {
                TryResult::Continue(value)
            }
        }
    };
}
pub(crate) use try_result_ok;

/// Result of methods that are not allowed to call JavaScript or perform
/// garbage collection.
pub type TryResult<'a, T> = ControlFlow<TryError<'a>, T>;

/// Returns the contained [`Continue`] value, consuming the self value.
///
/// # Panics
///
/// Panics if the self value contains [`Break`].
///
/// [`Break`]: TryResult::Break
/// [`Continue`]: TryResult::Continue
#[inline]
pub fn unwrap_try<'a, T: 'a>(try_result: TryResult<'a, T>) -> T {
    match try_result {
        TryResult::Continue(t) => t,
        TryResult::Break(_) => unreachable!(),
    }
}

pub(crate) enum InnerJob {
    PromiseResolveThenable(PromiseResolveThenableJob),
    PromiseReaction(PromiseReactionJob),
    #[cfg(feature = "atomics")]
    WaitAsync(WaitAsyncJob),
    #[cfg(feature = "weak-refs")]
    FinalizationRegistry(FinalizationRegistryCleanupJob),
}

/// # [Job](https://tc39.es/ecma262/#sec-jobs)
///
/// A _Job_ is an Abstract Closure with no parameters that initiates an
/// ECMAScript computation when no other ECMAScript computation is currently in
/// progress. Jobs are scheduled for execution by ECMAScript host environments
/// in a particular agent.
///
/// A Job is executed by calling the [`run`] method on it, consuming it.
///
/// [`run`]: Job::run
pub struct Job {
    pub(crate) realm: Option<Global<Realm<'static>>>,
    pub(crate) inner: InnerJob,
}

impl Job {
    /// Returns `true` if the Job has finished and can be run.
    pub fn is_finished(&self) -> bool {
        match &self.inner {
            #[cfg(feature = "atomics")]
            InnerJob::WaitAsync(job) => job.is_finished(),
            _ => true,
        }
    }

    /// Execute the Job, consuming it in the process.
    ///
    /// The execution of a Job never returns any result but it may throw an
    /// error value.
    pub fn run<'a>(self, agent: &mut Agent, gc: GcScope<'a, '_>) -> JsResult<'a, ()> {
        let mut id = 0;
        ndt::job_evaluation_start!(|| {
            id = core::ptr::from_ref(&self).addr() as u64;
            id
        });
        let mut pushed_context = false;
        if let Some(realm) = self.realm.map(|r| r.take(agent))
            && agent.current_realm(gc.nogc()) != realm
        {
            agent.push_execution_context(ExecutionContext {
                ecmascript_code: None,
                function: None,
                realm,
                script_or_module: None,
            });
            pushed_context = true;
        }

        let result = match self.inner {
            InnerJob::PromiseResolveThenable(job) => job.run(agent, gc),
            InnerJob::PromiseReaction(job) => job.run(agent, gc),
            #[cfg(feature = "atomics")]
            InnerJob::WaitAsync(job) => job.run(agent, gc),
            #[cfg(feature = "weak-refs")]
            InnerJob::FinalizationRegistry(job) => {
                job.run(agent, gc);
                Ok(())
            }
        };

        if pushed_context {
            agent.execution_context_stack.pop();
        }

        ndt::job_evaluation_done!(|| id);

        result
    }
}

/// Parameter to [HostPromiseRejectionTracker] embedder hook.
///
/// [HostPromiseRejectionTracker]: https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PromiseRejectionTrackerOperation {
    /// A Promise was rejected without any handlers.
    Reject,
    /// A handler was added to a rejected Promise for the first time.
    Handle,
}

#[derive(Clone, Copy, Default, PartialEq, Eq)]
#[cfg(feature = "shared-array-buffer")]
/// Parameter to [HostGrowSharedArrayBuffer] embedder hook.
///
/// [HostGrowSharedArrayBuffer]: https://tc39.es/ecma262/#sec-hostgrowsharedarraybuffer
pub enum GrowSharedArrayBufferResult {
    /// Returned when the embedder does not handle growing of this
    /// SharedArrayBuffer.
    #[default]
    Unhandled = 0,
    /// Returned when the embedder did handle growing of this SharedArrayBuffer.
    Handled = 1,
}

/// Trait the Nova JavaScript engine to interact with the embedder. The embedder
/// calls methods are defined by the ECMAScript specification.
pub trait HostHooks: core::fmt::Debug {
    /// ### [19.2.1.2 HostEnsureCanCompileStrings ( calleeRealm )](https://tc39.es/ecma262/#sec-hostensurecancompilestrings)
    #[allow(unused_variables)]
    fn ensure_can_compile_strings<'a>(
        &self,
        callee_realm: Realm<'a>,
        gc: NoGcScope<'a, '_>,
    ) -> JsResult<'a, ()> {
        // The default implementation of HostEnsureCanCompileStrings is to return NormalCompletion(unused).
        Ok(())
    }

    /// ### [20.2.5 HostHasSourceTextAvailable ( func )](https://tc39.es/ecma262/#sec-hosthassourcetextavailable)
    #[allow(unused_variables)]
    fn has_source_text_available(&self, func: Function) -> bool {
        // The default implementation of HostHasSourceTextAvailable is to return true.
        true
    }

    /// ### [9.5.4 HostEnqueueGenericJob ( job, realm )](https://tc39.es/ecma262/#sec-hostenqueuegenericjob)
    ///
    /// The host-defined abstract operation HostEnqueueGenericJob takes
    /// arguments _job_ (a Job Abstract Closure) and _realm_ (a Realm Record)
    /// and returns unused. It schedules _job_ in the realm realm in the agent
    /// signified by _realm_.\[\[AgentSignifier]] to be performed at some future
    /// time. The Abstract Closures used with this algorithm are intended to be
    /// scheduled without additional constraints, such as priority and ordering.
    ///
    /// An implementation of HostEnqueueGenericJob must conform to the
    /// requirements in 9.5.
    fn enqueue_generic_job(&self, job: Job);

    /// ### [9.5.5 HostEnqueuePromiseJob ( job, realm )](https://tc39.es/ecma262/#sec-hostenqueuepromisejob)
    fn enqueue_promise_job(&self, job: Job);

    /// ### [9.5.6 HostEnqueueTimeoutJob ( timeoutJob, realm, milliseconds )](https://tc39.es/ecma262/#sec-hostenqueuetimeoutjob)
    ///
    /// The host-defined abstract operation HostEnqueueTimeoutJob takes
    /// arguments _timeoutJob_ (a Job Abstract Closure), _realm_ (a Realm
    /// Record), and _milliseconds_ (a non-negative finite Number) and returns
    /// unused. It schedules _timeoutJob_ in the realm _realm_ in the agent
    /// signified by _realm_.\[\[AgentSignifier]] to be performed after at least
    /// _milliseconds_ milliseconds.
    ///
    /// An implementation of HostEnqueueTimeoutJob must conform to the
    /// requirements in 9.5.
    fn enqueue_timeout_job(&self, timeout_job: Job, milliseconds: u64);

    /// ### [9.9.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry )](https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry)
    ///
    /// The host-defined abstract operation
    /// HostEnqueueFinalizationRegistryCleanupJob takes argument
    /// _finalizationRegistry_ (a FinalizationRegistry) and returns unused.
    ///
    /// Let _cleanupJob_ be a new Job Abstract Closure with no parameters that
    /// captures _finalizationRegistry_ and performs the following steps when
    /// called:
    ///
    /// ```text
    /// 1. Let cleanupResult be
    ///    Completion(CleanupFinalizationRegistry(finalizationRegistry)).
    /// 2. If cleanupResult is an abrupt completion, perform any host-defined
    ///    steps for reporting the error.
    /// 3. Return unused.
    /// ```
    ///
    /// An implementation of HostEnqueueFinalizationRegistryCleanupJob schedules
    /// cleanupJob to be performed at some future time, if possible. It must
    /// also conform to the requirements in 9.5.
    #[allow(unused_variables)]
    #[cfg(feature = "weak-refs")]
    fn enqueue_finalization_registry_cleanup_job(&self, job: Job) {
        // By default, just ignore cleanup.
    }

    /// ### [27.2.1.9 HostPromiseRejectionTracker ( promise, operation )](https://tc39.es/ecma262/#sec-host-promise-rejection-tracker)
    #[allow(unused_variables)]
    fn promise_rejection_tracker(
        &self,
        promise: Promise,
        operation: PromiseRejectionTrackerOperation,
    ) {
        // The default implementation of HostPromiseRejectionTracker is to return unused.
    }

    /// ### [16.2.1.10 HostLoadImportedModule ( referrer, moduleRequest, hostDefined, payload )](https://tc39.es/ecma262/#sec-HostLoadImportedModule)
    ///
    /// The host-defined abstract operation HostLoadImportedModule takes
    /// arguments referrer (a Script Record, a Cyclic Module Record, or a Realm
    /// Record), moduleRequest (a ModuleRequest Record), hostDefined (anything),
    /// and payload (a GraphLoadingState Record or a PromiseCapability Record)
    /// and returns unused.
    ///
    /// > NOTE 1: An example of when referrer can be a Realm Record is in a web
    /// > browser host. There, if a user clicks on a control given by
    /// > ```html
    /// > <button type="button" onclick="import('./foo.mjs')">Click me</button>
    /// > ```
    /// > there will be no active script or module at the time the `import()`
    /// > expression runs. More generally, this can happen in any situation
    /// > where the host pushes execution contexts with null ScriptOrModule
    /// > components onto the execution context stack.
    ///
    /// An implementation of HostLoadImportedModule must conform to the
    /// following requirements:
    ///
    /// * The host environment must perform `FinishLoadingImportedModule
    ///   referrer, moduleRequest, payload, result)`, where `result` is either
    ///   a normal completion containing the loaded Module Record or a throw
    ///   completion, either synchronously or asynchronously.
    ///
    /// * If this operation is called multiple times with two `(referrer,
    ///   moduleRequest)` pairs such that:
    ///
    ///   * the first `referrer` is the same as the second `referrer`;
    ///
    ///   * `ModuleRequestsEqual(the first moduleRequest, the second
    ///     moduleRequest)` is true;
    ///
    ///   and it performs `FinishLoadingImportedModule(referrer, moduleRequest,
    ///   payload, result)` where `result` is a normal completion, then it must
    ///   perform `FinishLoadingImportedModule(referrer, moduleRequest,
    ///   payload, result)` with the same result each time.
    ///
    /// * If `moduleRequest.[[Attributes]]` has an entry entry such that
    ///   `entry.[[Key]]` is "type" and `entry.[[Value]]` is "json", when the
    ///   host environment performs `FinishLoadingImportedModule(referrer,
    ///   moduleRequest, payload, result)`, result must either be the
    ///   Completion Record returned by an invocation of `ParseJSONModule` or a
    ///   throw completion.
    ///
    /// * The operation must treat `payload` as an opaque value to be passed
    ///   through to `FinishLoadingImportedModule`.
    ///
    /// The actual process performed is host-defined, but typically consists of
    /// performing whatever I/O operations are necessary to load the appropriate
    /// Module Record. Multiple different `(referrer,
    /// moduleRequest.[[Specifier]], moduleRequest.[[Attributes]])` triples may
    /// map to the same Module Record instance. The actual mapping semantics is
    /// host-defined but typically a normalization process is applied to
    /// specifier as part of the mapping process. A typical normalization
    /// process would include actions such as expansion of relative and
    /// abbreviated path specifiers.
    ///
    /// > NOTE 2: The above text requires that hosts support JSON modules when
    /// > imported with `type: "json"` (and `HostLoadImportedModule` completes
    /// > normally), but it does not prohibit hosts from supporting JSON
    /// > modules when imported without `type: "json"`.
    #[allow(unused_variables)]
    fn load_imported_module<'gc>(
        &self,
        agent: &mut Agent,
        referrer: Referrer<'gc>,
        module_request: ModuleRequest<'gc>,
        host_defined: Option<HostDefined>,
        payload: &mut GraphLoadingStateRecord<'gc>,
        gc: NoGcScope<'gc, '_>,
    ) {
        unimplemented!();
    }

    /// ### [16.2.1.12.1 HostGetSupportedImportAttributes ( )](https://tc39.es/ecma262/#sec-hostgetsupportedimportattributes)
    ///
    /// The host-defined abstract operation HostGetSupportedImportAttributes
    /// takes no arguments and returns a List of Strings. It allows host
    /// environments to specify which import attributes they support. Only
    /// attributes with supported keys will be provided to the host.
    ///
    /// An implementation of HostGetSupportedImportAttributes must conform to
    /// the following requirements:
    ///
    /// * It must return a List of Strings, each indicating a supported
    ///   attribute.
    /// * Each time this operation is called, it must return the same List with
    ///   the same contents in the same order.
    ///
    /// The default implementation of HostGetSupportedImportAttributes is to
    /// return a new empty List.
    ///
    /// > Note: The purpose of requiring the host to specify its supported
    /// > import attributes, rather than passing all attributes to the host and
    /// > letting it then choose which ones it wants to handle, is to ensure
    /// > that unsupported attributes are handled in a consistent way across
    /// > different hosts.
    fn get_supported_import_attributes(&self) -> &[&'static str] {
        &[]
    }

    /// ### [13.3.12.1.1 HostGetImportMetaProperties ( moduleRecord )](https://tc39.es/ecma262/#sec-hostgetimportmetaproperties)
    ///
    /// The host-defined abstract operation HostGetImportMetaProperties takes
    /// argument moduleRecord (a Module Record) and returns a List of Records
    /// with fields \[\[Key]] (a property key) and \[\[Value]] (an ECMAScript
    /// language value). It allows hosts to provide property keys and values for
    /// the object returned from `import.meta`.
    ///
    /// The default implementation of HostGetImportMetaProperties is to return a
    /// new empty List.
    #[allow(unused_variables)]
    fn get_import_meta_properties<'gc>(
        &self,
        agent: &mut Agent,
        module_record: SourceTextModule,
        gc: NoGcScope<'gc, '_>,
    ) -> Vec<(PropertyKey<'gc>, Value<'gc>)> {
        Default::default()
    }

    /// ### [13.3.12.1.2 HostFinalizeImportMeta ( importMeta, moduleRecord )](https://tc39.es/ecma262/#sec-hostfinalizeimportmeta)
    ///
    /// The host-defined abstract operation HostFinalizeImportMeta takes
    /// arguments importMeta (an Object) and moduleRecord (a Module Record) and
    /// returns unused. It allows hosts to perform any extraordinary operations
    /// to prepare the object returned from import.meta.
    ///
    /// Most hosts will be able to simply define HostGetImportMetaProperties,
    /// and leave HostFinalizeImportMeta with its default behaviour. However,
    /// HostFinalizeImportMeta provides an "escape hatch" for hosts which need
    /// to directly manipulate the object before it is exposed to ECMAScript
    /// code.
    ///
    /// The default implementation of HostFinalizeImportMeta is to return
    /// unused.
    #[allow(unused_variables)]
    fn finalize_import_meta(
        &self,
        agent: &mut Agent,
        import_meta: OrdinaryObject,
        module_record: SourceTextModule,
        gc: NoGcScope,
    ) {
    }

    /// ### [25.2.2.3 HostGrowSharedArrayBuffer ( buffer, newByteLength )](tc39.es/ecma262/#sec-hostgrowsharedarraybuffer)
    ///
    /// The host-defined abstract operation HostGrowSharedArrayBuffer takes
    /// arguments `buffer` (a SharedArrayBuffer) and `newByteLength` (a
    /// non-negative integer) and returns either a normal completion containing
    /// either HANDLED or UNHANDLED, or a throw completion. It gives the host an
    /// opportunity to perform implementation-defined growing of `buffer`. If
    /// the host chooses not to handle growing of `buffer`, it may return
    /// UNHANDLED for the default behaviour.
    ///
    /// The implementation of HostGrowSharedArrayBuffer must conform to the
    /// following requirements:
    ///
    /// * If the abstract operation does not complete normally with UNHANDLED,
    ///   and `newByteLength` < the current byte length of the `buffer` or
    ///   `newByteLength` > `buffer.[[ArrayBufferMaxByteLength]]`, throw a
    ///   RangeError exception.
    /// * Let `isLittleEndian` be the value of the `[[LittleEndian]]` field of
    ///   the surrounding agent's Agent Record. If the abstract operation
    ///   completes normally with HANDLED, a WriteSharedMemory or
    ///   ReadModifyWriteSharedMemory event whose `[[Order]]` is seq-cst,
    ///   `[[Payload]]` is `NumericToRawBytes(biguint64, newByteLength, isLittleEndian)`,
    ///   `[[Block]]` is `buffer.[[ArrayBufferByteLengthData]]`, `[[ByteIndex]]`
    ///   is 0, and `[[ElementSize]]` is 8 is added to the surrounding agent's
    ///   candidate execution such that racing calls to
    ///   `SharedArrayBuffer.prototype.grow` are not "lost", i.e. silently do
    ///   nothing.
    ///
    /// > NOTE: The second requirement above is intentionally vague about how
    /// > or when the current byte length of buffer is read. Because the byte
    /// > length must be updated via an atomic read-modify-write operation on
    /// > the underlying hardware, architectures that use
    /// > load-link/store-conditional or load-exclusive/store-exclusive
    /// > instruction pairs may wish to keep the paired instructions close in
    /// > the instruction stream. As such, `SharedArrayBuffer.prototype.grow`
    /// > itself does not perform bounds checking on newByteLength before
    /// > calling HostGrowSharedArrayBuffer, nor is there a requirement on when
    /// > the current byte length is read.
    /// >
    /// > This is in contrast with HostResizeArrayBuffer, which is guaranteed
    /// > that the value of `newByteLength` is `≥ 0` and
    /// > `≤ buffer.[[ArrayBufferMaxByteLength]]`.
    #[allow(unused_variables)]
    #[inline(always)]
    #[cfg(feature = "shared-array-buffer")]
    fn grow_shared_array_buffer<'gc>(
        &self,
        agent: &Agent,
        buffer: SharedArrayBuffer,
        new_byte_length: u64,
        gc: NoGcScope<'gc, '_>,
    ) -> JsResult<'gc, GrowSharedArrayBufferResult> {
        Ok(GrowSharedArrayBufferResult::Unhandled)
    }

    /// Get access to the Host data, useful to share state between calls of
    /// built-in functions.
    ///
    /// # Panics
    ///
    /// The default implementation panics when called.
    fn get_host_data(&self) -> &dyn Any {
        unimplemented!()
    }
}

/// # Owned ECMAScript [`Agent`]
///
/// This can be used to run code and to run garbage collection on the [`Agent`]
/// with no JavaScript guaranteed to be running.
///
/// [`Agent`]: Agent
///
/// ## Examples
///
/// ```rust
/// use nova_vm::{ecmascript::{Agent, DefaultHostHooks, GcAgent, Object}, engine::GcScope};
/// let mut agent = GcAgent::new(Default::default(), &DefaultHostHooks);
/// let create_global_object: Option<
///     for<'a> fn(&mut Agent, GcScope<'a, '_>) -> Object<'a>,
/// > = None;
/// let create_global_this_value: Option<
///     for<'a> fn(&mut Agent, GcScope<'a, '_>) -> Object<'a>,
/// > = None;
/// let initialize_global_object: Option<fn(&mut Agent, Object, GcScope)> = None;
/// let realm = agent.create_realm(create_global_object, create_global_this_value, initialize_global_object);
/// let _ = agent.run_in_realm(&realm, |_agent, _gc| {
///   // do work here
/// });
/// ```
pub struct GcAgent {
    agent: Agent,
    realm_roots: Vec<Option<Realm<'static>>>,
}

/// # ECMAScript Realm root
///
/// As long as this is not passed back into GcAgent, the Realm it represents
/// won't be removed by the garbage collector.
#[must_use]
#[repr(transparent)]
pub struct RealmRoot {
    /// Defines an index in the GcAgent::realm_roots vector that contains the
    /// RealmIdentifier of this Realm.
    index: u8,
}

impl RealmRoot {
    /// Initialize the Realm's \[\[HostDefined]] field to a value.
    ///
    /// ## Panics
    ///
    /// Panics if the \[\[HostDefined]] field is non-empty.
    pub fn initialize_host_defined(&self, agent: &mut GcAgent, host_defined: HostDefined) {
        let realm = agent.get_realm_by_root(self);
        realm.initialize_host_defined(&mut agent.agent, host_defined);
    }
}

impl GcAgent {
    /// Create a new JavaScript engine.
    pub fn new(options: AgentOptions, host_hooks: &'static dyn HostHooks) -> Self {
        Self {
            agent: Agent::new(options, host_hooks),
            realm_roots: Vec::with_capacity(1),
        }
    }

    /// Root the given realm: this stores the [`Realm`] in a list of roots and returns a RealmRoot object that
    /// points to the list index where the
    ///
    /// [`Realm`]: crate::ecmascript::Realm
    fn root_realm(&mut self, identifier: Realm<'static>) -> RealmRoot {
        let index = if let Some((index, deleted_entry)) = self
            .realm_roots
            .iter_mut()
            .enumerate()
            .find(|(_, entry)| entry.is_none())
        {
            *deleted_entry = Some(identifier);
            index
        } else {
            self.realm_roots.push(Some(identifier));
            self.realm_roots.len() - 1
        };
        // Agent's Realm creation should've already popped the context that
        // created this Realm. The context stack should now be empty.
        assert!(self.agent.execution_context_stack.is_empty());
        RealmRoot {
            index: u8::try_from(index).expect("Only up to 256 simultaneous Realms are supported"),
        }
    }

    /// Creates a new Realm
    ///
    /// The Realm will not be removed by garbage collection until
    /// [`GcAgent::remove_realm`] is called.
    pub fn create_realm(
        &mut self,
        create_global_object: Option<
            impl for<'a> FnOnce(&mut Agent, GcScope<'a, '_>) -> Object<'a>,
        >,
        create_global_this_value: Option<
            impl for<'a> FnOnce(&mut Agent, GcScope<'a, '_>) -> Object<'a>,
        >,
        initialize_global_object: Option<impl FnOnce(&mut Agent, Object, GcScope)>,
    ) -> RealmRoot {
        let realm = self.agent.create_realm_internal(
            create_global_object,
            create_global_this_value,
            initialize_global_object,
        );
        self.root_realm(realm.unbind())
    }

    /// Creates a default realm suitable for basic testing only.
    pub fn create_default_realm(&mut self) -> RealmRoot {
        let realm = self.agent.create_default_realm();
        self.root_realm(realm)
    }

    /// Removes the given realm. Resources associated with the realm are free to
    /// be collected by the garbage collector after this call.
    pub fn remove_realm(&mut self, realm: RealmRoot) {
        let RealmRoot { index } = realm;
        let error_message = "Cannot remove a non-existing Realm";
        // After this removal, the Realm can be collected by GC.
        let _ = self
            .realm_roots
            .get_mut(index as usize)
            .expect(error_message)
            .take()
            .expect(error_message);
        while let Some(r) = self.realm_roots.last()
            && r.is_none()
        {
            let _ = self.realm_roots.pop();
        }
    }

    /// Run a closure inside a given realm.
    pub fn run_in_realm<F, R>(&mut self, realm: &RealmRoot, func: F) -> R
    where
        F: for<'agent, 'gc, 'scope> FnOnce(&'agent mut Agent, GcScope<'gc, 'scope>) -> R,
    {
        let realm = self.get_realm_by_root(realm);
        assert!(self.agent.execution_context_stack.is_empty());
        let result = self.agent.run_in_realm(realm, func);
        #[cfg(feature = "weak-refs")]
        clear_kept_objects(&mut self.agent);
        assert!(self.agent.execution_context_stack.is_empty());
        assert!(self.agent.vm_stack.is_empty());
        self.agent.stack_refs.borrow_mut().clear();
        result
    }

    /// Run a macrotask job.
    pub fn run_job<F, R>(&mut self, job: Job, then: F) -> R
    where
        F: for<'agent, 'gc, 'scope> FnOnce(
            &'agent mut Agent,
            JsResult<'_, ()>,
            GcScope<'gc, 'scope>,
        ) -> R,
    {
        assert!(self.agent.execution_context_stack.is_empty());
        let result = self.agent.run_job(job, then);
        #[cfg(feature = "weak-refs")]
        clear_kept_objects(&mut self.agent);
        assert!(self.agent.execution_context_stack.is_empty());
        assert!(self.agent.vm_stack.is_empty());
        self.agent.stack_refs.borrow_mut().clear();
        result
    }

    fn get_realm_by_root(&self, realm_root: &RealmRoot) -> Realm<'static> {
        let index = realm_root.index;
        let error_message = "Couldn't find Realm by RealmRoot";
        *self
            .realm_roots
            .get(index as usize)
            .expect(error_message)
            .as_ref()
            .expect(error_message)
    }

    /// Perform garbage collection on the Agent heap. Any [`RealmRoot`]s are
    /// retained.
    ///
    /// [`RealmRoot`]: RealmRoot
    pub fn gc(&mut self) {
        if self.agent.options.disable_gc {
            // GC is disabled; no-op
            return;
        }
        let (mut gc, mut scope) = unsafe { GcScope::create_root() };
        let gc = GcScope::new(&mut gc, &mut scope);
        let Self {
            agent, realm_roots, ..
        } = self;
        heap_gc(agent, realm_roots, gc);
    }
}

/// ## [9.7 Agents](https://tc39.es/ecma262/#sec-agents)
///
/// Agents are the way that JavaScript code is executed in the Nova JavaScript
/// engine. An Agent contains the JavaScript heap, the execution context, and
/// other parts required to execute JavaScript code.
///
/// For creating an Agent, see [`GcAgent`](GcAgent).
pub struct Agent {
    pub(crate) heap: Heap,
    pub(crate) options: AgentOptions,
    #[expect(dead_code)]
    symbol_id: usize,
    pub(crate) global_symbol_registry: AHashMap<String<'static>, Symbol<'static>>,
    pub(crate) host_hooks: &'static dyn HostHooks,
    execution_context_stack: Vec<ExecutionContext>,
    /// Temporary storage for on-stack heap roots.
    ///
    /// TODO: With Realm-specific heaps we'll need a side-table to define which
    /// Realm a particular stack value points to.
    pub(crate) stack_refs: RefCell<Vec<HeapRootData>>,
    /// Temporary storage for on-stack heap root collections.
    pub(crate) stack_ref_collections: RefCell<Vec<HeapRootCollection>>,
    /// Temporary storage for on-stack VMs.
    pub(crate) vm_stack: Vec<NonNull<Vm>>,
    /// ### \[\[KeptAlive]]
    ///
    /// > Note: instead of storing objects in a list here, we only store a
    /// > boolean to clear weak references as needed.
    #[cfg(feature = "weak-refs")]
    pub(super) kept_alive: bool,
    /// Global counter for PrivateNames. This only ever grows.
    private_names_counter: u32,
    /// ### \[\[ModuleAsyncEvaluationCount]]
    ///
    /// Initially 0, used to assign unique incrementing values to the
    /// \[\[AsyncEvaluationOrder]] field of modules that are asynchronous or
    /// have asynchronous dependencies.
    module_async_evaluation_count: u32,
}

impl Agent {
    pub(crate) fn new(options: AgentOptions, host_hooks: &'static dyn HostHooks) -> Self {
        Self {
            heap: Heap::new(),
            options,
            symbol_id: 0,
            global_symbol_registry: AHashMap::default(),
            host_hooks,
            execution_context_stack: Vec::new(),
            stack_refs: RefCell::new(Vec::with_capacity(64)),
            stack_ref_collections: RefCell::new(Vec::with_capacity(32)),
            vm_stack: Vec::with_capacity(16),
            #[cfg(feature = "weak-refs")]
            kept_alive: false,
            private_names_counter: 0,
            module_async_evaluation_count: 0,
        }
    }

    /// Returns the value of the Agent's `[[CanBlock]]` field.
    pub fn can_suspend(&self) -> bool {
        !self.options.no_block
    }

    /// Perform garbage collection on the Agent's heap.
    ///
    /// This invalidates all handles; be sure to use the [`Bindable::bind`]
    /// function to make handles automatically invalidate on garbage collection.
    ///
    /// [`Bindable::bind`]: crate::engine::Bindable::bind
    pub fn gc(&mut self, gc: GcScope) {
        let mut root_realms = self
            .heap
            .realms
            .iter()
            .enumerate()
            .map(|(i, _)| Some(Realm::from_index(i)))
            .collect::<Vec<_>>();
        heap_gc(self, &mut root_realms, gc);
    }

    /// Checks if garbage collection should be performed based on the number of
    /// bytes allocated since last garbage collection.
    pub(crate) fn check_gc(&mut self) -> bool {
        // Perform garbage collection if over 2 MiB of allocations have been
        // performed since last GC.
        const ALLOC_COUNTER_LIMIT: usize = 1024 * 1024 * 2;
        self.heap.alloc_counter > ALLOC_COUNTER_LIMIT
    }

    fn get_created_realm_root(&mut self) -> Realm<'static> {
        assert!(!self.execution_context_stack.is_empty());
        let identifier = self.current_realm_id_internal();
        let _ = self.pop_execution_context();
        identifier.unbind()
    }

    /// Creates a new Realm
    ///
    /// This is intended for usage within BuiltinFunction calls.
    pub fn create_realm<'gc>(
        &mut self,
        create_global_object: Option<
            impl for<'a> FnOnce(&mut Agent, GcScope<'a, '_>) -> Object<'a>,
        >,
        create_global_this_value: Option<
            impl for<'a> FnOnce(&mut Agent, GcScope<'a, '_>) -> Object<'a>,
        >,
        initialize_global_object: Option<impl FnOnce(&mut Agent, Object, GcScope)>,
        gc: GcScope<'gc, '_>,
    ) -> Realm<'gc> {
        initialize_host_defined_realm(
            self,
            create_global_object,
            create_global_this_value,
            initialize_global_object,
            gc,
        );
        self.get_created_realm_root()
    }

    fn create_realm_internal(
        &mut self,
        create_global_object: Option<
            impl for<'a> FnOnce(&mut Agent, GcScope<'a, '_>) -> Object<'a>,
        >,
        create_global_this_value: Option<
            impl for<'a> FnOnce(&mut Agent, GcScope<'a, '_>) -> Object<'a>,
        >,
        initialize_global_object: Option<impl FnOnce(&mut Agent, Object, GcScope)>,
    ) -> Realm<'static> {
        let (mut gc, mut scope) = unsafe { GcScope::create_root() };
        let gc = GcScope::new(&mut gc, &mut scope);

        initialize_host_defined_realm(
            self,
            create_global_object,
            create_global_this_value,
            initialize_global_object,
            gc,
        );
        self.get_created_realm_root()
    }

    /// Creates a default realm suitable for basic testing only.
    ///
    /// This is intended for usage within BuiltinFunction calls.
    fn create_default_realm(&mut self) -> Realm<'static> {
        let (mut gc, mut scope) = unsafe { GcScope::create_root() };
        let gc = GcScope::new(&mut gc, &mut scope);

        initialize_default_realm(self, gc);
        self.get_created_realm_root()
    }

    fn run_in_realm<F, R>(&mut self, realm: Realm, func: F) -> R
    where
        F: for<'agent, 'gc, 'scope> FnOnce(&'agent mut Agent, GcScope<'gc, 'scope>) -> R,
    {
        let execution_stack_depth_before_call = self.execution_context_stack.len();
        self.push_execution_context(ExecutionContext {
            ecmascript_code: None,
            function: None,
            realm: realm.unbind(),
            script_or_module: None,
        });
        let (mut gc, mut scope) = unsafe { GcScope::create_root() };
        let gc = GcScope::new(&mut gc, &mut scope);

        let result = func(self, gc);
        assert_eq!(
            self.execution_context_stack.len(),
            execution_stack_depth_before_call + 1
        );
        self.pop_execution_context();
        result
    }

    /// Run a macrotask job.
    fn run_job<F, R>(&mut self, mut job: Job, then: F) -> R
    where
        F: for<'agent, 'gc, 'scope> FnOnce(
            &'agent mut Agent,
            JsResult<'_, ()>,
            GcScope<'gc, 'scope>,
        ) -> R,
    {
        let realm = job.realm.take().unwrap().take(self);
        let execution_stack_depth_before_call = self.execution_context_stack.len();
        self.push_execution_context(ExecutionContext {
            ecmascript_code: None,
            function: None,
            realm,
            script_or_module: None,
        });
        let (mut gc, mut scope) = unsafe { GcScope::create_root() };
        let mut gc = GcScope::new(&mut gc, &mut scope);

        let result = job.run(self, gc.reborrow()).unbind().bind(gc.nogc());
        let result = then(self, result.unbind(), gc);
        assert_eq!(
            self.execution_context_stack.len(),
            execution_stack_depth_before_call + 1
        );
        self.pop_execution_context();
        result
    }

    /// Get current Realm's global environment.
    #[cfg(test)]
    pub(crate) fn current_global_env<'a>(&self, gc: NoGcScope<'a, '_>) -> GlobalEnvironment<'a> {
        let realm = self.current_realm(gc);
        let Some(e) = realm.get(self).global_env else {
            panic_corrupted_agent()
        };
        e
    }

    /// Get current Realm's global object.
    pub fn current_global_object<'a>(&self, gc: NoGcScope<'a, '_>) -> Object<'a> {
        self.current_realm(gc).get(self).global_object
    }

    /// Get the [current Realm](https://tc39.es/ecma262/#current-realm).
    pub fn current_realm<'a>(&self, gc: NoGcScope<'a, '_>) -> Realm<'a> {
        self.current_realm_id_internal().bind(gc)
    }

    /// Set the current executiono context's Realm.
    pub(crate) fn set_current_realm(&mut self, realm: Realm) {
        let Some(ctx) = self.execution_context_stack.last_mut() else {
            panic_corrupted_agent()
        };
        ctx.realm = realm.unbind();
    }

    /// Internal method to get current Realm's identifier without binding.
    #[inline]
    pub(crate) fn current_realm_id_internal(&self) -> Realm<'static> {
        let Some(r) = self.execution_context_stack.last().map(|ctx| ctx.realm) else {
            panic_corrupted_agent()
        };
        r
    }

    pub(crate) fn current_realm_record(&self) -> &RealmRecord<'static> {
        self.get_realm_record_by_id(self.current_realm_id_internal())
    }

    pub(crate) fn get_realm_record_by_id<'r>(&self, id: Realm<'r>) -> &RealmRecord<'r> {
        id.get(self)
    }

    /// Create a native Error object with the given message.
    #[must_use]
    pub fn create_exception_with_static_message<'a>(
        &mut self,
        kind: ExceptionType,
        message: &'static str,
        gc: NoGcScope<'a, '_>,
    ) -> Value<'a> {
        let message = String::from_static_str(self, message, gc).unbind();
        self.heap
            .create(ErrorHeapData::new(kind, Some(message), None))
            .into()
    }

    #[must_use]
    pub(crate) fn todo<'a>(&mut self, feature: &'static str, gc: NoGcScope<'a, '_>) -> JsError<'a> {
        self.throw_exception(
            ExceptionType::Error,
            format!("{feature} not implemented"),
            gc,
        )
    }

    /// ### [5.2.3.2 Throw an Exception](https://tc39.es/ecma262/#sec-throw-an-exception)
    #[must_use]
    pub fn throw_exception_with_static_message<'a>(
        &mut self,
        kind: ExceptionType,
        message: &'static str,
        gc: NoGcScope<'a, '_>,
    ) -> JsError<'a> {
        JsError(
            self.create_exception_with_static_message(kind, message, gc)
                .unbind(),
        )
    }

    /// ### [5.2.3.2 Throw an Exception](https://tc39.es/ecma262/#sec-throw-an-exception)
    #[must_use]
    pub fn throw_exception<'a>(
        &mut self,
        kind: ExceptionType,
        message: std::string::String,
        gc: NoGcScope<'a, '_>,
    ) -> JsError<'a> {
        let message = String::from_string(self, message, gc).unbind();
        JsError(
            self.heap
                .create(ErrorHeapData::new(kind, Some(message), None))
                .into(),
        )
    }

    /// ### [5.2.3.2 Throw an Exception](https://tc39.es/ecma262/#sec-throw-an-exception)
    #[must_use]
    pub fn throw_exception_with_message<'a>(
        &mut self,
        kind: ExceptionType,
        message: String,
        gc: NoGcScope<'a, '_>,
    ) -> JsError<'a> {
        JsError(
            self.heap
                .create(ErrorHeapData::new(kind, Some(message.unbind()), None))
                .bind(gc)
                .into(),
        )
    }

    /// ### [5.2.3.2 Throw an Exception](https://tc39.es/ecma262/#sec-throw-an-exception)
    #[must_use]
    pub(crate) fn throw_allocation_exception<'a>(
        &mut self,
        error: TryReserveError,
        gc: NoGcScope<'a, '_>,
    ) -> JsError<'a> {
        self.throw_exception(ExceptionType::RangeError, error.to_string(), gc)
    }

    pub(crate) fn running_execution_context(&self) -> &ExecutionContext {
        let Some(ctx) = self.execution_context_stack.last() else {
            panic_corrupted_agent()
        };
        ctx
    }

    pub(crate) fn is_evaluating_strict_code(&self) -> bool {
        let Some(strict) = self
            .running_execution_context()
            .ecmascript_code
            .map(|e| e.is_strict_mode)
        else {
            panic_corrupted_agent()
        };
        strict
    }

    pub(crate) fn check_call_depth<'gc>(&mut self, gc: NoGcScope<'gc, '_>) -> JsResult<'gc, ()> {
        // Experimental number that caused stack overflow on local machine. A
        // better limit creation logic would be nice.
        if self.execution_context_stack.len() > 3500 {
            Err(self.throw_exception_with_static_message(
                ExceptionType::RangeError,
                "Maximum call stack size exceeded",
                gc,
            ))
        } else {
            Ok(())
        }
    }

    /// Returns the realm of the previous execution context.
    ///
    /// See steps 6-8 of [27.6.3.8 AsyncGeneratorYield ( value )](https://tc39.es/ecma262/#sec-asyncgeneratoryield).
    pub(crate) fn get_previous_context_realm<'a>(&self, gc: NoGcScope<'a, '_>) -> Realm<'a> {
        // 6. Assert: The execution context stack has at least two elements.
        assert!(self.execution_context_stack.len() >= 2);
        // 7. Let previousContext be the second to top element of the execution
        //    context stack.
        let previous_context =
            &self.execution_context_stack[self.execution_context_stack.len() - 2];
        // 8. Let previousRealm be previousContext's Realm.
        previous_context.realm.bind(gc)
    }

    pub(crate) fn push_execution_context(&mut self, context: ExecutionContext) {
        self.execution_context_stack.push(context);
    }

    pub(crate) fn pop_execution_context(&mut self) -> Option<ExecutionContext> {
        self.execution_context_stack.pop()
    }

    pub(crate) fn current_source_code<'a>(&self, gc: NoGcScope<'a, '_>) -> SourceCode<'a> {
        let Some(s) = self
            .execution_context_stack
            .last()
            .and_then(|s| s.ecmascript_code.as_ref())
            .map(|e| e.source_code.bind(gc))
        else {
            panic_corrupted_agent()
        };
        s
    }

    /// Returns the running execution context's LexicalEnvironment.
    pub(crate) fn current_lexical_environment<'a>(&self, gc: NoGcScope<'a, '_>) -> Environment<'a> {
        let Some(e) = self
            .execution_context_stack
            .last()
            .and_then(|s| s.ecmascript_code.as_ref())
            .map(|e| e.lexical_environment.bind(gc))
        else {
            panic_corrupted_agent()
        };
        e
    }

    /// Returns the running execution context's VariableEnvironment.
    pub(crate) fn current_variable_environment<'a>(
        &self,
        gc: NoGcScope<'a, '_>,
    ) -> Environment<'a> {
        let Some(e) = self
            .execution_context_stack
            .last()
            .and_then(|s| s.ecmascript_code.as_ref())
            .map(|e| e.variable_environment.bind(gc))
        else {
            panic_corrupted_agent()
        };
        e
    }

    /// Returns the running execution context's PrivateEnvironment.
    pub(crate) fn current_private_environment<'a>(
        &self,
        gc: NoGcScope<'a, '_>,
    ) -> Option<PrivateEnvironment<'a>> {
        let Some(e) = self
            .execution_context_stack
            .last()
            .and_then(|s| s.ecmascript_code.as_ref())
            .map(|e| e.private_environment.bind(gc))
        else {
            panic_corrupted_agent()
        };
        e
    }

    /// Sets the running execution context's LexicalEnvironment.
    pub(crate) fn set_current_lexical_environment(&mut self, env: Environment) {
        let Some(_) = self
            .execution_context_stack
            .last_mut()
            .and_then(|s| s.ecmascript_code.as_mut())
            .map(|e| {
                e.lexical_environment = env.unbind();
            })
        else {
            panic_corrupted_agent()
        };
    }

    /// Sets the running execution context's VariableEnvironment.
    pub(crate) fn set_current_variable_environment(&mut self, env: Environment) {
        let Some(_) = self
            .execution_context_stack
            .last_mut()
            .and_then(|s| s.ecmascript_code.as_mut())
            .map(|e| {
                e.variable_environment = env.unbind();
            })
        else {
            panic_corrupted_agent()
        };
    }

    /// Sets the running execution context's PrivateEnvironment.
    pub(crate) fn set_current_private_environment(&mut self, env: Option<PrivateEnvironment>) {
        let Some(_) = self
            .execution_context_stack
            .last_mut()
            .and_then(|s| s.ecmascript_code.as_mut())
            .map(|e| {
                e.private_environment = env.unbind();
            })
        else {
            panic_corrupted_agent()
        };
    }

    /// Allocates a range of PrivateName identifiers and returns the first in
    /// the range.
    pub(crate) fn create_private_names(&mut self, count: usize) -> PrivateName {
        let count = u32::try_from(count).expect("Unreasonable amount of PrivateNames");
        let first = self.private_names_counter;
        let next_free_name = first
            .checked_add(count)
            .expect("PrivateName counter overflowed");
        self.private_names_counter = next_free_name;
        PrivateName::from_u32(first)
    }

    /// ### [9.6.3 IncrementModuleAsyncEvaluationCount ( )](https://tc39.es/ecma262/#sec-IncrementModuleAsyncEvaluationCount)
    ///
    /// The abstract operation IncrementModuleAsyncEvaluationCount takes no
    /// arguments and returns an integer.
    ///
    /// > NOTE: This value is only used to keep track of the relative
    /// > evaluation order between pending modules. An implementation may
    /// > unobservably reset \[\[ModuleAsyncEvaluationCount]] to 0 whenever
    /// > there are no pending modules.
    pub(crate) fn increment_module_async_evaluation_count(&mut self) -> u32 {
        // 1. Let AR be the Agent Record of the surrounding agent.
        // 2. Let count be AR.[[ModuleAsyncEvaluationCount]].
        let count = self.module_async_evaluation_count;
        // 3. Set AR.[[ModuleAsyncEvaluationCount]] to count + 1.
        self.module_async_evaluation_count += 1;
        // 4. Return count.
        count
    }

    /// Panics if no active function object exists.
    pub(crate) fn active_function_object<'a>(&self, gc: NoGcScope<'a, '_>) -> Function<'a> {
        let Some(f) = self
            .execution_context_stack
            .last()
            .and_then(|s| s.function.bind(gc))
        else {
            panic_corrupted_agent()
        };
        f
    }

    /// ### [9.4.1 GetActiveScriptOrModule ( )](https://tc39.es/ecma262/#sec-getactivescriptormodule)
    ///
    /// The abstract operation GetActiveScriptOrModule takes no arguments and
    /// returns a Script Record, a Module Record, or null. It is used to
    /// determine the running script or module, based on the running execution
    /// context.
    pub(crate) fn get_active_script_or_module<'a>(
        &self,
        gc: NoGcScope<'a, '_>,
    ) -> Option<ScriptOrModule<'a>> {
        let Some(s) = self
            .execution_context_stack
            .last()
            .map(|s| s.script_or_module.bind(gc))
        else {
            panic_corrupted_agent()
        };
        s
    }

    /// Get access to the Host data, useful to share state between calls of built-in functions.
    ///
    /// # Panics
    ///
    /// Panics if the [`HostHooks::get_host_data`] hook was not implemented on
    /// the `host_hooks` parameter provided to [`GcAgent::new`].
    ///
    /// [`HostHooks::get_host_data`]: crate::ecmascript::HostHooks::get_host_data
    /// [`GcAgent::new`]: crate::ecmascript::GcAgent::new
    pub fn get_host_data(&self) -> &dyn Any {
        self.host_hooks.get_host_data()
    }

    /// Run a script in the current Realm.
    pub fn run_script<'gc>(
        &mut self,
        source_text: String,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, Value<'gc>> {
        let realm = self.current_realm(gc.nogc());
        let script = match parse_script(self, source_text, realm, false, None, gc.nogc()) {
            Ok(script) => script,
            Err(err) => {
                let gc = gc.into_nogc();
                let message =
                    String::from_string(self, err.first().unwrap().message.to_string(), gc);
                return Err(self.throw_exception_with_message(
                    ExceptionType::SyntaxError,
                    message,
                    gc,
                ));
            }
        };
        script_evaluation(self, script.unbind(), gc)
    }

    /// Run a SourceTextModule in the current Realm.
    ///
    /// This runs the LoadRequestedModules (passing in the host_defined
    /// parameter), Link, and finally Evaluate operations on the module.
    /// This should not be called multiple times on the same module.
    pub fn run_module<'gc>(
        &mut self,
        module: SourceTextModule,
        host_defined: Option<HostDefined>,
        mut gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, Value<'gc>> {
        let module = module.bind(gc.nogc());
        let Some(result) = module
            .load_requested_modules(self, host_defined, gc.nogc())
            .try_get_result(self, gc.nogc())
        else {
            return Err(self.throw_exception_with_static_message(
                ExceptionType::Error,
                "module was not sync",
                gc.into_nogc(),
            ));
        };
        result.unbind()?;

        module.link(self, gc.nogc()).unbind()?;
        if let Some(result) = module
            .unbind()
            .evaluate(self, gc.reborrow())
            .unbind()
            .try_get_result(self, gc.into_nogc())
        {
            // Note: module resolved synchronously.
            result
        } else {
            Ok(Value::Undefined)
        }
    }
}

/// ### [9.4.1 GetActiveScriptOrModule ()](https://tc39.es/ecma262/#sec-getactivescriptormodule)
///
/// The abstract operation GetActiveScriptOrModule takes no arguments and
/// returns a Script Record, a Module Record, or null. It is used to determine
/// the running script or module, based on the running execution context.
pub(crate) fn get_active_script_or_module<'a>(
    agent: &mut Agent,
    _: NoGcScope<'a, '_>,
) -> Option<ScriptOrModule<'a>> {
    if agent.execution_context_stack.is_empty() {
        return None;
    }
    agent
        .execution_context_stack
        .iter()
        .rev()
        .find_map(|context| context.script_or_module)
}

/// ### Try [9.4.2 ResolveBinding ( name \[ , env \] )](https://tc39.es/ecma262/#sec-resolvebinding)
///
/// The abstract operation ResolveBinding takes argument name (a String) and
/// optional argument env (an Environment Record or undefined) and returns
/// either a normal completion containing a Reference Record or a throw
/// completion. It is used to determine the binding of name. env can be used to
/// explicitly provide the Environment Record that is to be searched for the
/// binding.
pub(crate) fn try_resolve_binding<'a>(
    agent: &mut Agent,
    name: String<'a>,
    cache: Option<PropertyLookupCache<'a>>,
    gc: NoGcScope<'a, '_>,
) -> TryResult<'a, Reference<'a>> {
    // 1. If env is not present or env is undefined, then
    // a. Set env to the running execution context's LexicalEnvironment.
    let env = agent.current_lexical_environment(gc);

    // 2. Assert: env is an Environment Record.
    // Implicit from env's type.

    // 3. Let strict be IsStrict(the syntactic production that is being evaluated).
    let strict = agent.is_evaluating_strict_code();

    // 4. Return ? GetIdentifierReference(env, name, strict).
    try_get_identifier_reference(agent, env, name, cache, strict, gc)
}

/// ### [9.4.2 ResolveBinding ( name \[ , env \] )](https://tc39.es/ecma262/#sec-resolvebinding)
///
/// The abstract operation ResolveBinding takes argument name (a String) and
/// optional argument env (an Environment Record or undefined) and returns
/// either a normal completion containing a Reference Record or a throw
/// completion. It is used to determine the binding of name. env can be used to
/// explicitly provide the Environment Record that is to be searched for the
/// binding.
pub(crate) fn resolve_binding<'a, 'b>(
    agent: &mut Agent,
    name: String<'b>,
    cache: Option<PropertyLookupCache<'a>>,
    env: Option<Environment>,
    gc: GcScope<'a, 'b>,
) -> JsResult<'a, Reference<'a>> {
    let name = name.bind(gc.nogc());
    let env = env
        .unwrap_or_else(|| {
            // 1. If env is not present or env is undefined, then
            //    a. Set env to the running execution context's LexicalEnvironment.
            agent.current_lexical_environment(gc.nogc())
        })
        .bind(gc.nogc());
    let cache = cache.bind(gc.nogc());

    // 2. Assert: env is an Environment Record.
    // Implicit from env's type.

    // 3. Let strict be IsStrict(the syntactic production that is being evaluated).
    let strict = agent.is_evaluating_strict_code();

    // 4. Return ? GetIdentifierReference(env, name, strict).
    get_identifier_reference(
        agent,
        Some(env.unbind()),
        name.unbind(),
        cache.unbind(),
        strict,
        gc,
    )
}

/// Native error types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExceptionType {
    /// ### [19.3.10 Error ( . . . )](https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object-error)
    Error,
    /// ### [19.3.1 AggregateError ( . . . )](https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object-aggregate-error)
    AggregateError,
    /// ### [19.3.11 EvalError ( . . . )](https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object-evalerror)
    EvalError,
    /// ### [19.3.26 RangeError ( . . . )](https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object-rangeerror)
    RangeError,
    /// ### [19.3.27 ReferenceError ( . . . )](https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object-referenceerror)
    ReferenceError,
    /// ### [19.3.33 SyntaxError ( . . . )](https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object-syntaxerror)
    SyntaxError,
    /// ### [19.3.34 TypeError ( . . . )](https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object-typeerror)
    TypeError,
    /// ### [19.3.39 URIError ( . . . )](https://tc39.es/ecma262/#sec-constructor-properties-of-the-global-object-urierror)
    UriError,
}

impl TryFrom<u16> for ExceptionType {
    type Error = ();

    fn try_from(value: u16) -> Result<Self, ()> {
        match value {
            0 => Ok(Self::Error),
            1 => Ok(Self::AggregateError),
            2 => Ok(Self::EvalError),
            3 => Ok(Self::RangeError),
            4 => Ok(Self::ReferenceError),
            5 => Ok(Self::SyntaxError),
            6 => Ok(Self::TypeError),
            7 => Ok(Self::UriError),
            _ => Err(()),
        }
    }
}

impl PrimitiveHeapAccess for Agent {}

impl HeapMarkAndSweep for Agent {
    fn mark_values(&self, queues: &mut WorkQueues) {
        let Self {
            heap,
            execution_context_stack,
            stack_refs,
            stack_ref_collections,
            vm_stack,
            options: _,
            symbol_id: _,
            global_symbol_registry,
            host_hooks: _,
            #[cfg(feature = "weak-refs")]
                kept_alive: _,
            private_names_counter: _,
            module_async_evaluation_count: _,
        } = self;

        execution_context_stack.iter().for_each(|ctx| {
            ctx.mark_values(queues);
        });
        stack_refs
            .borrow()
            .iter()
            .for_each(|value| value.mark_values(queues));
        stack_ref_collections
            .borrow()
            .iter()
            .for_each(|collection| collection.mark_values(queues));
        vm_stack.iter().for_each(|vm_ptr| {
            unsafe { vm_ptr.as_ref() }.mark_values(queues);
        });
        global_symbol_registry.mark_values(queues);
        let mut last_filled_global_value = None;
        heap.globals
            .borrow()
            .iter()
            .enumerate()
            .for_each(|(i, &value)| {
                if value != HeapRootData::Empty {
                    value.mark_values(queues);
                    last_filled_global_value = Some(i);
                }
            });
        // Remove as many `None` global values without moving any `Some(Value)` values.
        if let Some(last_filled_global_value) = last_filled_global_value {
            heap.globals
                .borrow_mut()
                .truncate(last_filled_global_value + 1);
        }
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        let Agent {
            heap: _,
            execution_context_stack,
            stack_refs,
            stack_ref_collections,
            vm_stack,
            options: _,
            symbol_id: _,
            global_symbol_registry,
            host_hooks: _,
            #[cfg(feature = "weak-refs")]
                kept_alive: _,
            private_names_counter: _,
            module_async_evaluation_count: _,
        } = self;

        execution_context_stack
            .iter_mut()
            .for_each(|entry| entry.sweep_values(compactions));
        stack_refs
            .borrow_mut()
            .iter_mut()
            .for_each(|entry| entry.sweep_values(compactions));
        stack_ref_collections
            .borrow_mut()
            .iter_mut()
            .for_each(|entry| entry.sweep_values(compactions));
        vm_stack
            .iter_mut()
            .for_each(|entry| unsafe { entry.as_mut().sweep_values(compactions) });
        global_symbol_registry.sweep_values(compactions);
    }
}

#[cold]
#[inline(never)]
fn panic_corrupted_agent() -> ! {
    panic!("Agent is corrupted")
}