This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 425
/
function.js
1497 lines (1275 loc) · 58.3 KB
/
function.js
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
/**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/* @flow */
import type { LexicalEnvironment } from "../environment.js";
import type { PropertyKeyValue } from "../types.js";
import { FatalError } from "../errors.js";
import type { Realm } from "../realm.js";
import type { ECMAScriptFunctionValue } from "../values/index.js";
import {
AbruptCompletion,
Completion,
JoinedNormalAndAbruptCompletions,
ReturnCompletion,
SimpleNormalCompletion,
} from "../completions.js";
import { GlobalEnvironmentRecord, ObjectEnvironmentRecord } from "../environment.js";
import {
AbstractValue,
AbstractObjectValue,
BoundFunctionValue,
ECMAScriptSourceFunctionValue,
EmptyValue,
FunctionValue,
NumberValue,
ObjectValue,
StringValue,
SymbolValue,
UndefinedValue,
Value,
} from "../values/index.js";
import { OrdinaryCallEvaluateBody, OrdinaryCallBindThis, PrepareForOrdinaryCall, Call } from "./call.js";
import { SameValue } from "../methods/abstract.js";
import { Construct } from "../methods/construct.js";
import { UpdateEmpty } from "../methods/index.js";
import { CreateListIterator } from "../methods/iterator.js";
import { EvalPropertyName } from "../evaluators/ObjectExpression.js";
import { Create, Environment, Join, Properties } from "../singletons.js";
import traverseFast from "../utils/traverse-fast.js";
import invariant from "../invariant.js";
import parse from "../utils/parse.js";
import IsStrict from "../utils/strict.js";
import type {
BabelNode,
BabelNodeBlockStatement,
BabelNodeClassMethod,
BabelNodeDoWhileStatement,
BabelNodeForInStatement,
BabelNodeForOfStatement,
BabelNodeForStatement,
BabelNodeIfStatement,
BabelNodeLabeledStatement,
BabelNodeLVal,
BabelNodeObjectMethod,
BabelNodeProgram,
BabelNodeStatement,
BabelNodeSwitchStatement,
BabelNodeTryStatement,
BabelNodeVariableDeclaration,
BabelNodeWhileStatement,
BabelNodeWithStatement,
} from "@babel/types";
import * as t from "@babel/types";
function InternalCall(
realm: Realm,
F: ECMAScriptFunctionValue,
thisArgument: Value,
argsList: Array<Value>,
tracerIndex: number
): Value {
// 1. Assert: F is an ECMAScript function object.
invariant(F instanceof FunctionValue, "expected function value");
// Tracing: Give all registered tracers a chance to detour, wrapping around each other if needed.
while (tracerIndex < realm.tracers.length) {
let tracer = realm.tracers[tracerIndex];
let nextIndex = ++tracerIndex;
let detourResult = tracer.detourCall(F, thisArgument, argsList, undefined, () =>
InternalCall(realm, F, thisArgument, argsList, nextIndex)
);
if (detourResult instanceof Value) return detourResult;
}
// 2. If F's [[FunctionKind]] internal slot is "classConstructor", throw a TypeError exception.
if (F.$FunctionKind === "classConstructor")
throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not callable");
// 3. Let callerContext be the running execution context.
let callerContext = realm.getRunningContext();
// 4. Let calleeContext be PrepareForOrdinaryCall(F, undefined).
let calleeContext = PrepareForOrdinaryCall(realm, F, undefined);
let calleeEnv = calleeContext.lexicalEnvironment;
let result;
try {
for (let t1 of realm.tracers) t1.beforeCall(F, thisArgument, argsList, undefined);
// 5. Assert: calleeContext is now the running execution context.
invariant(realm.getRunningContext() === calleeContext, "calleeContext should be current execution context");
// 6. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
OrdinaryCallBindThis(realm, F, calleeContext, thisArgument);
// 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList).
result = OrdinaryCallEvaluateBody(realm, F, argsList);
} finally {
// 8. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
realm.popContext(calleeContext);
realm.onDestroyScope(calleeContext.lexicalEnvironment);
if (calleeContext.lexicalEnvironment !== calleeEnv) realm.onDestroyScope(calleeEnv);
invariant(realm.getRunningContext() === callerContext);
for (let t2 of realm.tracers) t2.afterCall(F, thisArgument, argsList, undefined, (result: any));
}
// 9. If result.[[Type]] is return, return NormalCompletion(result.[[Value]]).
if (result instanceof ReturnCompletion) {
return result.value;
}
// 10. ReturnIfAbrupt(result).
if (result instanceof AbruptCompletion) {
throw result;
}
// 11. Return NormalCompletion(undefined).
return realm.intrinsics.undefined;
}
// ECMA262 9.4.1.1
function $BoundCall(realm: Realm, F: BoundFunctionValue, thisArgument: Value, argumentsList: Array<Value>): Value {
// 1. Let target be the value of F's [[BoundTargetFunction]] internal slot.
let target = F.$BoundTargetFunction;
// 2. Let boundThis be the value of F's [[BoundThis]] internal slot.
let boundThis = F.$BoundThis;
// 3. Let boundArgs be the value of F's [[BoundArguments]] internal slot.
let boundArgs = F.$BoundArguments;
// 4. Let args be a new list containing the same values as the list boundArgs in the same order followed
// by the same values as the list argumentsList in the same order.
let args = boundArgs.concat(argumentsList);
// 5. Return ? Call(target, boundThis, args).
return Call(realm, target, boundThis, args);
}
// ECMA262 9.4.1.2
function $BoundConstruct(
realm: Realm,
F: BoundFunctionValue,
argumentsList: Array<Value>,
newTarget: ObjectValue
): ObjectValue {
// 1. Let target be the value of F's [[BoundTargetFunction]] internal slot.
let target = F.$BoundTargetFunction;
// 2. Assert: target has a [[Construct]] internal method.
invariant(target.$Construct !== undefined, "doesn't have a construct internal method");
// 3. Let boundArgs be the value of F's [[BoundArguments]] internal slot.
let boundArgs = F.$BoundArguments;
// 4. Let args be a new list containing the same values as the list boundArgs in the same order followed
// by the same values as the list argumentsList in the same order.
let args = boundArgs.concat(argumentsList);
// 5. If SameValue(F, newTarget) is true, let newTarget be target.
if (SameValue(realm, F, newTarget)) newTarget = target;
// 6. Return ? Construct(target, args, newTarget).
return Construct(realm, target, args, newTarget);
}
function InternalConstruct(
realm: Realm,
F: ECMAScriptFunctionValue,
argumentsList: Array<Value>,
newTarget: ObjectValue,
thisArgument: void | ObjectValue,
tracerIndex: number
): ObjectValue {
// 1. Assert: F is an ECMAScript function object.
invariant(F instanceof FunctionValue, "expected function");
// 2. Assert: Type(newTarget) is Object.
invariant(newTarget instanceof ObjectValue, "expected object");
if (!realm.hasRunningContext()) {
invariant(realm.useAbstractInterpretation);
throw new FatalError("no running context");
}
// 3. Let callerContext be the running execution context.
let callerContext = realm.getRunningContext();
// 4. Let kind be F's [[ConstructorKind]] internal slot.
let kind = F.$ConstructorKind;
// 5. If kind is "base", then
if (thisArgument === undefined && kind === "base") {
// a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%ObjectPrototype%").
thisArgument = Create.OrdinaryCreateFromConstructor(realm, newTarget, "ObjectPrototype");
}
// Tracing: Give all registered tracers a chance to detour, wrapping around each other if needed.
while (tracerIndex < realm.tracers.length) {
let tracer = realm.tracers[tracerIndex];
let nextIndex = ++tracerIndex;
let detourResult = tracer.detourCall(F, thisArgument, argumentsList, newTarget, () =>
InternalConstruct(realm, F, argumentsList, newTarget, thisArgument, nextIndex)
);
if (detourResult instanceof ObjectValue) return detourResult;
invariant(detourResult === undefined);
}
// 6. Let calleeContext be PrepareForOrdinaryCall(F, newTarget).
let calleeContext = PrepareForOrdinaryCall(realm, F, newTarget);
let calleeEnv = calleeContext.lexicalEnvironment;
// 7. Assert: calleeContext is now the running execution context.
invariant(realm.getRunningContext() === calleeContext, "expected calleeContext to be running context");
let result, envRec;
try {
for (let t1 of realm.tracers) t1.beforeCall(F, thisArgument, argumentsList, newTarget);
// 8. If kind is "base", perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
if (kind === "base") {
invariant(thisArgument, "this wasn't initialized for some reason");
OrdinaryCallBindThis(realm, F, calleeContext, thisArgument);
}
// 9. Let constructorEnv be the LexicalEnvironment of calleeContext.
let constructorEnv = calleeContext.lexicalEnvironment;
// 10. Let envRec be constructorEnv's EnvironmentRecord.
envRec = constructorEnv.environmentRecord;
// 11. Let result be OrdinaryCallEvaluateBody(F, argumentsList).
result = OrdinaryCallEvaluateBody(realm, F, argumentsList);
} finally {
// 12. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
realm.popContext(calleeContext);
realm.onDestroyScope(calleeContext.lexicalEnvironment);
if (calleeContext.lexicalEnvironment !== calleeEnv) realm.onDestroyScope(calleeEnv);
invariant(realm.getRunningContext() === callerContext);
for (let t2 of realm.tracers) t2.afterCall(F, thisArgument, argumentsList, newTarget, result);
}
// 13. If result.[[Type]] is return, then
if (result instanceof ReturnCompletion) {
// a. If Type(result.[[Value]]) is Object, return NormalCompletion(result.[[Value]]).
if (result.value.mightBeObject()) {
return result.value.throwIfNotConcreteObject();
}
// b. If kind is "base", return NormalCompletion(thisArgument).
if (kind === "base") {
invariant(thisArgument, "this wasn't initialized for some reason");
return thisArgument;
}
// c. If result.[[Value]] is not undefined, throw a TypeError exception.
if (!result.value.mightBeUndefined())
throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "constructor must return Object");
result.value.throwIfNotConcrete();
} else if (result instanceof AbruptCompletion) {
// 14. Else, ReturnIfAbrupt(result).
throw result;
}
// 15. Return ? envRec.GetThisBinding().
let envRecThisBinding = envRec.GetThisBinding();
invariant(envRecThisBinding instanceof ObjectValue);
return envRecThisBinding;
}
export class FunctionImplementation {
FindVarScopedDeclarations(ast_node: BabelNode): Array<BabelNode> {
function FindVarScopedDeclarationsFor(ast: BabelNode, level: number) {
let statements = [];
switch (ast.type) {
case "Program":
statements = ((ast: any): BabelNodeProgram).body;
break;
case "BlockStatement":
statements = ((ast: any): BabelNodeBlockStatement).body;
break;
case "DoWhileStatement":
statements = [((ast: any): BabelNodeDoWhileStatement).body];
break;
case "WhileStatement":
statements = [((ast: any): BabelNodeWhileStatement).body];
break;
case "IfStatement":
let astIfStatement: BabelNodeIfStatement = (ast: any);
statements = [astIfStatement.consequent, astIfStatement.alternate];
break;
case "ForStatement":
let astForStatement: BabelNodeForStatement = (ast: any);
statements = [astForStatement.init, astForStatement.body];
break;
case "ForInStatement":
let astForInStatement: BabelNodeForInStatement = (ast: any);
statements = [astForInStatement.left, astForInStatement.body];
break;
case "ForOfStatement":
let astForOfStatement: BabelNodeForOfStatement = (ast: any);
statements = [astForOfStatement.left, astForOfStatement.body];
break;
case "LabeledStatement":
statements = [((ast: any): BabelNodeLabeledStatement).body];
break;
case "WithStatement":
statements = [((ast: any): BabelNodeWithStatement).body];
break;
case "SwitchStatement":
for (let switchCase of ((ast: any): BabelNodeSwitchStatement).cases) {
statements.push(...switchCase.consequent);
}
break;
case "TryStatement":
let astTryStatement: BabelNodeTryStatement = (ast: any);
statements = [astTryStatement.block];
if (astTryStatement.finalizer) statements.push(astTryStatement.finalizer);
if (astTryStatement.handler) statements.push(astTryStatement.handler.body);
break;
case "VariableDeclaration":
return ((ast: any): BabelNodeVariableDeclaration).kind === "var" ? [ast] : [];
case "FunctionDeclaration":
return level < 2 ? [ast] : [];
default:
return [];
}
let decls = [];
for (let statement of statements) {
if (statement) {
decls = decls.concat(FindVarScopedDeclarationsFor(statement, level + 1));
}
}
return decls;
}
return FindVarScopedDeclarationsFor(ast_node, 0);
}
// ECMA262 9.2.12
FunctionDeclarationInstantiation(
realm: Realm,
func: ECMAScriptSourceFunctionValue,
argumentsList: Array<Value>
): EmptyValue {
// 1. Let calleeContext be the running execution context.
let calleeContext = realm.getRunningContext();
// 2. Let env be the LexicalEnvironment of calleeContext.
let env = calleeContext.lexicalEnvironment;
// 3. Let envRec be env's EnvironmentRecord.
let envRec = env.environmentRecord;
// 4. Let code be the value of the [[ECMAScriptCode]] internal slot of func.
let code = func.$ECMAScriptCode;
invariant(code !== undefined);
// 5. Let strict be the value of the [[Strict]] internal slot of func.
let strict = func.$Strict;
// 6. Let formals be the value of the [[FormalParameters]] internal slot of func.
let formals = func.$FormalParameters;
invariant(formals !== undefined);
// 7. Let parameterNames be the BoundNames of formals.
let parameterNames = Object.create(null);
for (let param of formals) {
let paramBindings = t.getBindingIdentifiers(param, true);
for (let name in paramBindings) {
parameterNames[name] = (parameterNames[name] || []).concat(paramBindings[name]);
}
}
// 8. If parameterNames has any duplicate entries, let hasDuplicates be true. Otherwise, let hasDuplicates be false.
let hasDuplicates = false;
for (let name in parameterNames) {
let identifiers = parameterNames[name];
if (identifiers.length > 1) hasDuplicates = true;
}
parameterNames = Object.keys(parameterNames);
// 9. Let simpleParameterList be IsSimpleParameterList of formals.
let simpleParameterList = true;
for (let param of formals) {
if (param.type !== "Identifier") {
simpleParameterList = false;
break;
}
}
// 10. Let hasParameterExpressions be ContainsExpression of formals.
let hasParameterExpressions = false;
invariant(formals !== undefined);
for (let param of formals) {
if (Environment.ContainsExpression(realm, param)) {
hasParameterExpressions = true;
break;
}
}
// 11. Let varNames be the VarDeclaredNames of code.
let varNames = [];
traverseFast(code, node => {
if (node.type === "VariableDeclaration" && ((node: any): BabelNodeVariableDeclaration).kind === "var") {
varNames = varNames.concat(Object.keys(t.getBindingIdentifiers(node)));
}
if (node.type === "FunctionExpression" || node.type === "FunctionDeclaration") {
return true;
}
return false;
});
// 12. Let varDeclarations be the VarScopedDeclarations of code.
let varDeclarations = this.FindVarScopedDeclarations(code);
// 13. Let lexicalNames be the LexicallyDeclaredNames of code.
let lexicalNames = [];
// 14. Let functionNames be an empty List.
let functionNames = [];
// 15. Let functionsToInitialize be an empty List.
let functionsToInitialize = [];
// 16. For each d in varDeclarations, in reverse list order do
for (let d of varDeclarations.reverse()) {
// a. If d is neither a VariableDeclaration or a ForBinding, then
if (d.type !== "VariableDeclaration") {
// i. Assert: d is either a FunctionDeclaration or a GeneratorDeclaration.
invariant(d.type === "FunctionDeclaration" || d.type === "GeneratorDeclaration");
// ii. Let fn be the sole element of the BoundNames of d.
let fn = Environment.BoundNames(realm, d)[0];
// iii. If fn is not an element of functionNames, then
if (functionNames.indexOf(fn) < 0) {
// 1. Insert fn as the first element of functionNames.
functionNames.unshift(fn);
// 2. NOTE If there are multiple FunctionDeclarations or GeneratorDeclarations for the same name, the last declaration is used.
// 3. Insert d as the first element of functionsToInitialize.
functionsToInitialize.unshift(d);
}
}
}
// 17. Let argumentsObjectNeeded be true.
let argumentsObjectNeeded = true;
// 18. If the value of the [[realmMode]] internal slot of func is lexical, then
if (func.$ThisMode === "lexical") {
// a. NOTE Arrow functions never have an arguments objects.
// b. Let argumentsObjectNeeded be false.
argumentsObjectNeeded = false;
} else if (parameterNames.indexOf("arguments") >= 0) {
// 19. Else if "arguments" is an element of parameterNames, then
// a. Let argumentsObjectNeeded be false.
argumentsObjectNeeded = false;
} else if (hasParameterExpressions === false) {
// 20. Else if hasParameterExpressions is false, then
// a. If "arguments" is an element of functionNames or if "arguments" is an element of lexicalNames, then
if (functionNames.indexOf("arguments") >= 0 || lexicalNames.indexOf("arguments") >= 0) {
// i. Let argumentsObjectNeeded be false.
argumentsObjectNeeded = true;
}
}
// 21. For each String paramName in parameterNames, do
for (let paramName of parameterNames) {
// a. Let alreadyDeclared be envRec.HasBinding(paramName).
let alreadyDeclared = envRec.HasBinding(paramName);
// b. NOTE Early errors ensure that duplicate parameter names can only occur in non-strict functions that do not have parameter default values or rest parameters.
// c. If alreadyDeclared is false, then
if (alreadyDeclared === false) {
// i. Perform ! envRec.CreateMutableBinding(paramName, false).
envRec.CreateMutableBinding(paramName, false);
// ii. If hasDuplicates is true, then
if (hasDuplicates === true) {
// 1. Perform ! envRec.InitializeBinding(paramName, undefined).
envRec.InitializeBinding(paramName, realm.intrinsics.undefined);
}
}
}
// 22. If argumentsObjectNeeded is true, then
if (argumentsObjectNeeded === true) {
let ao;
// a. If strict is true or if simpleParameterList is false, then
if (strict === true || simpleParameterList === false) {
// i. Let ao be CreateUnmappedArgumentsObject(argumentsList).
ao = Create.CreateUnmappedArgumentsObject(realm, argumentsList);
} else {
// b. Else,
// i. NOTE mapped argument object is only provided for non-strict functions that don't have a rest parameter, any parameter default value initializers, or any destructured parameters.
// ii. Let ao be CreateMappedArgumentsObject(func, formals, argumentsList, envRec).
invariant(formals !== undefined);
ao = Create.CreateMappedArgumentsObject(realm, func, formals, argumentsList, envRec);
}
// c. If strict is true, then
if (strict === true) {
// i. Perform ! envRec.CreateImmutableBinding("arguments", false).
envRec.CreateImmutableBinding("arguments", false);
} else {
// d. Else,
// i. Perform ! envRec.CreateMutableBinding("arguments", false).
envRec.CreateMutableBinding("arguments", false);
}
// e. Call envRec.InitializeBinding("arguments", ao).
envRec.InitializeBinding("arguments", ao);
// f. Append "arguments" to parameterNames.
parameterNames.push("arguments");
}
// 23. Let iteratorRecord be Record {[[Iterator]]: CreateListIterator(argumentsList), [[Done]]: false}.
let iteratorRecord = {
$Iterator: CreateListIterator(realm, argumentsList),
$Done: false,
};
// 24. If hasDuplicates is true, then
if (hasDuplicates === true) {
// a. Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
invariant(formals !== undefined);
Environment.IteratorBindingInitialization(realm, formals, iteratorRecord, strict);
} else {
// 25. Else,
// a. Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
invariant(formals !== undefined);
Environment.IteratorBindingInitialization(realm, formals, iteratorRecord, strict, env);
}
// 26. If hasParameterExpressions is false, then
let varEnv, varEnvRec;
if (hasParameterExpressions === false) {
// a. NOTE Only a single lexical environment is needed for the parameters and top-level vars.
// b. Let instantiatedVarNames be a copy of the List parameterNames.
let instantiatedVarNames = parameterNames.slice();
// c. For each n in varNames, do
for (let n of varNames) {
// i. If n is not an element of instantiatedVarNames, then
if (instantiatedVarNames.indexOf(n) < 0) {
// 1. Append n to instantiatedVarNames.
instantiatedVarNames.push(n);
// 2. Perform ! envRec.CreateMutableBinding(n, false).
envRec.CreateMutableBinding(n, false);
// 3. Call envRec.InitializeBinding(n, undefined).
envRec.InitializeBinding(n, realm.intrinsics.undefined);
}
}
// e. Let varEnv be env.
varEnv = env;
// f. Let varEnvRec be envRec.
varEnvRec = envRec;
} else {
// 27. Else,
// a. NOTE A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body.
// b. Let varEnv be NewDeclarativeEnvironment(env).
varEnv = Environment.NewDeclarativeEnvironment(realm, env);
// At this point we haven't set any context's lexical environment to varEnv (and we might never do so),
// so it shouldn't be active
realm.activeLexicalEnvironments.delete(varEnv);
// c. Let varEnvRec be varEnv's EnvironmentRecord.
varEnvRec = varEnv.environmentRecord;
// d. Set the VariableEnvironment of calleeContext to varEnv.
calleeContext.variableEnvironment = varEnv;
// e. Let instantiatedVarNames be a new empty List.
let instantiatedVarNames = [];
// f. For each n in varNames, do
for (let n of varNames) {
// i. If n is not an element of instantiatedVarNames, then
if (instantiatedVarNames.indexOf(n) < 0) {
// 1. Append n to instantiatedVarNames.
instantiatedVarNames.push(n);
// 2. Perform ! varEnvRec.CreateMutableBinding(n, false).
varEnvRec.CreateMutableBinding(n, false);
// 3. If n is not an element of parameterNames or if n is an element of functionNames, let initialValue be undefined.
let initialValue;
if (parameterNames.indexOf(n) < 0 || functionNames.indexOf(n) < 0) {
initialValue = realm.intrinsics.undefined;
} else {
// 4. Else,
// a. Let initialValue be ! envRec.GetBindingValue(n, false).
initialValue = envRec.GetBindingValue(n, false);
}
// 5. Call varEnvRec.InitializeBinding(n, initialValue).
varEnvRec.InitializeBinding(n, initialValue);
// 6. NOTE vars whose names are the same as a formal parameter, initially have the same value as the corresponding initialized parameter.
}
}
}
// 28. NOTE: Annex B.3.3.1 adds additional steps at realm point.
let lexEnv;
// 29. If strict is false, then
if (strict === false) {
// a. Let lexEnv be NewDeclarativeEnvironment(varEnv).
lexEnv = Environment.NewDeclarativeEnvironment(realm, varEnv);
// b. NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations so that a direct eval (see 12.3.4.1) can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level lexically scoped declarations. realm is not needed for strict functions because a strict direct eval always places all declarations into a new Environment Record.
} else {
// 30. Else, let lexEnv be varEnv.
lexEnv = varEnv;
// Since we previously removed varEnv, make sure to re-add it when it's used.
realm.activeLexicalEnvironments.add(varEnv);
}
// 31. Let lexEnvRec be lexEnv's EnvironmentRecord.
let lexEnvRec = lexEnv.environmentRecord;
// 32. Set the LexicalEnvironment of calleeContext to lexEnv.
calleeContext.lexicalEnvironment = lexEnv;
// 33. Let lexDeclarations be the LexicallyScopedDeclarations of code.
let lexDeclarations = [];
// 34. For each element d in lexDeclarations do
for (let d of lexDeclarations) {
// a. NOTE A lexically declared name cannot be the same as a function/generator declaration, formal parameter, or a var name. Lexically declared names are only instantiated here but not initialized.
// b. For each element dn of the BoundNames of d do
for (let dn of Environment.BoundNames(realm, d)) {
// i. If IsConstantDeclaration of d is true, then
if (d.kind === "const") {
// 1. Perform ! lexEnvRec.CreateImmutableBinding(dn, true).
lexEnvRec.CreateImmutableBinding(dn, true);
} else {
// ii. Else,
// 1. Perform ! lexEnvRec.CreateMutableBinding(dn, false).
lexEnvRec.CreateMutableBinding(dn, false);
}
}
}
// 35. For each parsed grammar phrase f in functionsToInitialize, do
for (let f of functionsToInitialize) {
// a. Let fn be the sole element of the BoundNames of f.
let fn = Environment.BoundNames(realm, f)[0];
// b. Let fo be the result of performing InstantiateFunctionObject for f with argument lexEnv.
let fo = lexEnv.evaluate(f, strict);
invariant(fo instanceof Value);
// c. Perform ! varEnvRec.SetMutableBinding(fn, fo, false).
varEnvRec.SetMutableBinding(fn, fo, false);
}
// 36. Return NormalCompletion(empty).
return realm.intrinsics.empty;
}
// ECMA262 9.2.11
SetFunctionName(realm: Realm, F: ObjectValue, _name: PropertyKeyValue | AbstractValue, prefix?: string): boolean {
// 1. Assert: F is an extensible object that does not have a name own property.
invariant(F.getExtensible(), "expected object to be extensible and not have a name property");
// 2. Assert: Type(name) is either Symbol or String.
invariant(
typeof _name === "string" ||
_name instanceof StringValue ||
_name instanceof SymbolValue ||
_name instanceof AbstractValue,
"expected name to be a string or symbol"
);
let name = typeof _name === "string" ? new StringValue(realm, _name) : _name;
// 3. Assert: If prefix was passed, then Type(prefix) is String.
invariant(prefix === undefined || typeof prefix === "string", "expected prefix to be a string if passed");
// 4. If Type(name) is Symbol, then
if (name instanceof SymbolValue) {
// a. Let description be name's [[Description]] value.
let description = name.$Description;
// b. If description is undefined, let name be the empty String.
if (description === undefined) {
name = realm.intrinsics.emptyString;
} else {
// c. Else, let name be the concatenation of "[", description, and "]".
invariant(description instanceof Value);
name = new StringValue(realm, `[${description.throwIfNotConcreteString().value}]`);
}
}
// 5. If prefix was passed, then
if (prefix) {
// a. Let name be the concatenation of prefix, code unit 0x0020 (SPACE), and name.
if (name instanceof AbstractValue) {
let prefixVal = new StringValue(realm, prefix + " ");
name = AbstractValue.createFromBinaryOp(realm, "+", prefixVal, name, name.expressionLocation);
} else {
name = new StringValue(realm, `${prefix} ${name.value}`);
}
}
// 6. Return ! DefinePropertyOrThrow(F, "name", PropertyDescriptor{[[Value]]: name, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true}).
return Properties.DefinePropertyOrThrow(realm, F, "name", {
value: name,
enumerable: false,
writable: false,
configurable: true,
});
}
// ECMA262 9.2.3
FunctionInitialize(
realm: Realm,
F: ECMAScriptSourceFunctionValue,
kind: "normal" | "method" | "arrow",
ParameterList: Array<BabelNodeLVal>,
Body: BabelNodeBlockStatement,
Scope: LexicalEnvironment
): ECMAScriptSourceFunctionValue {
// Tell the realm to mark any local bindings that are visible to this function as being potentially captured by it.
realm.markVisibleLocalBindingsAsPotentiallyCaptured();
// Note that F is a new object, and we can thus write to internal slots
invariant(realm.isNewObject(F));
// 1. Assert: F is an extensible object that does not have a length own property.
invariant(F.getExtensible(), "expected to be extensible and no length property");
// 2. Let len be the ExpectedArgumentCount of ParameterList.
let len = 0;
for (let FormalParameter of ParameterList) {
if (FormalParameter.type === "AssignmentPattern") {
break;
}
len += 1;
}
// 3. Perform ! DefinePropertyOrThrow(F, "length", PropertyDescriptor{[[Value]]: len, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true}).
Properties.DefinePropertyOrThrow(realm, F, "length", {
value: new NumberValue(realm, len),
writable: false,
enumerable: false,
configurable: true,
});
// 4. Let Strict be the value of the [[Strict]] internal slot of F.
let Strict = F.$Strict;
if (!Strict) {
Properties.DefinePropertyOrThrow(realm, F, "caller", {
value: new UndefinedValue(realm),
writable: true,
enumerable: false,
configurable: true,
});
}
// 5. Set the [[Environment]] internal slot of F to the value of Scope.
F.$Environment = Scope;
// 6. Set the [[FormalParameters]] internal slot of F to ParameterList. + 7. Set the [[ECMAScriptCode]] internal slot of F to Body.
F.initialize(ParameterList, Body);
// 8. Set the [[ScriptOrModule]] internal slot of F to GetActiveScriptOrModule().
F.$ScriptOrModule = Environment.GetActiveScriptOrModule(realm);
// 9. If kind is Arrow, set the [[realmMode]] internal slot of F to lexical.
if (kind === "arrow") {
F.$ThisMode = "lexical";
} else if (Strict === true) {
// 10. Else if Strict is true, set the [[realmMode]] internal slot of F to strict.
F.$ThisMode = "strict";
} else {
// 11. Else set the [[realmMode]] internal slot of F to global.
F.$ThisMode = "global";
}
// Return F.
return F;
}
// ECMA262 9.2.6
GeneratorFunctionCreate(
realm: Realm,
kind: "normal" | "method",
ParameterList: Array<BabelNodeLVal>,
Body: BabelNodeBlockStatement,
Scope: LexicalEnvironment,
Strict: boolean
): ECMAScriptSourceFunctionValue {
// 1. Let functionPrototype be the intrinsic object %Generator%.
let functionPrototype = realm.intrinsics.Generator;
// 2. Let F be FunctionAllocate(functionPrototype, Strict, "generator").
let F = this.FunctionAllocate(realm, functionPrototype, Strict, "generator");
// 3. Return FunctionInitialize(F, kind, ParameterList, Body, Scope).
return this.FunctionInitialize(realm, F, kind, ParameterList, Body, Scope);
}
// ECMA262 9.2.7
AddRestrictedFunctionProperties(F: FunctionValue, realm: Realm): boolean {
// 1. Assert: realm.[[Intrinsics]].[[%ThrowTypeError%]] exists and has been initialized.
// 2. Let thrower be realm.[[Intrinsics]].[[%ThrowTypeError%]].
let thrower = realm.intrinsics.ThrowTypeError;
invariant(thrower);
let desc = {
get: thrower,
set: thrower,
enumerable: false,
configurable: true,
};
// 3. Perform ! DefinePropertyOrThrow(F, "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true}).
Properties.DefinePropertyOrThrow(realm, F, "caller", desc);
// 4. Return ! DefinePropertyOrThrow(F, "arguments", PropertyDescriptor {[[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true}).
return Properties.DefinePropertyOrThrow(realm, F, "arguments", desc);
}
// ECMA262 9.2.1
$Call(realm: Realm, F: ECMAScriptFunctionValue, thisArgument: Value, argsList: Array<Value>): Value {
return InternalCall(realm, F, thisArgument, argsList, 0);
}
// ECMA262 9.2.2
$Construct(
realm: Realm,
F: ECMAScriptFunctionValue,
argumentsList: Array<Value>,
newTarget: ObjectValue
): ObjectValue {
return InternalConstruct(realm, F, argumentsList, newTarget, undefined, 0);
}
// ECMA262 9.2.3
FunctionAllocate(
realm: Realm,
functionPrototype: ObjectValue | AbstractObjectValue,
strict: boolean,
functionKind: "normal" | "non-constructor" | "generator"
): ECMAScriptSourceFunctionValue {
// 1. Assert: Type(functionPrototype) is Object.
invariant(functionPrototype instanceof ObjectValue, "expected functionPrototype to be an object");
// 2. Assert: functionKind is either "normal", "non-constructor" or "generator".
invariant(
functionKind === "normal" || functionKind === "non-constructor" || functionKind === "generator",
"invalid functionKind"
);
// 3. If functionKind is "normal", let needsConstruct be true.
let needsConstruct;
if (functionKind === "normal") {
needsConstruct = true;
} else {
// 4. Else, let needsConstruct be false.
needsConstruct = false;
}
// 5. If functionKind is "non-constructor", let functionKind be "normal".
if (functionKind === "non-constructor") {
functionKind = "normal";
}
// 6. Let F be a newly created ECMAScript function object with the internal slots listed in Table 27. All of those internal slots are initialized to undefined.
let F = new ECMAScriptSourceFunctionValue(realm);
// 7. Set F's essential internal methods to the default ordinary object definitions specified in 9.1.
// 8. Set F's [[Call]] internal method to the definition specified in 9.2.1.
F.$Call = (thisArgument, argsList) => {
return this.$Call(realm, F, thisArgument, argsList);
};
// 9. If needsConstruct is true, then
if (needsConstruct === true) {
// a. Set F's [[Construct]] internal method to the definition specified in 9.2.2.
F.$Construct = (argumentsList, newTarget) => {
return this.$Construct(realm, F, argumentsList, newTarget);
};
// b. Set the [[ConstructorKind]] internal slot of F to "base".
F.$ConstructorKind = "base";
}
// 10. Set the [[Strict]] internal slot of F to strict.
F.$Strict = strict;
// 11. Set the [[FunctionKind]] internal slot of F to functionKind.
F.$FunctionKind = functionKind;
// 12. Set the [[Prototype]] internal slot of F to functionPrototype.
F.$Prototype = functionPrototype;
// 13. Set the [[Extensible]] internal slot of F to true.
F.setExtensible(true);
// 14. Set the [[Realm]] internal slot of F to the current Realm Record.
F.$Realm = realm;
// 15. Return F.
return F;
}
// ECMA262 9.4.1.3
BoundFunctionCreate(
realm: Realm,
targetFunction: ObjectValue,
boundThis: Value,
boundArgs: Array<Value>
): ObjectValue {
// 1. Assert: Type(targetFunction) is Object.
invariant(targetFunction instanceof ObjectValue, "expected an object");
// 2. Let proto be ? targetFunction.[[GetPrototypeOf]]().
let proto = targetFunction.$GetPrototypeOf();
// 3. Let obj be a newly created object.
let obj = new BoundFunctionValue(realm);
// 4. Set obj's essential internal methods to the default ordinary object definitions specified in 9.1.
// 5. Set the [[Call]] internal method of obj as described in 9.4.1.1.
obj.$Call = (thisArgument, argsList) => {
return $BoundCall(realm, obj, thisArgument, argsList);
};
// 6. If targetFunction has a [[Construct]] internal method, then
if (targetFunction.$Construct) {
// a. Set the [[Construct]] internal method of obj as described in 9.4.1.2.
obj.$Construct = (thisArgument, argsList) => {
return $BoundConstruct(realm, obj, thisArgument, argsList);
};
}
// 7. Set the [[Prototype]] internal slot of obj to proto.
obj.$Prototype = proto;
// 8. Set the [[Extensible]] internal slot of obj to true.
obj.setExtensible(true);
// 9. Set the [[BoundTargetFunction]] internal slot of obj to targetFunction.
obj.$BoundTargetFunction = targetFunction;
// 10. Set the [[BoundThis]] internal slot of obj to the value of boundThis.
obj.$BoundThis = boundThis;
// 11. Set the [[BoundArguments]] internal slot of obj to boundArgs.
obj.$BoundArguments = boundArgs;
// 12. Return obj.
return obj;
}
// ECMA262 18.2.1.1
PerformEval(realm: Realm, x: Value, evalRealm: Realm, strictCaller: boolean, direct: boolean): Value {
// 1. Assert: If direct is false, then strictCaller is also false.
if (direct === false) invariant(strictCaller === false, "strictCaller is only allowed on direct eval");
// 2. If Type(x) is not String, return x.
if (!(x instanceof StringValue)) return x;
// 3. Let script be the ECMAScript code that is the result of parsing x, interpreted as UTF-16 encoded Unicode text
// as described in 6.1.4, for the goal symbol Script. If the parse fails, throw a SyntaxError exception. If any
// early errors are detected, throw a SyntaxError or a ReferenceError exception, depending on the type of the
// error (but see also clause 16). Parsing and early error detection may be interweaved in an implementation
// dependent manner.