-
-
Notifications
You must be signed in to change notification settings - Fork 602
Expand file tree
/
Copy pathmod.rs
More file actions
626 lines (574 loc) · 21.3 KB
/
mod.rs
File metadata and controls
626 lines (574 loc) · 21.3 KB
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
use crate::{
Context, JsResult, JsString, JsSymbol, JsValue,
object::{JsObject, PrivateName},
};
use boa_ast::scope::{BindingLocator, BindingLocatorScope, Scope};
use boa_gc::{Finalize, Gc, Trace};
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>,
global: Gc<DeclarativeEnvironment>,
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,
}
}
}
impl EnvironmentStack {
/// Create a new environment stack.
pub(crate) fn new(global: Gc<DeclarativeEnvironment>) -> Self {
assert!(matches!(
global.kind(),
DeclarativeEnvironmentKind::Global(_)
));
Self {
stack: Vec::new(),
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.global = global;
}
/// Gets the current global environment.
pub(crate) fn global(&self) -> &Gc<DeclarativeEnvironment> {
&self.global
}
/// Gets the next outer function environment.
pub(crate) fn outer_function_environment(&self) -> Option<(Gc<DeclarativeEnvironment>, Scope)> {
for env in self
.stack
.iter()
.filter_map(Environment::as_declarative)
.rev()
{
if let Some(function_env) = env.kind().as_function() {
return Some((env.clone(), function_env.compile().clone()));
}
}
None
}
/// Pop all current environments except the global environment.
pub(crate) fn pop_to_global(&mut self) -> Vec<Environment> {
let mut envs = Vec::new();
std::mem::swap(&mut envs, &mut self.stack);
envs
}
/// 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
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();
}
}
self.global().kind()
}
/// `GetThisBinding`
///
/// Returns the current `this` binding of the environment.
/// Note: If the current environment is the global environment, this function returns `Ok(None)`.
///
/// More information:
/// - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-function-environment-records-getthisbinding
pub(crate) fn get_this_binding(&self) -> JsResult<Option<JsValue>> {
for env in self.stack.iter().rev() {
if let Environment::Declarative(decl) = env
&& let Some(this) = decl.get_this_binding()?
{
return Ok(Some(this));
}
}
Ok(None)
}
/// Push a new object environment on the environments stack.
pub(crate) fn push_object(&mut self, object: JsObject) {
self.stack.push(Environment::Object(object));
}
/// Push a lexical environment on the environments stack and return it's index.
pub(crate) fn push_lexical(&mut self, bindings_count: u32) -> u32 {
let (poisoned, with) = {
// Check if the outer environment is a declarative environment.
let with = if let Some(env) = self.stack.last() {
env.as_declarative().is_none()
} else {
false
};
let environment = self
.stack
.iter()
.rev()
.find_map(Environment::as_declarative)
.unwrap_or(self.global());
(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(bindings_count)),
poisoned,
with,
),
)));
index
}
/// Push a function environment on the environments stack.
pub(crate) fn push_function(&mut self, scope: Scope, function_slots: FunctionSlots) {
let num_bindings = scope.num_bindings_non_local();
let (poisoned, with) = {
// Check if the outer environment is a declarative environment.
let with = if let Some(env) = self.stack.last() {
env.as_declarative().is_none()
} else {
false
};
let environment = self
.stack
.iter()
.rev()
.find_map(Environment::as_declarative)
.unwrap_or(self.global());
(environment.poisoned(), with || environment.with())
};
self.stack.push(Environment::Declarative(Gc::new(
DeclarativeEnvironment::new(
DeclarativeEnvironmentKind::Function(FunctionEnvironment::new(
num_bindings,
function_slots,
scope,
)),
poisoned,
with,
),
)));
}
/// Push a module environment on the environments stack.
pub(crate) fn push_module(&mut self, scope: Scope) {
let num_bindings = scope.num_bindings_non_local();
self.stack.push(Environment::Declarative(Gc::new(
DeclarativeEnvironment::new(
DeclarativeEnvironmentKind::Module(ModuleEnvironment::new(num_bindings, scope)),
false,
false,
),
)));
}
/// Pop environment from the environments stack.
#[track_caller]
pub(crate) fn pop(&mut self) {
debug_assert!(!self.stack.is_empty());
self.stack.pop();
}
/// Get the most outer environment.
pub(crate) fn current_declarative_ref(&self) -> Option<&Gc<DeclarativeEnvironment>> {
if let Some(env) = self.stack.last() {
env.as_declarative()
} else {
Some(self.global())
}
}
/// 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.is_function() {
return;
}
}
self.global().poison();
}
/// Set the value of a lexical binding.
///
/// # Errors
///
/// Returns an error if the binding is an indirect module reference.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
#[track_caller]
pub(crate) fn put_lexical_value(
&mut self,
environment: BindingLocatorScope,
binding_index: u32,
value: JsValue,
) -> JsResult<()> {
let env = match environment {
BindingLocatorScope::GlobalObject | BindingLocatorScope::GlobalDeclarative => {
self.global()
}
BindingLocatorScope::Stack(index) => self
.stack
.get(index as usize)
.and_then(Environment::as_declarative)
.expect("must be declarative environment"),
};
env.set(binding_index, value)
}
/// Set the value of a binding if it is uninitialized.
///
/// # Errors
///
/// Returns an error if the binding is an indirect module reference.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
#[track_caller]
pub(crate) fn put_value_if_uninitialized(
&mut self,
environment: BindingLocatorScope,
binding_index: u32,
value: JsValue,
) -> JsResult<()> {
let env = match environment {
BindingLocatorScope::GlobalObject | BindingLocatorScope::GlobalDeclarative => {
self.global()
}
BindingLocatorScope::Stack(index) => self
.stack
.get(index as usize)
.and_then(Environment::as_declarative)
.expect("must be declarative environment"),
};
if env.get(binding_index).is_none() {
env.set(binding_index, value)?;
}
Ok(())
}
/// 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
}
/// Indicate if the current environment stack has an object environment.
pub(crate) fn has_object_environment(&self) -> bool {
self.stack
.iter()
.any(|env| matches!(env, Environment::Object(_)))
}
}
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<()> {
if let Some(env) = self.vm.frame().environments.current_declarative_ref()
&& !env.with()
&& !env.poisoned()
{
return Ok(());
}
let (global, min_index) = match locator.scope() {
BindingLocatorScope::GlobalObject | BindingLocatorScope::GlobalDeclarative => (true, 0),
BindingLocatorScope::Stack(index) => (false, index),
};
let max_index = self.vm.frame().environments.stack.len() as u32;
for index in (min_index..max_index).rev() {
match self.environment_expect(index) {
Environment::Declarative(env) => {
if env.poisoned() {
if let Some(env) = env.kind().as_function()
&& let Some(b) = env.compile().get_binding(locator.name())
{
locator.set_scope(b.scope());
locator.set_binding_index(b.binding_index());
return Ok(());
}
} else if !env.with() {
return Ok(());
}
}
Environment::Object(o) => {
let o = o.clone();
let key = locator.name().clone();
if o.has_property(key.clone(), self)? {
if let Some(unscopables) = o.get(JsSymbol::unscopables(), self)?.as_object()
&& unscopables.get(key.clone(), self)?.to_boolean()
{
continue;
}
locator.set_scope(BindingLocatorScope::Stack(index));
return Ok(());
}
}
}
}
if global
&& self.realm().environment().poisoned()
&& let Some(b) = self.realm().scope().get_binding(locator.name())
{
locator.set_scope(b.scope());
locator.set_binding_index(b.binding_index());
}
Ok(())
}
/// Finds the object environment that contains the binding and returns the `this` value of the object environment.
pub(crate) fn this_from_object_environment_binding(
&mut self,
locator: &BindingLocator,
) -> JsResult<Option<JsObject>> {
if let Some(env) = self.vm.frame().environments.current_declarative_ref()
&& !env.with()
{
return Ok(None);
}
let min_index = match locator.scope() {
BindingLocatorScope::GlobalObject | BindingLocatorScope::GlobalDeclarative => 0,
BindingLocatorScope::Stack(index) => index,
};
let max_index = self.vm.frame().environments.stack.len() as u32;
for index in (min_index..max_index).rev() {
match self.environment_expect(index) {
Environment::Declarative(env) => {
if env.poisoned() {
if let Some(env) = env.kind().as_function()
&& env.compile().get_binding(locator.name()).is_some()
{
break;
}
} else if !env.with() {
break;
}
}
Environment::Object(o) => {
let o = o.clone();
let key = locator.name().clone();
if o.has_property(key.clone(), self)? {
if let Some(unscopables) = o.get(JsSymbol::unscopables(), self)?.as_object()
&& unscopables.get(key.clone(), self)?.to_boolean()
{
continue;
}
return Ok(Some(o));
}
}
}
}
Ok(None)
}
/// 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> {
match locator.scope() {
BindingLocatorScope::GlobalObject => {
let key = locator.name().clone();
let obj = self.global_object();
obj.has_property(key, self)
}
BindingLocatorScope::GlobalDeclarative => {
let env = self.vm.frame().environments.global();
Ok(env.get(locator.binding_index()).is_some())
}
BindingLocatorScope::Stack(index) => match self.environment_expect(index) {
Environment::Declarative(env) => Ok(env.get(locator.binding_index()).is_some()),
Environment::Object(obj) => {
let key = locator.name().clone();
let obj = obj.clone();
obj.has_property(key, self)
}
},
}
}
/// Get the value of a binding.
///
/// # Panics
///
/// Panics if the environment or binding index are out of range.
#[track_caller]
pub(crate) fn get_binding(&mut self, locator: &BindingLocator) -> JsResult<Option<JsValue>> {
match locator.scope() {
BindingLocatorScope::GlobalObject => {
let key = locator.name().clone();
let obj = self.global_object();
obj.try_get(key, self)
}
BindingLocatorScope::GlobalDeclarative => {
let env = self.vm.frame().environments.global();
Ok(env.get(locator.binding_index()))
}
BindingLocatorScope::Stack(index) => match self.environment_expect(index) {
Environment::Declarative(env) => Ok(env.get(locator.binding_index())),
Environment::Object(obj) => {
let key = locator.name().clone();
let obj = obj.clone();
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<()> {
match locator.scope() {
BindingLocatorScope::GlobalObject => {
let key = locator.name().clone();
let obj = self.global_object();
obj.set(key, value, strict, self)?;
}
BindingLocatorScope::GlobalDeclarative => {
let env = self.vm.frame().environments.global();
env.set(locator.binding_index(), value)?;
}
BindingLocatorScope::Stack(index) => match self.environment_expect(index) {
Environment::Declarative(decl) => {
decl.set(locator.binding_index(), value)?;
}
Environment::Object(obj) => {
let key = locator.name().clone();
let obj = obj.clone();
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> {
match locator.scope() {
BindingLocatorScope::GlobalObject => {
let key = locator.name().clone();
let obj = self.global_object();
obj.__delete__(&key.into(), &mut self.into())
}
BindingLocatorScope::GlobalDeclarative => Ok(false),
BindingLocatorScope::Stack(index) => match self.environment_expect(index) {
Environment::Declarative(_) => Ok(false),
Environment::Object(obj) => {
let key = locator.name().clone();
let obj = obj.clone();
obj.__delete__(&key.into(), &mut self.into())
}
},
}
}
/// Return the environment at the given index.
///
/// # Panics
///
/// Panics if the `index` is out of range.
pub(crate) fn environment_expect(&self, index: u32) -> &Environment {
self.vm
.frame()
.environments
.stack
.get(index as usize)
.expect("environment index must be in range")
}
}