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
// 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.1 Environment Records](https://tc39.es/ecma262/#sec-environment-records)
//!
//! Environment Record is a specification type used to define the association of
//! Identifiers to specific variables and functions, based upon the lexical
//! nesting structure of ECMAScript code. Usually an Environment Record is
//! associated with some specific syntactic structure of ECMAScript code such as
//! a FunctionDeclaration, a BlockStatement, or a Catch clause of a
//! TryStatement. Each time such code is evaluated, a new Environment Record is
//! created to record the identifier bindings that are created by that code.
//!
//! Every Environment Record has an \[\[OuterEnv\]\] field, which is either null or
//! a reference to an outer Environment Record. This is used to model the
//! logical nesting of Environment Record values. The outer reference of an
//! (inner) Environment Record is a reference to the Environment Record that
//! logically surrounds the inner Environment Record. An outer Environment
//! Record may, of course, have its own outer Environment Record. An Environment
//! Record may serve as the outer environment for multiple inner Environment
//! Records. For example, if a FunctionDeclaration contains two nested
//! FunctionDeclarations then the Environment Records of each of the nested
//! functions will have as their outer Environment Record the Environment Record
//! of the current evaluation of the surrounding function.

mod declarative_environment;
mod function_environment;
mod global_environment;
mod module_environment;
mod object_environment;
mod private_environment;

pub(crate) use declarative_environment::*;
pub(crate) use function_environment::*;
pub(crate) use global_environment::*;
pub(crate) use module_environment::*;
pub(crate) use object_environment::*;
pub(crate) use private_environment::*;

use std::ops::ControlFlow;

use crate::{
    ecmascript::{
        Agent, InternalMethods, JsResult, Object, PropertyLookupCache, Proxy, Reference, SetResult,
        String, TryError, TryHasResult, TryResult, Value, js_result_into_try,
    },
    engine::{Bindable, GcScope, HeapRootData, NoGcScope, Scopable, bindable_handle},
    heap::{CompactionLists, HeapIndexHandle, HeapMarkAndSweep, WorkQueues},
};

/// ### [\[\[OuterEnv\]\]](https://tc39.es/ecma262/#sec-environment-records)
///
/// Every Environment Record has an \[\[OuterEnv\]\] field, which is either
/// null or a reference to an outer Environment Record. This is used to model
/// the logical nesting of Environment Record values. The outer reference of an
/// (inner) Environment Record is a reference to the Environment Record that
/// logically surrounds the inner Environment Record. An outer Environment
/// Record may, of course, have its own outer Environment Record. An
/// Environment Record may serve as the outer environment for multiple inner
/// Environment Records. For example, if a FunctionDeclaration contains two
/// nested FunctionDeclarations then the Environment Records of each of the
/// nested functions will have as their outer Environment Record the
/// Environment Record of the current evaluation of the surrounding function.
pub(crate) type OuterEnv<'a> = Option<Environment<'a>>;

macro_rules! create_environment_index {
    ($record: ident, $index: ident, $entry: ident) => {
        /// An index used to access an environment from [`Environments`].
        /// Internally, we store the index in a [`NonZeroU32`] with the index
        /// plus one. This allows us to not use an empty value in storage for
        /// the zero index while still saving room for a [`None`] value when
        /// stored in an [`Option`].
        ///
        /// [`NonZeroU32`]: core::num::NonZeroU32
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        #[repr(transparent)]
        pub(crate) struct $index<'a>(crate::heap::BaseIndex<'a, $record>);
        crate::heap::index_handle!($index);

        impl core::fmt::Debug for $index<'_> {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(
                    f,
                    "$index({:?})",
                    crate::heap::HeapIndexHandle::get_index_u32(*self)
                )
            }
        }

        impl<'a> crate::heap::DirectArenaAccess for $index<'a> {
            type Data = $record;
            type Output = $record;

            #[inline]
            fn get_direct(self, source: &Vec<Self::Data>) -> &Self::Output {
                source
                    .get(crate::heap::HeapIndexHandle::get_index(self))
                    .expect("Invalid environment handle")
            }
        }

        impl<'a> crate::heap::DirectArenaAccessMut for $index<'a> {
            #[inline]
            fn get_direct_mut(self, source: &mut Vec<Self::Data>) -> &mut Self::Output {
                source
                    .get_mut(crate::heap::HeapIndexHandle::get_index(self))
                    .expect("Invalid environment handle")
            }
        }

        impl AsRef<Vec<$record>> for crate::ecmascript::execution::Agent {
            #[inline(always)]
            fn as_ref(&self) -> &Vec<$record> {
                &self.heap.environments.$entry
            }
        }

        impl AsMut<Vec<$record>> for crate::ecmascript::execution::Agent {
            #[inline(always)]
            fn as_mut(&mut self) -> &mut Vec<$record> {
                &mut self.heap.environments.$entry
            }
        }
    };
}

create_environment_index!(
    DeclarativeEnvironmentRecord,
    DeclarativeEnvironment,
    declarative
);
create_environment_index!(FunctionEnvironmentRecord, FunctionEnvironment, function);
create_environment_index!(GlobalEnvironmentRecord, GlobalEnvironment, global);
create_environment_index!(ObjectEnvironmentRecord, ObjectEnvironment, object);
create_environment_index!(ModuleEnvironmentRecord, ModuleEnvironment, module);
create_environment_index!(PrivateEnvironmentRecord, PrivateEnvironment, private);

impl<'a> From<DeclarativeEnvironment<'a>> for Environment<'a> {
    fn from(value: DeclarativeEnvironment<'a>) -> Self {
        Environment::Declarative(value)
    }
}

impl<'a> From<GlobalEnvironment<'a>> for Environment<'a> {
    fn from(value: GlobalEnvironment<'a>) -> Self {
        Environment::Global(value)
    }
}

impl<'a> From<ModuleEnvironment<'a>> for Environment<'a> {
    fn from(value: ModuleEnvironment<'a>) -> Self {
        Environment::Module(value)
    }
}

impl<'a> From<ObjectEnvironment<'a>> for Environment<'a> {
    fn from(value: ObjectEnvironment<'a>) -> Self {
        Environment::Object(value)
    }
}

/// ### [9.1.1 The Environment Record Type Hierarchy](https://tc39.es/ecma262/#sec-the-environment-record-type-hierarchy)
///
/// Environment Records can be thought of as existing in a simple
/// object-oriented hierarchy where Environment Record is an abstract class
/// with three concrete subclasses: Declarative Environment Record, Object
/// Environment Record, and Global Environment Record. Function Environment
/// Records and Module Environment Records are subclasses of Declarative
/// Environment Record.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum Environment<'a> {
    // Leave 0 for None option
    Declarative(DeclarativeEnvironment<'a>) = 1,
    Function(FunctionEnvironment<'a>),
    Global(GlobalEnvironment<'a>),
    Module(ModuleEnvironment<'a>),
    Object(ObjectEnvironment<'a>),
}
bindable_handle!(Environment);

impl<'e> Environment<'e> {
    pub(crate) fn get_outer_env(self, agent: &Agent) -> OuterEnv<'e> {
        match self {
            Environment::Declarative(e) => e.get_outer_env(agent),
            Environment::Function(e) => e.get_outer_env(agent),
            Environment::Global(_) => None,
            Environment::Module(e) => e.get_outer_env(agent),
            Environment::Object(e) => e.get_outer_env(agent),
        }
    }

    /// ### Try [HasBinding(N)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Determine if an Environment Record has a binding for the String value
    /// N. Return true if it does and false if it does not.
    pub(crate) fn try_has_binding<'gc>(
        self,
        agent: &mut Agent,
        name: String,
        cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> ControlFlow<TryError<'gc>, TryHasBindingContinue<'gc>> {
        match self {
            Environment::Declarative(e) => {
                TryHasBindingContinue::Result(e.has_binding(agent, name)).into()
            }
            Environment::Function(e) => {
                TryHasBindingContinue::Result(e.has_binding(agent, name)).into()
            }
            Environment::Global(e) => e.try_has_binding(agent, name, cache, gc),
            Environment::Module(e) => {
                TryHasBindingContinue::Result(e.has_binding(agent, name)).into()
            }
            Environment::Object(e) => e.try_has_binding(agent, name, cache, gc),
        }
    }

    /// # [HasBinding(N)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Determine if an Environment Record has a binding for the String value
    /// N. Return true if it does and false if it does not.
    pub(crate) fn has_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        gc: GcScope<'a, '_>,
    ) -> JsResult<'a, bool> {
        match self {
            Environment::Declarative(e) => Ok(e.has_binding(agent, name)),
            Environment::Function(e) => Ok(e.has_binding(agent, name)),
            Environment::Global(e) => e.has_binding(agent, name, gc),
            Environment::Module(e) => Ok(e.has_binding(agent, name)),
            Environment::Object(e) => e.has_binding(agent, name, gc),
        }
    }

    /// ### Try [CreateMutableBinding(N, D)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Create a new but uninitialized mutable binding in an Environment
    /// Record. The String value N is the text of the bound name. If the
    /// Boolean argument D is true the binding may be subsequently deleted.
    pub(crate) fn try_create_mutable_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        is_deletable: bool,
        cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'a, '_>,
    ) -> TryResult<'a, ()> {
        match self {
            Environment::Declarative(e) => {
                e.create_mutable_binding(agent, name, is_deletable);
                TryResult::Continue(())
            }
            Environment::Function(e) => {
                e.create_mutable_binding(agent, name, is_deletable);
                TryResult::Continue(())
            }
            Environment::Global(e) => {
                js_result_into_try(e.create_mutable_binding(agent, name, is_deletable, gc))
            }
            Environment::Module(e) => {
                e.create_mutable_binding(agent, name, is_deletable);
                TryResult::Continue(())
            }
            Environment::Object(e) => {
                e.try_create_mutable_binding(agent, name, is_deletable, cache, gc)
            }
        }
    }

    /// # [CreateMutableBinding(N, D)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Create a new but uninitialized mutable binding in an Environment
    /// Record. The String value N is the text of the bound name. If the
    /// Boolean argument D is true the binding may be subsequently deleted.
    pub(crate) fn create_mutable_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        is_deletable: bool,
        gc: GcScope<'a, '_>,
    ) -> JsResult<'a, ()> {
        match self {
            Environment::Declarative(e) => {
                e.create_mutable_binding(agent, name, is_deletable);
                Ok(())
            }
            Environment::Function(e) => {
                e.create_mutable_binding(agent, name, is_deletable);
                Ok(())
            }
            Environment::Global(e) => {
                e.create_mutable_binding(agent, name, is_deletable, gc.into_nogc())
            }
            Environment::Module(e) => {
                e.create_mutable_binding(agent, name, is_deletable);
                Ok(())
            }
            Environment::Object(e) => e.create_mutable_binding(agent, name, is_deletable, gc),
        }
    }

    /// # [CreateImmutableBinding(N, S)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Create a new but uninitialized immutable binding in an Environment
    /// Record. The String value N is the text of the bound name. If S is true
    /// then attempts to set it after it has been initialized will always throw
    /// an exception, regardless of the strict mode setting of operations that
    /// reference that binding.
    pub(crate) fn create_immutable_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        is_strict: bool,
        gc: NoGcScope<'a, '_>,
    ) -> JsResult<'a, ()> {
        match self {
            Environment::Declarative(e) => {
                e.create_immutable_binding(agent, name, is_strict);
                Ok(())
            }
            Environment::Function(e) => {
                e.create_immutable_binding(agent, name, is_strict);
                Ok(())
            }
            Environment::Global(e) => e.create_immutable_binding(agent, name, is_strict, gc),
            Environment::Module(e) => {
                debug_assert!(is_strict);
                e.create_immutable_binding(agent, name);
                Ok(())
            }
            Environment::Object(e) => {
                e.create_immutable_binding(agent, name, is_strict);
                Ok(())
            }
        }
    }

    /// ### Try [InitializeBinding(N, V)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Set the value of an already existing but uninitialized binding in an
    /// Environment Record. The String value N is the text of the bound name.
    /// V is the value for the binding and is a value of any ECMAScript
    /// language type.
    pub(crate) fn try_initialize_binding<'gc>(
        self,
        agent: &mut Agent,
        name: String,
        cache: Option<PropertyLookupCache>,
        value: Value,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, SetResult<'gc>> {
        match self {
            Environment::Declarative(e) => {
                e.initialize_binding(agent, name, value);
                SetResult::Done.into()
            }
            Environment::Function(e) => {
                e.initialize_binding(agent, name, value);
                SetResult::Done.into()
            }
            Environment::Global(e) => e.try_initialize_binding(agent, name, cache, value, gc),
            Environment::Module(e) => {
                e.initialize_binding(agent, name, value);
                SetResult::Done.into()
            }
            Environment::Object(e) => e.try_initialize_binding(agent, name, cache, value, gc),
        }
    }

    /// # [InitializeBinding(N, V)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Set the value of an already existing but uninitialized binding in an
    /// Environment Record. The String value N is the text of the bound name.
    /// V is the value for the binding and is a value of any ECMAScript
    /// language type.
    pub(crate) fn initialize_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        cache: Option<PropertyLookupCache>,
        value: Value,
        gc: GcScope<'a, '_>,
    ) -> JsResult<'a, ()> {
        match self {
            Environment::Declarative(e) => {
                e.initialize_binding(agent, name, value);
                Ok(())
            }
            Environment::Function(e) => {
                e.initialize_binding(agent, name, value);
                Ok(())
            }
            Environment::Global(e) => e.initialize_binding(agent, name, cache, value, gc),
            Environment::Module(e) => {
                e.initialize_binding(agent, name, value);
                Ok(())
            }
            Environment::Object(e) => e.initialize_binding(agent, name, cache, value, gc),
        }
    }

    /// ### Try [SetMutableBinding(N, V, S)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Set the value of an already existing mutable binding in an Environment
    /// Record. The String value N is the text of the bound name. V is the
    /// value for the binding and may be a value of any ECMAScript language
    /// type. S is a Boolean flag. If S is true and the binding cannot be set
    /// throw a TypeError exception.
    pub(crate) fn try_set_mutable_binding<'gc>(
        self,
        agent: &mut Agent,
        name: String,
        cache: Option<PropertyLookupCache>,
        value: Value,
        is_strict: bool,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, SetResult<'gc>> {
        match self {
            Environment::Declarative(e) => js_result_into_try(
                e.set_mutable_binding(agent, name, value, is_strict, gc)
                    .map(|_| SetResult::Done),
            ),
            Environment::Function(e) => js_result_into_try(
                e.set_mutable_binding(agent, name, value, is_strict, gc)
                    .map(|_| SetResult::Done),
            ),
            Environment::Global(e) => {
                e.try_set_mutable_binding(agent, name, cache, value, is_strict, gc)
            }
            Environment::Module(e) => {
                debug_assert!(is_strict);
                js_result_into_try(
                    e.set_mutable_binding(agent, name, value, gc)
                        .map(|_| SetResult::Done),
                )
            }
            Environment::Object(e) => {
                e.try_set_mutable_binding(agent, name, cache, value, is_strict, gc)
            }
        }
    }

    /// # [SetMutableBinding(N, V, S)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Set the value of an already existing mutable binding in an Environment
    /// Record. The String value N is the text of the bound name. V is the
    /// value for the binding and may be a value of any ECMAScript language
    /// type. S is a Boolean flag. If S is true and the binding cannot be set
    /// throw a TypeError exception.
    pub(crate) fn set_mutable_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        cache: Option<PropertyLookupCache>,
        value: Value,
        is_strict: bool,
        gc: GcScope<'a, '_>,
    ) -> JsResult<'a, ()> {
        match self {
            Environment::Declarative(e) => {
                e.set_mutable_binding(agent, name, value, is_strict, gc.into_nogc())
            }
            Environment::Function(e) => {
                e.set_mutable_binding(agent, name, value, is_strict, gc.into_nogc())
            }
            Environment::Global(e) => {
                e.set_mutable_binding(agent, name, cache, value, is_strict, gc)
            }
            Environment::Module(e) => e.set_mutable_binding(agent, name, value, gc.into_nogc()),
            Environment::Object(e) => {
                e.set_mutable_binding(agent, name, cache, value, is_strict, gc)
            }
        }
    }

    /// ### Try [GetBindingValue(N, S)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Returns the value of an already existing binding from an Environment
    /// Record. The String value N is the text of the bound name. S is used to
    /// identify references originating in strict mode code or that otherwise
    /// require strict mode reference semantics. If S is true and the binding
    /// does not exist throw a ReferenceError exception. If the binding exists
    /// but is uninitialized a ReferenceError is thrown, regardless of the
    /// value of S.
    pub(crate) fn try_get_binding_value(
        self,
        agent: &mut Agent,
        name: String,
        cache: Option<PropertyLookupCache>,
        is_strict: bool,
        gc: NoGcScope<'e, '_>,
    ) -> TryResult<'e, Value<'e>> {
        match self {
            Environment::Declarative(e) => {
                js_result_into_try(e.get_binding_value(agent, name, is_strict, gc))
            }
            Environment::Function(e) => {
                js_result_into_try(e.get_binding_value(agent, name, is_strict, gc))
            }
            Environment::Global(e) => e.try_get_binding_value(agent, name, cache, is_strict, gc),
            Environment::Module(e) => e.try_get_binding_value(agent, name, is_strict, gc),
            Environment::Object(e) => e.try_get_binding_value(agent, name, cache, is_strict, gc),
        }
    }

    /// # [GetBindingValue(N, S)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Returns the value of an already existing binding from an Environment
    /// Record. The String value N is the text of the bound name. S is used to
    /// identify references originating in strict mode code or that otherwise
    /// require strict mode reference semantics. If S is true and the binding
    /// does not exist throw a ReferenceError exception. If the binding exists
    /// but is uninitialized a ReferenceError is thrown, regardless of the
    /// value of S.
    pub(crate) fn get_binding_value<'a>(
        self,
        agent: &mut Agent,
        name: String,
        is_strict: bool,
        gc: GcScope<'a, '_>,
    ) -> JsResult<'a, Value<'a>> {
        match self {
            Environment::Declarative(e) => {
                let gc = gc.into_nogc();
                e.bind(gc).get_binding_value(agent, name, is_strict, gc)
            }
            Environment::Function(e) => {
                let gc = gc.into_nogc();
                e.bind(gc).get_binding_value(agent, name, is_strict, gc)
            }
            Environment::Global(e) => e.get_binding_value(agent, name, is_strict, gc),
            Environment::Module(e) => {
                let gc = gc.into_nogc();
                e.bind(gc)
                    .env_get_binding_value(agent, name, is_strict, gc.into_nogc())
            }
            Environment::Object(e) => e.get_binding_value(agent, name, is_strict, gc),
        }
    }

    /// ### Try [DeleteBinding(N)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Delete a binding from an Environment Record. The String value N is the
    /// text of the bound name. If a binding for N exists, remove the binding
    /// and return true. If the binding exists but cannot be removed return
    /// false.
    pub(crate) fn try_delete_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        gc: NoGcScope<'a, '_>,
    ) -> TryResult<'a, bool> {
        match self {
            Environment::Declarative(e) => TryResult::Continue(e.delete_binding(agent, name)),
            Environment::Function(e) => TryResult::Continue(e.delete_binding(agent, name)),
            Environment::Global(e) => e.try_delete_binding(agent, name, gc),
            // NOTE: Module Environment Records are only used within strict
            // code and an early error rule prevents the delete operator, in
            // strict code, from being applied to a Reference Record that would
            // resolve to a Module Environment Record binding. See 13.5.1.1.
            Environment::Module(_) => unreachable!(),
            Environment::Object(e) => TryResult::Continue(e.try_delete_binding(agent, name, gc)?),
        }
    }

    /// # [DeleteBinding(N)](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Delete a binding from an Environment Record. The String value N is the
    /// text of the bound name. If a binding for N exists, remove the binding
    /// and return true. If the binding exists but cannot be removed return
    /// false.
    pub(crate) fn delete_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        gc: GcScope<'a, '_>,
    ) -> JsResult<'a, bool> {
        match self {
            Environment::Declarative(e) => Ok(e.delete_binding(agent, name)),
            Environment::Function(e) => Ok(e.delete_binding(agent, name)),
            Environment::Global(e) => e.delete_binding(agent, name, gc),
            // NOTE: Module Environment Records are only used within strict
            // code and an early error rule prevents the delete operator, in
            // strict code, from being applied to a Reference Record that would
            // resolve to a Module Environment Record binding. See 13.5.1.1.
            Environment::Module(_) => unreachable!(),
            Environment::Object(e) => e.delete_binding(agent, name, gc),
        }
    }

    /// # [HasThisBinding()](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Determine if an Environment Record establishes a this binding. Return
    /// true if it does and false if it does not.
    pub(crate) fn has_this_binding(self, agent: &Agent) -> bool {
        match self {
            Environment::Declarative(_) => false,
            Environment::Function(e) => e.has_this_binding(agent),
            Environment::Global(_) => true,
            Environment::Module(_) => true,
            Environment::Object(_) => false,
        }
    }

    /// Get the `this` binding value of this environment.
    ///
    /// ## Panics
    ///
    /// Panics if the environment does not have a `this` binding.
    pub(crate) fn get_this_binding(
        self,
        agent: &mut Agent,
        gc: NoGcScope<'e, '_>,
    ) -> JsResult<'e, Value<'e>> {
        match self {
            Environment::Function(e) => e.get_this_binding(agent, gc),
            Environment::Global(e) => Ok(e.get_this_binding(agent).into()),
            Environment::Module(_) => Ok(Value::Undefined),
            _ => unreachable!(),
        }
    }

    /// # [HasSuperBinding()](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// Determine if an Environment Record establishes a super method binding.
    /// Return true if it does and false if it does not.
    pub(crate) fn has_super_binding(self, agent: &mut Agent) -> bool {
        match self {
            Environment::Function(e) => e.has_super_binding(agent),
            _ => false,
        }
    }

    /// # [WithBaseObject()](https://tc39.es/ecma262/#table-abstract-methods-of-environment-records)
    ///
    /// If this Environment Record is associated with a with statement, return
    /// the with object. Otherwise, return undefined.
    pub(crate) fn with_base_object(self, agent: &mut Agent) -> Option<Object<'e>> {
        match self {
            Environment::Object(e) => e.with_base_object(agent),
            _ => None,
        }
    }
}

impl core::fmt::Debug for Environment<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Environment::Declarative(d) => {
                write!(f, "DeclarativeEnvironment({:?})", d.get_index_u32())
            }
            Environment::Function(d) => write!(f, "FunctionEnvironment({:?})", d.get_index_u32()),
            Environment::Global(d) => write!(f, "GlobalEnvironment({:?})", d.get_index_u32()),
            Environment::Module(d) => write!(f, "ModuleEnvironment({:?})", d.get_index_u32()),
            Environment::Object(d) => write!(f, "ObjectEnvironment({:?})", d.get_index_u32()),
            // EnvironmentIndex::Module(d) => {}
        }
    }
}

impl From<Environment<'_>> for HeapRootData {
    fn from(value: Environment<'_>) -> Self {
        match value {
            Environment::Declarative(e) => Self::from(e),
            Environment::Function(e) => Self::from(e),
            Environment::Global(e) => Self::from(e),
            Environment::Module(e) => Self::from(e),
            Environment::Object(e) => Self::from(e),
        }
    }
}

impl TryFrom<HeapRootData> for Environment<'_> {
    type Error = ();

    fn try_from(value: HeapRootData) -> Result<Self, Self::Error> {
        match value {
            HeapRootData::DeclarativeEnvironment(e) => Ok(Self::Declarative(e)),
            HeapRootData::FunctionEnvironment(e) => Ok(Self::Function(e)),
            HeapRootData::GlobalEnvironment(e) => Ok(Self::Global(e)),
            HeapRootData::ModuleEnvironment(e) => Ok(Self::Module(e)),
            HeapRootData::ObjectEnvironment(e) => Ok(Self::Object(e)),
            _ => Err(()),
        }
    }
}

impl HeapMarkAndSweep for Environment<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        match self {
            Environment::Declarative(e) => e.mark_values(queues),
            Environment::Function(e) => e.mark_values(queues),
            Environment::Global(e) => e.mark_values(queues),
            Environment::Module(e) => e.mark_values(queues),
            Environment::Object(e) => e.mark_values(queues),
        }
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        match self {
            Environment::Declarative(e) => e.sweep_values(compactions),
            Environment::Function(e) => e.sweep_values(compactions),
            Environment::Global(e) => e.sweep_values(compactions),
            Environment::Module(e) => e.sweep_values(compactions),
            Environment::Object(e) => e.sweep_values(compactions),
        }
    }
}

#[derive(Debug)]
pub(crate) struct Environments {
    pub(crate) declarative: Vec<DeclarativeEnvironmentRecord>,
    pub(crate) function: Vec<FunctionEnvironmentRecord>,
    pub(crate) global: Vec<GlobalEnvironmentRecord>,
    pub(crate) object: Vec<ObjectEnvironmentRecord>,
    pub(crate) module: Vec<ModuleEnvironmentRecord>,
    pub(crate) private: Vec<PrivateEnvironmentRecord>,
}

impl Default for Environments {
    fn default() -> Self {
        Self {
            declarative: Vec::with_capacity(256),
            function: Vec::with_capacity(1024),
            global: Vec::with_capacity(1),
            object: Vec::with_capacity(1024),
            module: Vec::with_capacity(8),
            private: Vec::with_capacity(0),
        }
    }
}

/// Result of the HasBinding abstract operation's Try variant.
///
/// > Note: we could return eg. the exact object and offset that a property was
/// > found at, and cache that for later usage. Experiments showed that it did
/// > not have a meaningful impact on performance at that time.
pub(crate) enum TryHasBindingContinue<'a> {
    Result(bool),
    /// A Proxy trap call is needed.
    ///
    /// This means that the method ran to completion but could not call the
    /// Proxy trap itself.
    Proxy(Proxy<'a>),
}
bindable_handle!(TryHasBindingContinue);

impl<'a> TryFrom<TryHasBindingContinue<'a>> for bool {
    type Error = Proxy<'a>;

    fn try_from(value: TryHasBindingContinue<'a>) -> Result<Self, Self::Error> {
        match value {
            TryHasBindingContinue::Result(bool) => Ok(bool),
            TryHasBindingContinue::Proxy(proxy) => Err(proxy),
        }
    }
}

impl<'a> From<TryHasResult<'a>> for TryHasBindingContinue<'a> {
    fn from(value: TryHasResult<'a>) -> Self {
        match value {
            TryHasResult::Unset => Self::Result(false),
            TryHasResult::Offset(_, _) | TryHasResult::Custom(_, _) => Self::Result(true),
            TryHasResult::Proxy(proxy) => Self::Proxy(proxy),
        }
    }
}

impl<'a> From<TryHasResult<'a>> for TryResult<'a, TryHasBindingContinue<'a>> {
    fn from(value: TryHasResult<'a>) -> Self {
        Self::Continue(value.into())
    }
}

impl<'a> From<TryHasBindingContinue<'a>> for TryResult<'a, TryHasBindingContinue<'a>> {
    fn from(value: TryHasBindingContinue<'a>) -> Self {
        Self::Continue(value)
    }
}

/// ### Try [9.1.2.1 GetIdentifierReference ( env, name, strict )](https://tc39.es/ecma262/#sec-getidentifierreference)
///
/// The abstract operation GetIdentifierReference takes arguments env (an
/// Environment Record or null), name (a String), and strict (a Boolean) and
/// returns either a normal completion containing a Reference Record or a throw
/// completion.
pub(crate) fn try_get_identifier_reference<'a>(
    agent: &mut Agent,
    env: Environment,
    name: String,
    cache: Option<PropertyLookupCache>,
    strict: bool,
    gc: NoGcScope<'a, '_>,
) -> TryResult<'a, Reference<'a>> {
    let env = env.bind(gc);
    let name = name.bind(gc);
    let cache = cache.bind(gc);
    // 1. If env is null, then
    // 2. Let exists be ? env.HasBinding(name).
    let exists = if let ControlFlow::Continue(TryHasBindingContinue::Result(exists)) =
        env.try_has_binding(agent, name, cache, gc)
    {
        exists
    } else {
        return TryError::GcError.into();
    };

    // 3. If exists is true, then
    if exists {
        // a. Return the Reference Record {
        // [[ReferencedName]]: name,
        // [[Base]]: env,
        // [[Strict]]: strict,
        TryResult::Continue(Reference::new_variable_reference(env, name, cache, strict))
        // [[ThisValue]]: EMPTY
        // }.
    }
    // 4. Else,
    else {
        // a. Let outer be env.[[OuterEnv]].
        let outer = env.get_outer_env(agent);

        let Some(outer) = outer else {
            // a. Return the Reference Record {
            // [[Base]]: UNRESOLVABLE,
            // [[ReferencedName]]: name,
            // [[Strict]]: strict,
            return TryResult::Continue(Reference::new_unresolvable_reference(name, strict));
            // [[ThisValue]]: EMPTY
            // }.
        };

        // b. Return ? GetIdentifierReference(outer, name, strict).
        try_get_identifier_reference(agent, outer, name, cache, strict, gc)
    }
}

/// ### [9.1.2.1 GetIdentifierReference ( env, name, strict )](https://tc39.es/ecma262/#sec-getidentifierreference)
///
/// The abstract operation GetIdentifierReference takes arguments env (an
/// Environment Record or null), name (a String), and strict (a Boolean) and
/// returns either a normal completion containing a Reference Record or a throw
/// completion.
pub(crate) fn get_identifier_reference<'a, 'b>(
    agent: &mut Agent,
    env: Option<Environment>,
    name: String,
    cache: Option<PropertyLookupCache>,
    strict: bool,
    mut gc: GcScope<'a, 'b>,
) -> JsResult<'a, Reference<'a>> {
    let env = env.bind(gc.nogc());
    let mut name = name.bind(gc.nogc());
    let mut cache = cache.bind(gc.nogc());

    // 1. If env is null, then
    let Some(mut env) = env else {
        let name = name.unbind().bind(gc.into_nogc());
        // a. Return the Reference Record {
        // [[Base]]: UNRESOLVABLE,
        // [[ReferencedName]]: name,
        // [[Strict]]: strict,
        return Ok(Reference::new_unresolvable_reference(name, strict));
        // [[ThisValue]]: EMPTY
        // }.
    };

    // 2. Let exists be ? env.HasBinding(name).
    let exists = env.try_has_binding(agent, name, cache, gc.nogc());
    let exists = if let ControlFlow::Continue(TryHasBindingContinue::Result(exists)) = exists {
        exists
    } else {
        let env_scoped = env.scope(agent, gc.nogc());
        let name_scoped = name.scope(agent, gc.nogc());
        let cache_scoped = cache.map(|c| c.scope(agent, gc.nogc()));
        let exists = handle_try_has_binding_result_cold(
            agent,
            env.unbind(),
            name.unbind(),
            exists.unbind(),
            gc.reborrow(),
        )
        .unbind()?
        .bind(gc.nogc());
        // SAFETY: not shared.
        unsafe {
            cache = cache_scoped.map(|c| c.take(agent));
            name = name_scoped.take(agent);
            env = env_scoped.take(agent);
        }
        exists
    };

    // 3. If exists is true, then
    if exists {
        // a. Return the Reference Record {
        // [[Base]]: env,
        // [[ReferencedName]]: name,
        // [[Strict]]: strict,
        Ok(Reference::new_variable_reference(env, name, cache, strict).unbind())
        // [[ThisValue]]: EMPTY
        // }.
    }
    // 4. Else,
    else {
        // a. Let outer be env.[[OuterEnv]].
        let outer = env.get_outer_env(agent);

        // b. Return ? GetIdentifierReference(outer, name, strict).
        get_identifier_reference(
            agent,
            outer.unbind(),
            name.unbind(),
            cache.unbind(),
            strict,
            gc,
        )
    }
}

#[cold]
#[inline(never)]
fn handle_try_has_binding_result_cold<'a>(
    agent: &mut Agent,
    env: Environment,
    name: String,
    exists: ControlFlow<TryError, TryHasBindingContinue>,
    gc: GcScope<'a, '_>,
) -> JsResult<'a, bool> {
    match exists {
        ControlFlow::Continue(c) => match c {
            TryHasBindingContinue::Result(exists) => Ok(exists),
            TryHasBindingContinue::Proxy(proxy) => {
                proxy
                    .unbind()
                    .internal_has_property(agent, name.to_property_key(), gc)
            }
        },
        ControlFlow::Break(b) => match b {
            TryError::Err(err) => Err(err.unbind().bind(gc.into_nogc())),
            _ => env.unbind().has_binding(agent, name.unbind(), gc),
        },
    }
}

impl Environments {
    pub(crate) fn push_declarative_environment<'a>(
        &mut self,
        env: DeclarativeEnvironmentRecord,
        _: NoGcScope<'a, '_>,
    ) -> DeclarativeEnvironment<'a> {
        self.declarative.push(env);
        DeclarativeEnvironment::from_index_u32(self.declarative.len() as u32 - 1)
    }

    pub(crate) fn push_function_environment<'a>(
        &mut self,
        env: FunctionEnvironmentRecord,
        _: NoGcScope<'a, '_>,
    ) -> FunctionEnvironment<'a> {
        self.function.push(env);
        FunctionEnvironment::from_index_u32(self.function.len() as u32 - 1)
    }

    pub(crate) fn push_global_environment<'a>(
        &mut self,
        env: GlobalEnvironmentRecord,
        _: NoGcScope<'a, '_>,
    ) -> GlobalEnvironment<'a> {
        self.global.push(env);
        GlobalEnvironment::from_index_u32(self.global.len() as u32 - 1)
    }

    pub(crate) fn push_module_environment<'a>(
        &mut self,
        env: ModuleEnvironmentRecord,
        _: NoGcScope<'a, '_>,
    ) -> ModuleEnvironment<'a> {
        self.module.push(env);
        ModuleEnvironment::from_index_u32(self.module.len() as u32 - 1)
    }

    pub(crate) fn push_object_environment<'a>(
        &mut self,
        env: ObjectEnvironmentRecord,
        decl_env: DeclarativeEnvironmentRecord,
        _: NoGcScope<'a, '_>,
    ) -> (ObjectEnvironment<'a>, DeclarativeEnvironment<'a>) {
        self.object.push(env);
        self.declarative.push(decl_env);
        (
            ObjectEnvironment::from_index_u32(self.object.len() as u32 - 1),
            DeclarativeEnvironment::from_index_u32(self.declarative.len() as u32 - 1),
        )
    }

    pub(crate) fn push_private_environment<'a>(
        &mut self,
        env: PrivateEnvironmentRecord,
        _: NoGcScope<'a, '_>,
    ) -> PrivateEnvironment<'a> {
        self.private.push(env);
        PrivateEnvironment::from_index_u32(self.private.len() as u32 - 1)
    }

    pub(crate) fn get_declarative_environment(
        &self,
        index: DeclarativeEnvironment,
    ) -> &DeclarativeEnvironmentRecord {
        self.declarative
            .get(index.get_index())
            .expect("DeclarativeEnvironment did not match to any vector index")
    }

    pub(crate) fn get_declarative_environment_mut(
        &mut self,
        index: DeclarativeEnvironment,
    ) -> &mut DeclarativeEnvironmentRecord {
        self.declarative
            .get_mut(index.get_index())
            .expect("DeclarativeEnvironment did not match to any vector index")
    }

    #[expect(dead_code)]
    pub(crate) fn get_function_environment(
        &self,
        index: FunctionEnvironment,
    ) -> &FunctionEnvironmentRecord {
        self.function
            .get(index.get_index())
            .expect("FunctionEnvironment did not match to any vector index")
    }

    #[expect(dead_code)]
    pub(crate) fn get_function_environment_mut(
        &mut self,
        index: FunctionEnvironment,
    ) -> &mut FunctionEnvironmentRecord {
        self.function
            .get_mut(index.get_index())
            .expect("FunctionEnvironment did not match to any vector index")
    }

    pub(crate) fn get_module_environment(
        &self,
        index: ModuleEnvironment,
    ) -> &ModuleEnvironmentRecord {
        self.module
            .get(index.get_index())
            .expect("ModuleEnvironment did not match to any vector index")
    }

    pub(crate) fn get_module_environment_mut(
        &mut self,
        index: ModuleEnvironment,
    ) -> &mut ModuleEnvironmentRecord {
        self.module
            .get_mut(index.get_index())
            .expect("ModuleEnvironment did not match to any vector index")
    }

    #[expect(dead_code)]
    pub(crate) fn get_global_environment(
        &self,
        index: GlobalEnvironment,
    ) -> &GlobalEnvironmentRecord {
        self.global
            .get(index.get_index())
            .expect("GlobalEnvironment did not match to any vector index")
    }

    #[expect(dead_code)]
    pub(crate) fn get_global_environment_mut(
        &mut self,
        index: GlobalEnvironment,
    ) -> &mut GlobalEnvironmentRecord {
        self.global
            .get_mut(index.get_index())
            .expect("GlobalEnvironment did not match to any vector index")
    }

    #[expect(dead_code)]
    pub(crate) fn get_object_environment(
        &self,
        index: ObjectEnvironment,
    ) -> &ObjectEnvironmentRecord {
        self.object
            .get(index.get_index())
            .expect("ObjectEnvironment did not match to any vector index")
    }

    #[expect(dead_code)]
    pub(crate) fn get_object_environment_mut(
        &mut self,
        index: ObjectEnvironment,
    ) -> &mut ObjectEnvironmentRecord {
        self.object
            .get_mut(index.get_index())
            .expect("ObjectEnvironment did not match to any vector index")
    }

    pub(crate) fn get_private_environment(
        &self,
        index: PrivateEnvironment,
    ) -> &PrivateEnvironmentRecord {
        self.private
            .get(index.get_index())
            .expect("PrivateEnvironment did not match to any vector index")
    }

    pub(crate) fn get_private_environment_mut(
        &mut self,
        index: PrivateEnvironment,
    ) -> &mut PrivateEnvironmentRecord {
        self.private
            .get_mut(index.get_index())
            .expect("PrivateEnvironment did not match to any vector index")
    }
}

/// ### [9.4.3 GetThisEnvironment ( )](https://tc39.es/ecma262/#sec-getthisenvironment)
/// The abstract operation GetThisEnvironment takes no arguments and returns an
/// Environment Record. It finds the Environment Record that currently supplies
/// the binding of the keyword this.
pub(crate) fn get_this_environment<'a>(agent: &Agent, gc: NoGcScope<'a, '_>) -> Environment<'a> {
    // 1. Let env be the running execution context's LexicalEnvironment.
    let mut env = agent.current_lexical_environment(gc);
    // 2. Repeat,
    loop {
        // a. Let exists be env.HasThisBinding().
        // b. If exists is true, return env.
        if env.has_this_binding(agent) {
            return env;
        }
        // c. Let outer be env.[[OuterEnv]].
        // d. Assert: outer is not null.
        // e. Set env to outer.
        env = env.get_outer_env(agent).unwrap();
    }
}

impl AsRef<Environments> for Environments {
    fn as_ref(&self) -> &Environments {
        self
    }
}

impl AsMut<Environments> for Environments {
    fn as_mut(&mut self) -> &mut Environments {
        self
    }
}

impl AsRef<Environments> for Agent {
    fn as_ref(&self) -> &Environments {
        &self.heap.environments
    }
}

impl AsMut<Environments> for Agent {
    fn as_mut(&mut self) -> &mut Environments {
        &mut self.heap.environments
    }
}