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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::ops::ControlFlow;
use crate::{
ecmascript::{
Agent, ArgumentsList, BUILTIN_STRING_MEMORY, Environment, ExceptionType, InternalMethods,
JsError, JsResult, Object, ObjectEnvironment, OuterEnv, PropertyDescriptor, PropertyKey,
PropertyLookupCache, PropertyOffset, SetAtOffsetProps, SetResult, String, TryError,
TryGetResult, TryHasResult, TryResult, Value, call_function, call_proxy_set,
define_property_or_throw, get, has_property, js_result_into_try, set, throw_set_error,
to_boolean, try_define_property_or_throw, try_get, try_get_ordinary_object_value,
try_get_result_into_value, try_has_property, try_result_into_js, try_set,
},
engine::{Bindable, GcScope, NoGcScope, Scopable},
heap::{ArenaAccess, CompactionLists, HeapMarkAndSweep, WellKnownSymbols, WorkQueues},
};
use super::TryHasBindingContinue;
/// ### [9.1.1.2 Object Environment Records](https://tc39.es/ecma262/#sec-object-environment-records)
///
/// Each Object Environment Record is associated with an object called its
/// binding object. An Object Environment Record binds the set of string
/// identifier names that directly correspond to the property names of its
/// binding object. Property keys that are not strings in the form of an
/// IdentifierName are not included in the set of bound identifiers. Both own
/// and inherited properties are included in the set regardless of the setting
/// of their \[\[Enumerable\]\] attribute. Because properties can be
/// dynamically added and deleted from objects, the set of identifiers bound by
/// an Object Environment Record may potentially change as a side-effect of any
/// operation that adds or deletes properties. Any bindings that are created as
/// a result of such a side-effect are considered to be a mutable binding even
/// if the Writable attribute of the corresponding property is false. Immutable
/// bindings do not exist for Object Environment Records.
#[derive(Debug, Clone)]
pub(crate) struct ObjectEnvironmentRecord {
/// ### \[\[BindingObject\]\]
///
/// The binding object of this Environment Record.
binding_object: Object<'static>,
/// ### \[\[IsWithEnvironment\]\]
///
/// Indicates whether this Environment Record is created for a with
/// statement.
is_with_environment: bool,
/// ### \[\[OuterEnv\]\]
///
/// See [OuterEnv].
outer_env: OuterEnv<'static>,
}
impl ObjectEnvironmentRecord {
/// ### [9.1.2.3 NewObjectEnvironment ( O, W, E )](https://tc39.es/ecma262/#sec-newobjectenvironmenthttps://tc39.es/ecma262/#sec-newobjectenvironment)
///
/// The abstract operation NewObjectEnvironment takes arguments O (an
/// Object), W (a Boolean), and E (an Environment Record or null) and
/// returns an Object Environment Record.
pub(crate) fn new(
binding_object: Object,
is_with_environment: bool,
outer_env: OuterEnv,
) -> ObjectEnvironmentRecord {
// 1. Let env be a new Object Environment Record.
ObjectEnvironmentRecord {
// 2. Set env.[[BindingObject]] to O.
binding_object: binding_object.unbind(),
// 3. Set env.[[IsWithEnvironment]] to W.
is_with_environment,
// 4. Set env.[[OuterEnv]] to E.
outer_env: outer_env.unbind(),
}
// 5. Return env.
}
}
impl HeapMarkAndSweep for ObjectEnvironmentRecord {
fn mark_values(&self, queues: &mut WorkQueues) {
let Self {
binding_object,
is_with_environment: _,
outer_env,
} = self;
outer_env.mark_values(queues);
binding_object.mark_values(queues);
}
fn sweep_values(&mut self, compactions: &CompactionLists) {
let Self {
binding_object,
is_with_environment: _,
outer_env,
} = self;
outer_env.sweep_values(compactions);
binding_object.sweep_values(compactions);
}
}
impl<'e> ObjectEnvironment<'e> {
pub(crate) fn get_binding_object(self, agent: &Agent) -> Object<'e> {
self.get(agent).binding_object
}
pub(crate) fn get_outer_env(self, agent: &Agent) -> Option<Environment<'e>> {
self.get(agent).outer_env
}
/// ### Try [9.1.1.2.1 HasBinding ( N )](https://tc39.es/ecma262/#sec-object-environment-records-hasbinding-n)
///
/// The HasBinding concrete method of an Object Environment Record envRec
/// takes argument N (a String) and returns either a normal completion
/// containing a Boolean or a throw completion. It determines if its
/// associated binding object has a property whose name is N.
pub(crate) fn try_has_binding<'gc>(
self,
agent: &mut Agent,
n: String,
cache: Option<PropertyLookupCache>,
gc: NoGcScope<'gc, '_>,
) -> ControlFlow<TryError<'gc>, TryHasBindingContinue<'gc>> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object.bind(gc);
let is_with_environment = env_rec.is_with_environment;
let name = PropertyKey::from(n).bind(gc);
// 2. Let foundBinding be ? HasProperty(bindingObject, N).
let found_binding = try_has_property(agent, binding_object, name, cache, gc)?;
// 3. If foundBinding is false, return false.
if found_binding == TryHasResult::Unset {
return TryHasBindingContinue::Result(false).into();
}
// 4. If envRec.[[IsWithEnvironment]] is false, return true.
if !is_with_environment {
return found_binding.into();
}
// 5. Let unscopables be ? Get(bindingObject, @@unscopables).
let unscopables = match try_get(
agent,
binding_object,
WellKnownSymbols::Unscopables.into(),
None,
gc,
)? {
TryGetResult::Unset => return found_binding.into(),
TryGetResult::Value(value) => value,
TryGetResult::Get(_) | TryGetResult::Proxy(_) => {
return TryError::GcError.into();
}
};
// 6. If unscopables is an Object, then
if let Ok(unscopables) = Object::try_from(unscopables) {
// a. Let blocked be ToBoolean(? Get(unscopables, N)).
let blocked = match try_get(agent, unscopables, name, cache, gc) {
ControlFlow::Continue(c) => match c {
TryGetResult::Unset => false,
TryGetResult::Value(value) => to_boolean(agent, value),
TryGetResult::Get(_) | TryGetResult::Proxy(_) => {
return TryError::GcError.into();
}
},
ControlFlow::Break(b) => return b.into(),
};
// b. If blocked is true, return false.
if blocked {
return TryHasBindingContinue::Result(false).into();
}
}
// 7. Return true.
found_binding.into()
}
/// ### [9.1.1.2.1 HasBinding ( N )](https://tc39.es/ecma262/#sec-object-environment-records-hasbinding-n)
///
/// The HasBinding concrete method of an Object Environment Record envRec
/// takes argument N (a String) and returns either a normal completion
/// containing a Boolean or a throw completion. It determines if its
/// associated binding object has a property whose name is N.
pub(crate) fn has_binding<'a>(
self,
agent: &mut Agent,
n: String,
mut gc: GcScope<'a, '_>,
) -> JsResult<'a, bool> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object.bind(gc.nogc());
let is_with_environment = env_rec.is_with_environment;
let name = PropertyKey::from(n).bind(gc.nogc());
if !is_with_environment
&& let Object::Object(binding_object) = binding_object
&& let Ok(value) = try_get_ordinary_object_value(agent, binding_object, name)
{
// We either found a value or checked each property in the
// prototype chain and found nothing.
return Ok(value.is_some());
}
let scoped_binding_object = binding_object.scope(agent, gc.nogc());
let scoped_name = name.scope(agent, gc.nogc());
// 2. Let foundBinding be ? HasProperty(bindingObject, N).
let found_binding =
has_property(agent, binding_object.unbind(), name.unbind(), gc.reborrow()).unbind()?;
// 3. If foundBinding is false, return false.
if !found_binding {
return Ok(false);
}
// 4. If envRec.[[IsWithEnvironment]] is false, return true.
if !is_with_environment {
return Ok(true);
}
// 5. Let unscopables be ? Get(bindingObject, @@unscopables).
let unscopables = get(
agent,
scoped_binding_object.get(agent),
PropertyKey::Symbol(WellKnownSymbols::Unscopables.into()),
gc.reborrow(),
)
.unbind()?
.bind(gc.nogc());
// 6. If unscopables is an Object, then
if let Ok(unscopables) = Object::try_from(unscopables) {
// a. Let blocked be ToBoolean(? Get(unscopables, N)).
let blocked = get(
agent,
unscopables.unbind(),
scoped_name.get(agent),
gc.reborrow(),
)
.unbind()?
.bind(gc.nogc());
let blocked = to_boolean(agent, blocked);
// b. If blocked is true, return false.
Ok(!blocked)
} else {
// 7. Return true.
Ok(true)
}
}
/// ### [9.1.1.2.2 CreateMutableBinding ( N, D )](https://tc39.es/ecma262/#sec-object-environment-records-createmutablebinding-n-d)
///
/// The CreateMutableBinding concrete method of an Object Environment
/// Record envRec takes arguments N (a String) and D (a Boolean) and
/// returns either a normal completion containing UNUSED or a throw
/// completion. It creates in an Environment Record's associated binding
/// object a property whose name is N and initializes it to the value
/// undefined. If D is true, the new property's [[Configurable]] attribute
/// is set to true; otherwise it is set to false.
pub(crate) fn try_create_mutable_binding<'a>(
self,
agent: &mut Agent,
n: String,
d: bool,
cache: Option<PropertyLookupCache>,
gc: NoGcScope<'a, '_>,
) -> TryResult<'a, ()> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object.bind(gc);
// 2. Perform ? DefinePropertyOrThrow(bindingObject, N, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }).
// 3. Return UNUSED.
let n = PropertyKey::from(n).bind(gc);
try_define_property_or_throw(
agent,
binding_object.unbind(),
n.unbind(),
PropertyDescriptor {
value: Some(Value::Undefined),
writable: Some(true),
get: None,
set: None,
enumerable: Some(true),
configurable: Some(d),
},
cache,
gc,
)
// NOTE
// Normally envRec will not have a binding for N but if it does, the
// semantics of DefinePropertyOrThrow may result in an existing binding
// being replaced or shadowed or cause an abrupt completion to be
// returned.
}
/// ### [9.1.1.2.2 CreateMutableBinding ( N, D )](https://tc39.es/ecma262/#sec-object-environment-records-createmutablebinding-n-d)
///
/// The CreateMutableBinding concrete method of an Object Environment
/// Record envRec takes arguments N (a String) and D (a Boolean) and
/// returns either a normal completion containing UNUSED or a throw
/// completion. It creates in an Environment Record's associated binding
/// object a property whose name is N and initializes it to the value
/// undefined. If D is true, the new property's [[Configurable]] attribute
/// is set to true; otherwise it is set to false.
pub(crate) fn create_mutable_binding<'a>(
self,
agent: &mut Agent,
n: String,
d: bool,
gc: GcScope<'a, '_>,
) -> JsResult<'a, ()> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object.bind(gc.nogc());
let n = PropertyKey::from(n).bind(gc.nogc());
// 2. Perform ? DefinePropertyOrThrow(bindingObject, N, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }).
define_property_or_throw(
agent,
binding_object.unbind(),
n.unbind(),
PropertyDescriptor {
value: Some(Value::Undefined),
writable: Some(true),
get: None,
set: None,
enumerable: Some(true),
configurable: Some(d),
},
gc,
)?;
// 3. Return UNUSED.
Ok(())
// NOTE
// Normally envRec will not have a binding for N but if it does, the
// semantics of DefinePropertyOrThrow may result in an existing binding
// being replaced or shadowed or cause an abrupt completion to be
// returned.
}
/// ### [9.1.1.2.3 CreateImmutableBinding ( N, S )](https://tc39.es/ecma262/#sec-object-environment-records-createimmutablebinding-n-s)
pub(crate) fn create_immutable_binding(self, _: &mut Agent, _: String, _: bool) {
unreachable!(
"The CreateImmutableBinding concrete method of an Object Environment Record is never used within this specification."
)
}
/// ### Try [9.1.1.2.4 InitializeBinding ( N, V )](https://tc39.es/ecma262/#sec-object-environment-records-initializebinding-n-v)
///
/// The InitializeBinding concrete method of an Object Environment Record
/// envRec takes arguments N (a String) and V (an ECMAScript language
/// value) and returns either a normal completion containing UNUSED or a
/// throw completion. It is used to set the bound value of the current
/// binding of the identifier whose name is N to the value V.
pub(crate) fn try_initialize_binding<'gc>(
self,
agent: &mut Agent,
n: String,
cache: Option<PropertyLookupCache>,
v: Value,
gc: NoGcScope<'gc, '_>,
) -> TryResult<'gc, SetResult<'gc>> {
// 1. Perform ? envRec.SetMutableBinding(N, V, false).
// 2. Return UNUSED.
self.try_set_mutable_binding(agent, n, cache, v, false, gc)
// NOTE
// In this specification, all uses of CreateMutableBinding for Object
// Environment Records are immediately followed by a call to
// InitializeBinding for the same name. Hence, this specification does
// not explicitly track the initialization state of bindings in Object
// Environment Records.
}
/// ### [9.1.1.2.4 InitializeBinding ( N, V )](https://tc39.es/ecma262/#sec-object-environment-records-initializebinding-n-v)
///
/// The InitializeBinding concrete method of an Object Environment Record
/// envRec takes arguments N (a String) and V (an ECMAScript language
/// value) and returns either a normal completion containing UNUSED or a
/// throw completion. It is used to set the bound value of the current
/// binding of the identifier whose name is N to the value V.
pub(crate) fn initialize_binding<'a>(
self,
agent: &mut Agent,
n: String,
cache: Option<PropertyLookupCache>,
v: Value,
gc: GcScope<'a, '_>,
) -> JsResult<'a, ()> {
// 1. Perform ? envRec.SetMutableBinding(N, V, false).
self.set_mutable_binding(agent, n, cache, v, false, gc)?;
// 2. Return UNUSED.
Ok(())
// NOTE
// In this specification, all uses of CreateMutableBinding for Object
// Environment Records are immediately followed by a call to
// InitializeBinding for the same name. Hence, this specification does
// not explicitly track the initialization state of bindings in Object
// Environment Records.
}
/// ### [9.1.1.2.5 SetMutableBinding ( N, V, S )](https://tc39.es/ecma262/#sec-object-environment-records-setmutablebinding-n-v-s)
///
/// The SetMutableBinding concrete method of an Object Environment Record
/// envRec takes arguments N (a String), V (an ECMAScript language value),
/// and S (a Boolean) and returns either a normal completion containing
/// UNUSED or a throw completion. It attempts to set the value of the
/// Environment Record's associated binding object's property whose name is
/// N to the value V. A property named N normally already exists but if it
/// does not or is not currently writable, error handling is determined by
/// S.
pub(crate) fn try_set_mutable_binding<'gc>(
self,
agent: &mut Agent,
n: String,
cache: Option<PropertyLookupCache>,
v: Value,
s: bool,
gc: NoGcScope<'gc, '_>,
) -> TryResult<'gc, SetResult<'gc>> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object.bind(gc);
let n = PropertyKey::from(n).bind(gc);
// 2. Let stillExists be ? HasProperty(bindingObject, N).
let still_exists = match try_has_property(agent, binding_object, n, cache, gc) {
ControlFlow::Continue(c) => match c {
TryHasResult::Unset => None,
TryHasResult::Offset(_, _) => Some(c),
TryHasResult::Custom(_, _) => Some(c),
// Can't continue as we have to check the proxy trap result and
// throw error or call [[Set]].
TryHasResult::Proxy(_) => return TryError::GcError.into(),
},
ControlFlow::Break(_) => return TryError::GcError.into(),
};
// 3. If stillExists is false and S is true, throw a ReferenceError exception.
if still_exists.is_none() && s {
Self::throw_property_doesnt_exist_error(agent, BUILTIN_STRING_MEMORY.object, n, gc)
.into()
} else if let Some(cache) = cache
&& let Some((offset, object)) = still_exists.and_then(|c| match c {
TryHasResult::Offset(offset, object) => {
PropertyOffset::new(offset).map(|o| (o, object))
}
TryHasResult::Custom(offset, object) => {
PropertyOffset::new_custom(offset).map(|o| (o, object))
}
_ => unreachable!(),
})
{
let result = object.set_at_offset(
agent,
&SetAtOffsetProps {
p: n.bind(gc),
receiver: binding_object.bind(gc).into(),
cache: cache.bind(gc),
value: v.bind(gc),
},
offset,
gc,
)?;
if result.failed() && s {
throw_set_error(agent, n, gc).into()
} else {
result.into()
}
} else {
// 4. Perform ? Set(bindingObject, N, V, S).
// 5. Return UNUSED.
try_set(agent, binding_object, n, v, s, cache, gc)
}
}
/// ### [9.1.1.2.5 SetMutableBinding ( N, V, S )](https://tc39.es/ecma262/#sec-object-environment-records-setmutablebinding-n-v-s)
///
/// The SetMutableBinding concrete method of an Object Environment Record
/// envRec takes arguments N (a String), V (an ECMAScript language value),
/// and S (a Boolean) and returns either a normal completion containing
/// UNUSED or a throw completion. It attempts to set the value of the
/// Environment Record's associated binding object's property whose name is
/// N to the value V. A property named N normally already exists but if it
/// does not or is not currently writable, error handling is determined by
/// S.
pub(crate) fn set_mutable_binding<'a>(
self,
agent: &mut Agent,
n: String,
cache: Option<PropertyLookupCache>,
v: Value,
s: bool,
gc: GcScope<'a, '_>,
) -> JsResult<'a, ()> {
let env = self.bind(gc.nogc());
let env_rec = &env.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object.bind(gc.nogc());
let n = PropertyKey::from(n).bind(gc.nogc());
let cache = cache.bind(gc.nogc());
let v = v.bind(gc.nogc());
if let Some(cache) = cache
&& let Some(result) = try_result_into_js(Self::set_mutable_binding_cached_inner(
agent,
binding_object,
n,
cache,
v,
s,
gc.nogc(),
))
.unbind()?
.bind(gc.nogc())
{
match result {
SetResult::Done | SetResult::Unwritable | SetResult::Accessor => {}
SetResult::Set(setter) => {
call_function(
agent,
setter.unbind(),
binding_object.unbind().into(),
Some(ArgumentsList::from_mut_value(&mut v.unbind())),
gc,
)?;
}
SetResult::Proxy(proxy) => {
call_proxy_set(
agent,
proxy.unbind(),
n.unbind(),
v.unbind(),
binding_object.unbind().into(),
s,
gc,
)?;
}
}
return Ok(());
}
Self::set_mutable_binding_inner(
agent,
binding_object.unbind(),
n.unbind(),
cache.unbind(),
v.unbind(),
s,
gc,
)
}
/// Inner method for setting a mutable binding with a property lookup
/// cache.
///
/// This ought to be the hot path.
fn set_mutable_binding_cached_inner<'a>(
agent: &mut Agent,
binding_object: Object,
n: PropertyKey,
cache: PropertyLookupCache,
v: Value,
s: bool,
gc: NoGcScope<'a, '_>,
) -> TryResult<'a, SetResult<'a>> {
let still_exists = match try_has_property(agent, binding_object, n, Some(cache), gc)? {
TryHasResult::Unset => false,
TryHasResult::Offset(_, _) => true,
TryHasResult::Custom(_, _) => true,
TryHasResult::Proxy(_) => return TryError::GcError.into(),
};
// 3. If stillExists is false and S is true,
if !still_exists && s {
return Self::throw_property_doesnt_exist_error(
agent,
BUILTIN_STRING_MEMORY.object,
n,
gc,
)
.into();
}
let result = binding_object.try_set(agent, n, v, binding_object.into(), Some(cache), gc)?;
if result.failed() {
// The key was unwritable and we're in strict mode;
// need to throw an error.
throw_set_error(agent, n, gc).into()
} else {
result.into()
}
}
/// Inner method for setting a mutable binding with no (matching) property
/// lookup cache.
///
/// This ought to be the cold path.
#[inline(never)]
fn set_mutable_binding_inner<'a>(
agent: &mut Agent,
binding_object: Object,
n: PropertyKey,
_cache: Option<PropertyLookupCache>,
v: Value,
s: bool,
mut gc: GcScope<'a, '_>,
) -> JsResult<'a, ()> {
let binding_object = binding_object.bind(gc.nogc());
let n = n.bind(gc.nogc());
let v = v.bind(gc.nogc());
let scoped_binding_object = binding_object.scope(agent, gc.nogc());
let scoped_n = n.scope(agent, gc.nogc());
let scoped_v = v.scope(agent, gc.nogc());
// 2. Let stillExists be ? HasProperty(bindingObject, N).
let still_exists = has_property(agent, binding_object.unbind(), n.unbind(), gc.reborrow());
let still_exists = still_exists.unbind()?;
// 3. If stillExists is false and S is true, throw a ReferenceError exception.
if !still_exists && s {
let binding_object_repr =
Value::from(scoped_binding_object.get(agent)).string_repr(agent, gc.reborrow());
Err(Self::throw_property_doesnt_exist_error(
agent,
binding_object_repr.unbind(),
scoped_n.get(agent),
gc.into_nogc(),
))
} else {
// 4. Perform ? Set(bindingObject, N, V, S).
set(
agent,
scoped_binding_object.get(agent),
scoped_n.get(agent),
scoped_v.get(agent),
s,
gc,
)?;
// 5. Return UNUSED.
Ok(())
}
}
fn throw_property_doesnt_exist_error<'a>(
agent: &mut Agent,
binding_object_repr: String,
n: PropertyKey,
gc: NoGcScope<'a, '_>,
) -> JsError<'a> {
let error_message = format!(
"Property '{}' does not exist in {}.",
n.as_display(agent),
binding_object_repr.to_string_lossy_(agent)
);
agent.throw_exception(ExceptionType::ReferenceError, error_message, gc)
}
/// ### [9.1.1.2.6 GetBindingValue ( N, S )](https://tc39.es/ecma262/#sec-object-environment-records-getbindingvalue-n-s)
///
/// The GetBindingValue concrete method of an Object Environment Record
/// envRec takes arguments N (a String) and S (a Boolean) and returns
/// either a normal completion containing an ECMAScript language value or a
/// throw completion. It returns the value of its associated binding
/// object's property whose name is N. The property should already exist
/// but if it does not the result depends upon S.
pub(crate) fn try_get_binding_value(
self,
agent: &mut Agent,
n: String,
cache: Option<PropertyLookupCache>,
s: bool,
gc: NoGcScope<'e, '_>,
) -> TryResult<'e, Value<'e>> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object.bind(gc);
let name = PropertyKey::from(n).bind(gc);
// 2. Let value be ? HasProperty(bindingObject, N).
let value = match try_has_property(agent, binding_object, name, cache, gc) {
ControlFlow::Continue(c) => match c {
TryHasResult::Unset => None,
TryHasResult::Offset(_, _) => Some(c),
TryHasResult::Custom(_, _) => Some(c),
TryHasResult::Proxy(_) => return TryError::GcError.into(),
},
ControlFlow::Break(_) => return TryError::GcError.into(),
};
// 3. If value is false, then
if value.is_none() {
js_result_into_try(Self::handle_property_not_found(agent, name, s, gc))
} else if let Some((offset, object)) = value.and_then(|c| match c {
TryHasResult::Offset(offset, object) => {
PropertyOffset::new(offset).map(|o| (o, object))
}
TryHasResult::Custom(offset, object) => {
PropertyOffset::new_custom(offset).map(|o| (o, object))
}
_ => unreachable!(),
}) {
match object.get_own_property_at_offset(agent, offset, gc) {
TryGetResult::Unset => TryResult::Continue(Value::Undefined),
TryGetResult::Value(value) => TryResult::Continue(value),
TryGetResult::Get(_function) => TryError::GcError.into(),
TryGetResult::Proxy(_proxy) => TryError::GcError.into(),
}
} else {
// 4. Return ? Get(bindingObject, N).
try_get_result_into_value(try_get(agent, binding_object, name, cache, gc))
}
}
/// ### [9.1.1.2.6 GetBindingValue ( N, S )](https://tc39.es/ecma262/#sec-object-environment-records-getbindingvalue-n-s)
///
/// The GetBindingValue concrete method of an Object Environment Record
/// envRec takes arguments N (a String) and S (a Boolean) and returns
/// either a normal completion containing an ECMAScript language value or a
/// throw completion. It returns the value of its associated binding
/// object's property whose name is N. The property should already exist
/// but if it does not the result depends upon S.
pub(crate) fn get_binding_value<'a>(
self,
agent: &mut Agent,
name: String,
s: bool,
mut gc: GcScope<'a, '_>,
) -> JsResult<'a, Value<'a>> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object.bind(gc.nogc());
let name = PropertyKey::from(name).bind(gc.nogc());
if let Object::Object(binding_object) = binding_object
&& let Ok(value) = try_get_ordinary_object_value(agent, binding_object, name)
{
return if let Some(value) = value {
// Found the property value.
Ok(value.unbind())
} else {
// Property did not exist.
Self::handle_property_not_found(agent, name.unbind(), s, gc.into_nogc())
};
}
let scoped_binding_object = binding_object.scope(agent, gc.nogc());
let scoped_name = name.scope(agent, gc.nogc());
// 2. Let value be ? HasProperty(bindingObject, N).
let value =
has_property(agent, binding_object.unbind(), name.unbind(), gc.reborrow()).unbind()?;
// 3. If value is false, then
if !value {
Self::handle_property_not_found(agent, scoped_name.get(agent), s, gc.into_nogc())
} else {
// 4. Return ? Get(bindingObject, N).
get(
agent,
scoped_binding_object.get(agent),
scoped_name.get(agent),
gc,
)
}
}
fn handle_property_not_found<'a>(
agent: &mut Agent,
name: PropertyKey,
s: bool,
gc: NoGcScope<'a, '_>,
) -> JsResult<'a, Value<'a>> {
// a. If S is false, return undefined; otherwise throw a ReferenceError exception.
if !s {
Ok(Value::Undefined)
} else {
let error_message = format!(
"Property '{}' does not exist in object.",
name.as_display(agent)
);
Err(agent.throw_exception(ExceptionType::ReferenceError, error_message, gc))
}
}
/// ### Try [9.1.1.2.7 DeleteBinding ( N )](https://tc39.es/ecma262/#sec-object-environment-records-deletebinding-n)
///
/// The DeleteBinding concrete method of an Object Environment Record
/// envRec takes argument N (a String) and returns either a normal
/// completion containing a Boolean or a throw completion. It can only
/// delete bindings that correspond to properties of the environment
/// object whose [[Configurable]] attribute have the value true.
pub(crate) fn try_delete_binding<'gc>(
self,
agent: &mut Agent,
name: String,
gc: NoGcScope<'gc, '_>,
) -> TryResult<'gc, bool> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object;
let name = PropertyKey::from(name);
// 2. Return ? bindingObject.[[Delete]](N).
binding_object.try_delete(agent, name, gc)
}
/// ### [9.1.1.2.7 DeleteBinding ( N )](https://tc39.es/ecma262/#sec-object-environment-records-deletebinding-n)
///
/// The DeleteBinding concrete method of an Object Environment Record
/// envRec takes argument N (a String) and returns either a normal
/// completion containing a Boolean or a throw completion. It can only
/// delete bindings that correspond to properties of the environment
/// object whose [[Configurable]] attribute have the value true.
pub(crate) fn delete_binding<'a>(
self,
agent: &mut Agent,
name: String,
gc: GcScope<'a, '_>,
) -> JsResult<'a, bool> {
let env_rec = &self.get(agent);
// 1. Let bindingObject be envRec.[[BindingObject]].
let binding_object = env_rec.binding_object;
let name = PropertyKey::from(name);
// 2. Return ? bindingObject.[[Delete]](N).
binding_object.internal_delete(agent, name, gc)
}
/// ### [9.1.1.2.10 WithBaseObject ( )](https://tc39.es/ecma262/#sec-object-environment-records-withbaseobject)
///
/// The WithBaseObject concrete method of an Object Environment Record
/// envRec takes no arguments and returns an Object or undefined.
pub(crate) fn with_base_object(self, agent: &Agent) -> Option<Object<'e>> {
let env_rec = &self.get(agent);
// 1. If envRec.[[IsWithEnvironment]] is true, return envRec.[[BindingObject]].
if env_rec.is_with_environment {
Some(env_rec.binding_object)
} else {
// 2. Otherwise, return undefined.
None
}
}
}
impl HeapMarkAndSweep for ObjectEnvironment<'static> {
fn mark_values(&self, queues: &mut WorkQueues) {
queues.object_environments.push(*self);
}
fn sweep_values(&mut self, compactions: &CompactionLists) {
compactions.object_environments.shift_index(&mut self.0);
}
}