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
use std::{cell::RefCell, rc::Rc};
use crate::{
environments::CompileTimeEnvironment,
object::{JsObject, PrivateName},
Context, JsResult, JsString, JsSymbol, JsValue,
};
use boa_ast::expression::Identifier;
use boa_gc::{empty_trace, Finalize, Gc, Trace};
use rustc_hash::FxHashSet;
mod declarative;
mod private;
use self::declarative::ModuleEnvironment;
pub(crate) use self::{
declarative::{
DeclarativeEnvironment, DeclarativeEnvironmentKind, FunctionEnvironment, FunctionSlots,
LexicalEnvironment, ThisBindingStatus,
},
private::PrivateEnvironment,
};
/// The environment stack holds all environments at runtime.
///
/// Environments themselves are garbage collected,
/// because they must be preserved for function calls.
#[derive(Clone, Debug, Trace, Finalize)]
pub(crate) struct EnvironmentStack {
stack: Vec<Environment>,
private_stack: Vec<Gc<PrivateEnvironment>>,
}
/// A runtime environment.
#[derive(Clone, Debug, Trace, Finalize)]
pub(crate) enum Environment {
Declarative(Gc<DeclarativeEnvironment>),
Object(JsObject),
}
impl Environment {
/// Returns the declarative environment if it is one.
pub(crate) const fn as_declarative(&self) -> Option<&Gc<DeclarativeEnvironment>> {
match self {
Self::Declarative(env) => Some(env),
Self::Object(_) => None,
}
}
/// Returns the declarative environment and panic if it is not one.
#[track_caller]
pub(crate) fn declarative_expect(&self) -> &Gc<DeclarativeEnvironment> {
self.as_declarative()
.expect("environment must be declarative")
}
}
impl EnvironmentStack {
/// Create a new environment stack.
pub(crate) fn new(global: Gc<DeclarativeEnvironment>) -> Self {
assert!(matches!(
global.kind(),
DeclarativeEnvironmentKind::Global(_)
));
Self {
stack: vec![Environment::Declarative(global)],
private_stack: Vec::new(),
}
}
/// Replaces the current global with a new global environment.
pub(crate) fn replace_global(&mut self, global: Gc<DeclarativeEnvironment>) {
assert!(matches!(
global.kind(),
DeclarativeEnvironmentKind::Global(_)
));
self.stack[0] = Environment::Declarative(global);
}
/// Extends the length of the next outer function environment to the number of compiled bindings.
///
/// This is only useful when compiled bindings are added after the initial compilation (eval).
pub(crate) fn extend_outer_function_environment(&mut self) {
for env in self
.stack
.iter()
.filter_map(Environment::as_declarative)
.rev()
{
if let DeclarativeEnvironmentKind::Function(fun) = &env.kind() {
let compile_bindings_number = env.compile_env().borrow().num_bindings() as usize;
let mut bindings = fun.poisonable_environment().bindings().borrow_mut();
if compile_bindings_number > bindings.len() {
bindings.resize(compile_bindings_number, None);
}
break;
}
}
}
/// Check if any of the provided binding names are defined as lexical bindings.
///
/// Start at the current environment.
/// Stop at the next outer function environment.
pub(crate) fn has_lex_binding_until_function_environment(
&self,
names: &FxHashSet<Identifier>,
) -> Option<Identifier> {
for env in self
.stack
.iter()
.filter_map(Environment::as_declarative)
.rev()
{
let compile = env.compile_env();
let compile = compile.borrow();
for name in names {
if compile.has_lex_binding(*name) {
return Some(*name);
}
}
if compile.is_function() {
break;
}
}
None
}
/// Check if the next outer function environment is the global environment.
pub(crate) fn is_next_outer_function_environment_global(&self) -> bool {
for env in self
.stack
.iter()
.rev()
.filter_map(Environment::as_declarative)
{
let compile = env.compile_env();
let compile = compile.borrow();
if compile.is_function() {
return compile.outer().is_none();
}
}
true
}
/// Pop all current environments except the global environment.
pub(crate) fn pop_to_global(&mut self) -> Vec<Environment> {
self.stack.split_off(1)
}
/// Get the number of current environments.
pub(crate) fn len(&self) -> usize {
self.stack.len()
}
/// Truncate current environments to the given number.
pub(crate) fn truncate(&mut self, len: usize) {
self.stack.truncate(len);
}
/// Extend the current environment stack with the given environments.
pub(crate) fn extend(&mut self, other: Vec<Environment>) {
self.stack.extend(other);
}
/// `GetThisEnvironment`
///
/// Returns the environment that currently provides a `this` biding.
///
/// More information:
/// - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-getthisenvironment
///
/// # Panics
///
/// Panics if no environment exists on the stack.
pub(crate) fn get_this_environment(&self) -> &DeclarativeEnvironmentKind {
for env in self.stack.iter().rev() {
if let Some(decl) = env.as_declarative().filter(|decl| decl.has_this_binding()) {
return decl.kind();
}
}
panic!("global environment must exist");
}
/// `GetThisBinding`
///
/// Returns the current `this` binding of the environment.
///
/// More information:
/// - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-function-environment-records-getthisbinding
pub(crate) fn get_this_binding(&self) -> JsResult<JsValue> {
for env in self.stack.iter().rev() {
if let Environment::Declarative(decl) = env {
if let Some(this) = decl.get_this_binding()? {
return Ok(this);
}
}
}
panic!("global environment must exist");
}
/// Push a new object environment on the environments stack and return it's index.
pub(crate) fn push_object(&mut self, object: JsObject) -> usize {
let index = self.stack.len();
self.stack.push(Environment::Object(object));
index
}
/// Push a lexical environment on the environments stack and return it's index.
///
/// # Panics
///
/// Panics if no environment exists on the stack.
#[track_caller]
pub(crate) fn push_lexical(
&mut self,
compile_environment: Rc<RefCell<CompileTimeEnvironment>>,
) -> u32 {
let num_bindings = compile_environment.borrow().num_bindings();
let (poisoned, with) = {
let with = self
.stack
.last()
.expect("global environment must always exist")
.as_declarative()
.is_none();
let environment = self
.stack
.iter()
.rev()
.find_map(Environment::as_declarative)
.expect("global environment must always exist");
(environment.poisoned(), with || environment.with())
};
let index = self.stack.len() as u32;
self.stack.push(Environment::Declarative(Gc::new(
DeclarativeEnvironment::new(
DeclarativeEnvironmentKind::Lexical(LexicalEnvironment::new(
num_bindings,
poisoned,
with,
)),
compile_environment,
),
)));
index
}
/// Push a function environment on the environments stack.
///
/// # Panics
///
/// Panics if no environment exists on the stack.
#[track_caller]
pub(crate) fn push_function(
&mut self,
compile_environment: Rc<RefCell<CompileTimeEnvironment>>,
function_slots: FunctionSlots,
) {
let num_bindings = compile_environment.borrow().num_bindings();
let (poisoned, with) = {
let with = self
.stack
.last()
.expect("global environment must always exist")
.as_declarative()
.is_none();
let environment = self
.stack
.iter()
.rev()
.find_map(Environment::as_declarative)
.expect("global environment must always exist");
(environment.poisoned(), with || environment.with())
};
self.stack.push(Environment::Declarative(Gc::new(
DeclarativeEnvironment::new(
DeclarativeEnvironmentKind::Function(FunctionEnvironment::new(
num_bindings,
poisoned,
with,
function_slots,
)),
compile_environment,
),
)));
}
/// Push a function environment that inherits it's internal slots from the outer function
/// environment.
///
/// # Panics
///
/// Panics if no environment exists on the stack.
#[track_caller]
pub(crate) fn push_function_inherit(
&mut self,
compile_environment: Rc<RefCell<CompileTimeEnvironment>>,
) {
let num_bindings = compile_environment.borrow().num_bindings();
debug_assert!(
self.stack.len() as u32 == compile_environment.borrow().environment_index(),
"tried to push an invalid compile environment"
);
let (poisoned, with, slots) = {
let with = self
.stack
.last()
.expect("can only be called inside a function")
.as_declarative()
.is_none();
let (environment, slots) = self
.stack
.iter()
.rev()
.find_map(|env| {
if let Some(env) = env.as_declarative() {
if let DeclarativeEnvironmentKind::Function(fun) = env.kind() {
return Some((env, fun.slots().clone()));
}
}
None
})
.expect("can only be called inside a function");
(environment.poisoned(), with || environment.with(), slots)
};
self.stack.push(Environment::Declarative(Gc::new(
DeclarativeEnvironment::new(
DeclarativeEnvironmentKind::Function(FunctionEnvironment::new(
num_bindings,
poisoned,
with,
slots,
)),
compile_environment,
),
)));
}
/// Push a module environment on the environments stack.
///
/// # Panics
///
/// Panics if no environment exists on the stack.
#[track_caller]
pub(crate) fn push_module(&mut self, compile_environment: Rc<RefCell<CompileTimeEnvironment>>) {
let num_bindings = compile_environment.borrow().num_bindings();
self.stack.push(Environment::Declarative(Gc::new(
DeclarativeEnvironment::new(
DeclarativeEnvironmentKind::Module(ModuleEnvironment::new(num_bindings)),
compile_environment,
),
)));
}
/// Pop environment from the environments stack.
#[track_caller]
pub(crate) fn pop(&mut self) -> Environment {
debug_assert!(self.stack.len() > 1);
self.stack
.pop()
.expect("environment stack is cannot be empty")
}
/// Get the most outer environment.
///
/// # Panics
///
/// Panics if no environment exists on the stack.
#[track_caller]
pub(crate) fn current(&self) -> Environment {
self.stack
.last()
.expect("global environment must always exist")
.clone()
}
/// Get the compile environment for the current runtime environment.
///
/// # Panics
///
/// Panics if no environment exists on the stack.
pub(crate) fn current_compile_environment(&self) -> Rc<RefCell<CompileTimeEnvironment>> {
self.stack
.iter()
.filter_map(Environment::as_declarative)
.last()
.expect("global environment must always exist")
.compile_env()
}
/// Mark that there may be added bindings from the current environment to the next function
/// environment.
pub(crate) fn poison_until_last_function(&mut self) {
for env in self
.stack
.iter()
.rev()
.filter_map(Environment::as_declarative)
{
env.poison();
if env.compile_env().borrow().is_function() {
return;
}
}
}
/// Set the value of a lexical binding.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
#[track_caller]
pub(crate) fn put_lexical_value(
&mut self,
environment_index: u32,
binding_index: u32,
value: JsValue,
) {
let env = self
.stack
.get(environment_index as usize)
.expect("environment index must be in range")
.declarative_expect();
env.set(binding_index, value);
}
/// Set the value of a binding if it is uninitialized.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
#[track_caller]
pub(crate) fn put_value_if_uninitialized(
&mut self,
environment_index: u32,
binding_index: u32,
value: JsValue,
) {
let env = self
.stack
.get(environment_index as usize)
.expect("environment index must be in range")
.declarative_expect();
if env.get(binding_index).is_none() {
env.set(binding_index, value);
}
}
/// Push a private environment to the private environment stack.
pub(crate) fn push_private(&mut self, environment: Gc<PrivateEnvironment>) {
self.private_stack.push(environment);
}
/// Pop a private environment from the private environment stack.
pub(crate) fn pop_private(&mut self) {
self.private_stack.pop();
}
/// `ResolvePrivateIdentifier ( privEnv, identifier )`
///
/// More information:
/// - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-resolve-private-identifier
pub(crate) fn resolve_private_identifier(&self, identifier: JsString) -> Option<PrivateName> {
// 1. Let names be privEnv.[[Names]].
// 2. For each Private Name pn of names, do
// a. If pn.[[Description]] is identifier, then
// i. Return pn.
// 3. Let outerPrivEnv be privEnv.[[OuterPrivateEnvironment]].
// 4. Assert: outerPrivEnv is not null.
// 5. Return ResolvePrivateIdentifier(outerPrivEnv, identifier).
for environment in self.private_stack.iter().rev() {
if environment.descriptions().contains(&identifier) {
return Some(PrivateName::new(identifier, environment.id()));
}
}
None
}
/// Return all private name descriptions in all private environments.
pub(crate) fn private_name_descriptions(&self) -> Vec<&JsString> {
let mut names = Vec::new();
for environment in self.private_stack.iter().rev() {
for name in environment.descriptions() {
if !names.contains(&name) {
names.push(name);
}
}
}
names
}
}
/// A binding locator contains all information about a binding that is needed to resolve it at runtime.
///
/// Binding locators get created at bytecode compile time and are accessible at runtime via the [`crate::vm::CodeBlock`].
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Finalize)]
pub(crate) struct BindingLocator {
name: Identifier,
environment_index: u32,
binding_index: u32,
global: bool,
}
unsafe impl Trace for BindingLocator {
empty_trace!();
}
impl BindingLocator {
/// Creates a new declarative binding locator that has knows indices.
pub(crate) const fn declarative(
name: Identifier,
environment_index: u32,
binding_index: u32,
) -> Self {
Self {
name,
environment_index,
binding_index,
global: false,
}
}
/// Creates a binding locator that indicates that the binding is on the global object.
pub(super) const fn global(name: Identifier) -> Self {
Self {
name,
environment_index: 0,
binding_index: 0,
global: true,
}
}
/// Returns the name of the binding.
pub(crate) const fn name(&self) -> Identifier {
self.name
}
/// Returns if the binding is located on the global object.
pub(crate) const fn is_global(&self) -> bool {
self.global
}
/// Returns the environment index of the binding.
pub(crate) const fn environment_index(&self) -> u32 {
self.environment_index
}
/// Returns the binding index of the binding.
pub(crate) const fn binding_index(&self) -> u32 {
self.binding_index
}
}
/// Action that is returned when a fallible binding operation.
pub(crate) enum BindingLocatorError {
/// Trying to mutate immutable binding,
MutateImmutable,
/// Indicates that any action is silently ignored.
Silent,
}
impl Context<'_> {
/// Gets the corresponding runtime binding of the provided `BindingLocator`, modifying
/// its indexes in place.
///
/// This readjusts a `BindingLocator` to the correct binding if a `with` environment or
/// `eval` call modified the compile-time bindings.
///
/// Only use if the binding origin is unknown or comes from a `var` declaration. Lexical bindings
/// are completely removed of runtime checks because the specification guarantees that runtime
/// semantics cannot add or remove lexical bindings.
pub(crate) fn find_runtime_binding(&mut self, locator: &mut BindingLocator) -> JsResult<()> {
let current = self.vm.environments.current();
if let Some(env) = current.as_declarative() {
if !env.with() && !env.poisoned() {
return Ok(());
}
}
for env_index in (locator.environment_index..self.vm.environments.stack.len() as u32).rev()
{
match self.environment_expect(env_index) {
Environment::Declarative(env) => {
if env.poisoned() {
let compile = env.compile_env();
let compile = compile.borrow();
if compile.is_function() {
if let Some(b) = compile.get_binding(locator.name) {
locator.environment_index = b.environment_index;
locator.binding_index = b.binding_index;
locator.global = false;
break;
}
}
} else if !env.with() {
break;
}
}
Environment::Object(o) => {
let o = o.clone();
let key: JsString = self
.interner()
.resolve_expect(locator.name.sym())
.into_common(false);
if o.has_property(key.clone(), self)? {
if let Some(unscopables) = o.get(JsSymbol::unscopables(), self)?.as_object()
{
if unscopables.get(key.clone(), self)?.to_boolean() {
continue;
}
}
locator.environment_index = env_index;
locator.global = false;
break;
}
}
}
}
Ok(())
}
/// Checks if the binding pointed by `locator` is initialized.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
pub(crate) fn is_initialized_binding(&mut self, locator: &BindingLocator) -> JsResult<bool> {
if locator.global {
let key: JsString = self
.interner()
.resolve_expect(locator.name.sym())
.into_common(false);
self.global_object().has_property(key, self)
} else {
match self.environment_expect(locator.environment_index) {
Environment::Declarative(env) => Ok(env.get(locator.binding_index).is_some()),
Environment::Object(obj) => {
let key: JsString = self
.interner()
.resolve_expect(locator.name.sym())
.into_common(false);
obj.clone().has_property(key, self)
}
}
}
}
/// Get the value of a binding.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
pub(crate) fn get_binding(&mut self, locator: BindingLocator) -> JsResult<Option<JsValue>> {
if locator.global {
let global = self.global_object();
let key: JsString = self
.interner()
.resolve_expect(locator.name.sym())
.into_common(false);
if global.has_property(key.clone(), self)? {
global.get(key, self).map(Some)
} else {
Ok(None)
}
} else {
match self.environment_expect(locator.environment_index) {
Environment::Declarative(env) => Ok(env.get(locator.binding_index)),
Environment::Object(obj) => {
let obj = obj.clone();
let key: JsString = self
.interner()
.resolve_expect(locator.name.sym())
.into_common(false);
obj.get(key, self).map(Some)
}
}
}
}
/// Sets the value of a binding.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
#[track_caller]
pub(crate) fn set_binding(
&mut self,
locator: BindingLocator,
value: JsValue,
strict: bool,
) -> JsResult<()> {
if locator.global {
let key = self
.interner()
.resolve_expect(locator.name().sym())
.into_common::<JsString>(false);
self.global_object().set(key, value, strict, self)?;
} else {
match self.environment_expect(locator.environment_index) {
Environment::Declarative(decl) => {
decl.set(locator.binding_index, value);
}
Environment::Object(obj) => {
let obj = obj.clone();
let key: JsString = self
.interner()
.resolve_expect(locator.name.sym())
.into_common(false);
obj.set(key, value, strict, self)?;
}
}
}
Ok(())
}
/// Deletes a binding if it exists.
///
/// Returns `true` if the binding was deleted.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
pub(crate) fn delete_binding(&mut self, locator: BindingLocator) -> JsResult<bool> {
if locator.is_global() {
let key: JsString = self
.interner()
.resolve_expect(locator.name().sym())
.into_common::<JsString>(false);
self.global_object().__delete__(&key.into(), self)
} else {
match self.environment_expect(locator.environment_index) {
Environment::Declarative(_) => Ok(false),
Environment::Object(obj) => {
let obj = obj.clone();
let key: JsString = self
.interner()
.resolve_expect(locator.name.sym())
.into_common(false);
obj.__delete__(&key.into(), self)
}
}
}
}
/// Return the environment at the given index. Panics if the index is out of range.
pub(crate) fn environment_expect(&self, index: u32) -> &Environment {
self.vm
.environments
.stack
.get(index as usize)
.expect("environment index must be in range")
}
}