/
BytecodeGenerator.cpp
5501 lines (4627 loc) · 233 KB
/
BytecodeGenerator.cpp
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) 2008-2021 Apple Inc. All rights reserved.
* Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
* Copyright (C) 2012 Igalia, S.L.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "BytecodeGenerator.h"
#include "AbstractModuleRecord.h"
#include "BuiltinExecutables.h"
#include "BuiltinNames.h"
#include "BytecodeGeneratorBaseInlines.h"
#include "BytecodeGeneratorification.h"
#include "BytecodeUseDef.h"
#include "CatchScope.h"
#include "DefinePropertyAttributes.h"
#include "Interpreter.h"
#include "JSAsyncGenerator.h"
#include "JSBigInt.h"
#include "JSCInlines.h"
#include "JSImmutableButterfly.h"
#include "JSTemplateObjectDescriptor.h"
#include "Options.h"
#include "PrivateFieldPutKind.h"
#include "StrongInlines.h"
#include "SuperSampler.h"
#include "UnlinkedCodeBlock.h"
#include "UnlinkedEvalCodeBlock.h"
#include "UnlinkedFunctionCodeBlock.h"
#include "UnlinkedMetadataTableInlines.h"
#include "UnlinkedModuleProgramCodeBlock.h"
#include "UnlinkedProgramCodeBlock.h"
#include "VMTrapsInlines.h"
#include <wtf/BitVector.h>
#include <wtf/HashSet.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/WTFString.h>
namespace JSC {
template<typename CallOp, typename = std::true_type>
struct VarArgsOp;
template<typename CallOp>
struct VarArgsOp<CallOp, std::enable_if_t<std::is_same<CallOp, OpTailCall>::value, std::true_type>> {
using type = OpTailCallVarargs;
};
template<typename CallOp>
struct VarArgsOp<CallOp, std::enable_if_t<!std::is_same<CallOp, OpTailCall>::value, std::true_type>> {
using type = OpCallVarargs;
};
template<>
void GenericLabel<JSGeneratorTraits>::setLocation(BytecodeGenerator& generator, unsigned location)
{
m_location = location;
for (auto offset : m_unresolvedJumps) {
auto instruction = generator.m_writer.ref(offset);
int target = m_location - offset;
#define CASE(__op) \
case __op::opcodeID: \
instruction->cast<__op>()->setTargetLabel(BoundLabel(target), [&]() { \
generator.m_codeBlock->addOutOfLineJumpTarget(instruction.offset(), target); \
return BoundLabel(); \
}); \
break;
switch (instruction->opcodeID()) {
CASE(OpJmp)
CASE(OpJtrue)
CASE(OpJfalse)
CASE(OpJeqNull)
CASE(OpJneqNull)
CASE(OpJundefinedOrNull)
CASE(OpJnundefinedOrNull)
CASE(OpJeq)
CASE(OpJstricteq)
CASE(OpJneq)
CASE(OpJeqPtr)
CASE(OpJneqPtr)
CASE(OpJnstricteq)
CASE(OpJless)
CASE(OpJlesseq)
CASE(OpJgreater)
CASE(OpJgreatereq)
CASE(OpJnless)
CASE(OpJnlesseq)
CASE(OpJngreater)
CASE(OpJngreatereq)
CASE(OpJbelow)
CASE(OpJbeloweq)
default:
ASSERT_NOT_REACHED();
}
#undef CASE
}
}
void Variable::dump(PrintStream& out) const
{
out.print(
"{ident = ", m_ident,
", offset = ", m_offset,
", local = ", RawPointer(m_local),
", attributes = ", m_attributes,
", kind = ", m_kind,
", symbolTableConstantIndex = ", m_symbolTableConstantIndex,
", isLexicallyScoped = ", m_isLexicallyScoped, "}");
}
FinallyContext::FinallyContext(BytecodeGenerator& generator, Label& finallyLabel)
: m_outerContext(generator.m_currentFinallyContext)
, m_finallyLabel(&finallyLabel)
{
ASSERT(m_jumps.isEmpty());
m_completionRecord.typeRegister = generator.newTemporary();
m_completionRecord.valueRegister = generator.newTemporary();
generator.emitLoad(completionTypeRegister(), CompletionType::Normal);
generator.moveEmptyValue(completionValueRegister());
}
template<typename EmitBytecodeFunctor>
void BytecodeGenerator::asyncFuncParametersTryCatchWrap(const EmitBytecodeFunctor& emitBytecode)
{
TryData* tryData = nullptr;
if (m_asyncFuncParametersTryCatchInfo) {
AsyncFuncParametersTryCatchInfo& info = m_asyncFuncParametersTryCatchInfo.value();
ASSERT(info.catchStartLabel && info.thrownValue);
Ref<Label> tryStartLabel = newEmittedLabel();
tryData = pushTry(tryStartLabel.get(), *info.catchStartLabel.get(), HandlerType::SynthesizedCatch);
}
emitBytecode();
if (m_asyncFuncParametersTryCatchInfo) {
AsyncFuncParametersTryCatchInfo& info = m_asyncFuncParametersTryCatchInfo.value();
Ref<Label> tryEndLabel = newEmittedLabel();
popTry(tryData, tryEndLabel.get());
emitOutOfLineCatchHandler(info.thrownValue.get(), nullptr, tryData);
}
}
ParserError BytecodeGenerator::generate(unsigned& size)
{
if (UNLIKELY(m_outOfMemoryDuringConstruction))
return ParserError(ParserError::OutOfMemory);
bool callingNonCallableConstructor = false;
switch (constructorKind()) {
case ConstructorKind::None:
break;
case ConstructorKind::Naked:
case ConstructorKind::Base:
case ConstructorKind::Extends:
callingNonCallableConstructor = !isConstructor();
break;
}
m_codeBlock->setThisRegister(m_thisRegister.virtualRegister());
emitLogShadowChickenPrologueIfNecessary();
if (!callingNonCallableConstructor) {
// If we have declared a variable named "arguments" and we are using arguments then we should
// perform that assignment now.
if (m_needToInitializeArguments)
initializeVariable(variable(propertyNames().arguments), m_argumentsRegister);
if (m_restParameter) {
// We should move moving m_restParameter->emit(*this) to initializeDefaultParameterValuesAndSetupFunctionScopeStack
// as an optimization if we can prove that change has no side effect.
asyncFuncParametersTryCatchWrap([&] {
m_restParameter->emit(*this);
});
}
{
RefPtr<RegisterID> temp = newTemporary();
RefPtr<RegisterID> tolLevelScope;
for (auto functionPair : m_functionsToInitialize) {
FunctionMetadataNode* metadata = functionPair.first;
FunctionVariableType functionType = functionPair.second;
emitNewFunction(temp.get(), metadata);
if (functionType == NormalFunctionVariable)
initializeVariable(variable(metadata->ident()), temp.get());
else if (functionType == TopLevelFunctionVariable) {
if (!tolLevelScope) {
// We know this will resolve to the top level scope or global object because our parser/global initialization code
// doesn't allow let/const/class variables to have the same names as functions.
// This is a top level function, and it's an error to ever create a top level function
// name that would resolve to a lexical variable. E.g:
// ```
// function f() {
// {
// let x;
// {
// //// error thrown here
// eval("function x(){}");
// }
// }
// }
// ```
// Therefore, we're guaranteed to have this resolve to a top level variable.
RefPtr<RegisterID> tolLevelObjectScope = emitResolveScope(nullptr, Variable(metadata->ident()));
tolLevelScope = newBlockScopeVariable();
move(tolLevelScope.get(), tolLevelObjectScope.get());
}
emitPutToScope(tolLevelScope.get(), Variable(metadata->ident()), temp.get(), ThrowIfNotFound, InitializationMode::NotInitialization);
} else
RELEASE_ASSERT_NOT_REACHED();
}
}
m_scopeNode->emitBytecode(*this);
} else {
// At this point we would have emitted an unconditional throw followed by some nonsense that's
// just an artifact of how this generator is structured. That code never runs, but it confuses
// bytecode analyses because it constitutes an unterminated basic block. So, we terminate the
// basic block the strongest way possible.
emitUnreachable();
}
for (auto& handler : m_exceptionHandlersToEmit) {
Ref<Label> realCatchTarget = newLabel();
TryData* tryData = handler.tryData;
OpCatch::emit(this, handler.exceptionRegister, handler.thrownValueRegister);
realCatchTarget->setLocation(*this, m_lastInstruction.offset());
if (handler.completionTypeRegister.isValid()) {
RegisterID completionTypeRegister { handler.completionTypeRegister };
CompletionType completionType =
tryData->handlerType == HandlerType::Finally || tryData->handlerType == HandlerType::SynthesizedFinally
? CompletionType::Throw
: CompletionType::Normal;
emitLoad(&completionTypeRegister, completionType);
}
m_codeBlock->addJumpTarget(m_lastInstruction.offset());
emitJump(tryData->target.get());
tryData->target = WTFMove(realCatchTarget);
}
if (m_asyncFuncParametersTryCatchInfo) {
AsyncFuncParametersTryCatchInfo& info = m_asyncFuncParametersTryCatchInfo.value();
ASSERT(info.catchStartLabel && info.thrownValue);
emitLabel(*info.catchStartLabel.get());
// @rejectPromiseWithFirstResolvingFunctionCallCheck(@promise, thrownValue);
// return @promise;
RefPtr<RegisterID> rejectPromise = moveLinkTimeConstant(nullptr, LinkTimeConstant::rejectPromiseWithFirstResolvingFunctionCallCheck);
CallArguments args(*this, nullptr, 2);
emitLoad(args.thisRegister(), jsUndefined());
move(args.argumentRegister(0), promiseRegister());
move(args.argumentRegister(1), info.thrownValue.get());
JSTextPosition divot(m_scopeNode->firstLine(), m_scopeNode->startOffset(), m_scopeNode->lineStartOffset());
emitCall(newTemporary(), rejectPromise.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
emitReturn(promiseRegister());
}
m_staticPropertyAnalyzer.kill();
for (auto& range : m_tryRanges) {
int start = range.start->bind();
int end = range.end->bind();
// This will happen for empty try blocks and for some cases of finally blocks:
//
// try {
// try {
// } finally {
// return 42;
// // *HERE*
// }
// } finally {
// print("things");
// }
//
// The return will pop scopes to execute the outer finally block. But this includes
// popping the try context for the inner try. The try context is live in the fall-through
// part of the finally block not because we will emit a handler that overlaps the finally,
// but because we haven't yet had a chance to plant the catch target. Then when we finish
// emitting code for the outer finally block, we repush the try contex, this time with a
// new start index. But that means that the start index for the try range corresponding
// to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
// than the end index of the try block. This is harmless since end < start handlers will
// never get matched in our logic, but we do the runtime a favor and choose to not emit
// such handlers at all.
if (end <= start)
continue;
UnlinkedHandlerInfo info(static_cast<uint32_t>(start), static_cast<uint32_t>(end),
static_cast<uint32_t>(range.tryData->target->bind()), range.tryData->handlerType);
m_codeBlock->addExceptionHandler(info);
}
if (m_isAsync)
performGeneratorification(*this, m_codeBlock.get(), m_writer, m_generatorFrameSymbolTable.get(), m_generatorFrameSymbolTableIndex);
RELEASE_ASSERT(m_codeBlock->numCalleeLocals() < static_cast<unsigned>(FirstConstantRegisterIndex));
size = instructions().size();
m_codeBlock->finalize(m_writer.finalize());
if (m_expressionTooDeep)
return ParserError(ParserError::OutOfMemory);
return ParserError(ParserError::ErrorNone);
}
BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, OptionSet<CodeGenerationMode> codeGenerationMode, const RefPtr<TDZEnvironmentLink>& parentScopeTDZVariables, const PrivateNameEnvironment*)
: BytecodeGeneratorBase(makeUnique<UnlinkedCodeBlockGenerator>(vm, codeBlock), CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters())
, m_codeGenerationMode(codeGenerationMode)
, m_scopeNode(programNode)
, m_thisRegister(CallFrame::thisArgumentOffset())
, m_codeType(GlobalCode)
, m_vm(vm)
, m_usesExceptions(false)
, m_expressionTooDeep(false)
, m_isBuiltinFunction(false)
, m_usesNonStrictEval(false)
, m_inTailPosition(false)
, m_needsToUpdateArrowFunctionContext(programNode->usesArrowFunction() || programNode->usesEval())
, m_ecmaMode(ECMAMode::fromBool(programNode->isStrictMode()))
{
ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables);
m_codeBlock->setNumParameters(1); // Allocate space for "this"
emitEnter();
allocateAndEmitScope();
emitCheckTraps();
const FunctionStack& functionStack = programNode->functionStack();
for (auto* function : functionStack)
m_functionsToInitialize.append(std::make_pair(function, TopLevelFunctionVariable));
if (Options::validateBytecode()) {
for (auto& entry : programNode->varDeclarations())
RELEASE_ASSERT(entry.value.isVar());
}
codeBlock->setVariableDeclarations(programNode->varDeclarations());
codeBlock->setLexicalDeclarations(programNode->lexicalVariables());
// Even though this program may have lexical variables that go under TDZ, when linking the get_from_scope/put_to_scope
// operations we emit we will have ResolveTypes that implictly do TDZ checks. Therefore, we don't need
// additional TDZ checks on top of those. This is why we can omit pushing programNode->lexicalVariables()
// to the TDZ stack.
if (needsToUpdateArrowFunctionContext()) {
initializeArrowFunctionContextScopeIfNeeded();
emitPutThisToArrowFunctionContextScope();
}
}
BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, OptionSet<CodeGenerationMode> codeGenerationMode, const RefPtr<TDZEnvironmentLink>& parentScopeTDZVariables, const PrivateNameEnvironment* parentPrivateNameEnvironment)
: BytecodeGeneratorBase(makeUnique<UnlinkedCodeBlockGenerator>(vm, codeBlock), CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters())
, m_codeGenerationMode(codeGenerationMode)
, m_scopeNode(functionNode)
, m_codeType(FunctionCode)
, m_vm(vm)
// FIXME: This should be a flag
, m_usesExceptions(false)
, m_expressionTooDeep(false)
, m_isBuiltinFunction(codeBlock->isBuiltinFunction())
, m_usesNonStrictEval(functionNode->usesEval() && !functionNode->isStrictMode())
// FIXME: We should be able to have tail call elimination with the profiler
// enabled. This is currently not possible because the profiler expects
// op_will_call / op_did_call pairs before and after a call, which are not
// compatible with tail calls (we have no way of emitting op_did_call).
// https://bugs.webkit.org/show_bug.cgi?id=148819
//
// Note that we intentionally enable tail call for naked constructors since it does not have special code for "return".
, m_inTailPosition(Options::useTailCalls() && !isConstructor() && constructorKind() == ConstructorKind::None && functionNode->isStrictMode())
, m_needsToUpdateArrowFunctionContext(functionNode->usesArrowFunction() || functionNode->usesEval())
, m_ecmaMode(ECMAMode::fromBool(functionNode->isStrictMode()))
, m_derivedContextType(codeBlock->derivedContextType())
{
ECMAMode ecmaMode = m_ecmaMode;
pushPrivateAccessNames(parentPrivateNameEnvironment);
SymbolTable* functionSymbolTable = SymbolTable::create(m_vm);
functionSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
int symbolTableConstantIndex = 0;
m_cachedParentTDZ = parentScopeTDZVariables;
FunctionParameters& parameters = *functionNode->parameters();
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
// This implements IsSimpleParameterList in the Ecma 2015 spec.
// If IsSimpleParameterList is false, we will create a strict-mode like arguments object.
// IsSimpleParameterList is false if the argument list contains any default parameter values,
// a rest parameter, or any destructuring patterns.
// If we do have default parameters, destructuring parameters, or a rest parameter, our parameters will be allocated in a different scope.
bool isSimpleParameterList = parameters.isSimpleParameterList();
SourceParseMode parseMode = codeBlock->parseMode();
bool containsArrowOrEvalButNotInArrowBlock = ((functionNode->usesArrowFunction() && functionNode->doAnyInnerArrowFunctionsUseAnyFeature()) || usesEval()) && !m_codeBlock->isArrowFunction();
bool shouldCaptureSomeOfTheThings = shouldEmitDebugHooks() || functionNode->needsActivation() || containsArrowOrEvalButNotInArrowBlock;
bool shouldCaptureAllOfTheThings = shouldEmitDebugHooks() || usesEval();
bool needsArguments = ((functionNode->usesArguments() && !codeBlock->isArrowFunction()) || usesEval() || (functionNode->usesArrowFunction() && !codeBlock->isArrowFunction() && isArgumentsUsedInInnerArrowFunction())) && parseMode != SourceParseMode::ClassFieldInitializerMode;
if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
m_isAsync = true;
// Generator and AsyncFunction never provides "arguments". "arguments" reference will be resolved in an upper generator function scope.
needsArguments = false;
}
if (isGeneratorOrAsyncFunctionWrapperParseMode(parseMode) && needsArguments) {
// Generator does not provide "arguments". Instead, wrapping GeneratorFunction provides "arguments".
// This is because arguments of a generator should be evaluated before starting it.
// To workaround it, we evaluate these arguments as arguments of a wrapping generator function, and reference it from a generator.
//
// function *gen(a, b = hello())
// {
// return {
// @generatorNext: function (@generator, @generatorState, @generatorValue, @generatorResumeMode, @generatorFrame)
// {
// arguments; // This `arguments` should reference to the gen's arguments.
// ...
// }
// }
// }
shouldCaptureSomeOfTheThings = true;
}
if (shouldCaptureAllOfTheThings)
functionNode->varDeclarations().markAllVariablesAsCaptured();
auto captures = scopedLambda<bool (UniquedStringImpl*)>([&] (UniquedStringImpl* uid) -> bool {
if (!shouldCaptureSomeOfTheThings)
return false;
if (needsArguments && uid == propertyNames().arguments.impl()) {
// Actually, we only need to capture the arguments object when we "need full activation"
// because of name scopes. But historically we did it this way, so for now we just preserve
// the old behavior.
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072
return true;
}
return functionNode->captures(uid);
});
auto varKind = [&] (UniquedStringImpl* uid) -> VarKind {
return captures(uid) ? VarKind::Scope : VarKind::Stack;
};
m_calleeRegister.setIndex(CallFrameSlot::callee);
initializeParameters(parameters);
ASSERT(!(isSimpleParameterList && m_restParameter));
emitEnter();
if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode))
m_generatorRegister = &m_parameters[static_cast<unsigned>(JSGenerator::Argument::Generator)];
allocateAndEmitScope();
emitCheckTraps();
switch (constructorKind()) {
case ConstructorKind::None:
break;
case ConstructorKind::Naked:
if (!isConstructor()) {
emitThrowTypeError("Cannot call a constructor without |new|"_s);
return;
}
break;
case ConstructorKind::Base:
case ConstructorKind::Extends:
if (!isConstructor()) {
emitThrowTypeError("Cannot call a class constructor without |new|"_s);
return;
}
break;
}
if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
ASSERT(parseMode != SourceParseMode::GeneratorBodyMode);
ASSERT(!isAsyncFunctionBodyParseMode(parseMode));
bool isDynamicScope = functionNameScopeIsDynamic(usesEval(), ecmaMode.isStrict());
bool isFunctionNameCaptured = captures(functionNode->ident().impl());
bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
emitPushFunctionNameScope(functionNode->ident(), &m_calleeRegister, markAsCaptured);
}
if (shouldCaptureSomeOfTheThings)
m_lexicalEnvironmentRegister = addVar();
if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode) || shouldCaptureSomeOfTheThings || shouldEmitTypeProfilerHooks())
symbolTableConstantIndex = addConstantValue(functionSymbolTable)->index();
// We can allocate the "var" environment if we don't have default parameter expressions. If we have
// default parameter expressions, we have to hold off on allocating the "var" environment because
// the parent scope of the "var" environment is the parameter environment.
if (isSimpleParameterList)
initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, shouldCaptureSomeOfTheThings);
// Figure out some interesting facts about our arguments.
bool capturesAnyArgumentByName = false;
if (functionNode->hasCapturedVariables()) {
FunctionParameters& parameters = *functionNode->parameters();
for (size_t i = 0; i < parameters.size(); ++i) {
auto pattern = parameters.at(i).first;
if (!pattern->isBindingNode())
continue;
const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
capturesAnyArgumentByName |= captures(ident.impl());
}
}
if (capturesAnyArgumentByName)
ASSERT(m_lexicalEnvironmentRegister);
// Need to know what our functions are called. Parameters have some goofy behaviors when it
// comes to functions of the same name.
for (FunctionMetadataNode* function : functionNode->functionStack())
m_functions.add(function->ident().impl());
if (needsArguments) {
// Create the arguments object now. We may put the arguments object into the activation if
// it is captured. Either way, we create two arguments object variables: one is our
// private variable that is immutable, and another that is the user-visible variable. The
// immutable one is only used here, or during formal parameter resolutions if we opt for
// DirectArguments.
m_argumentsRegister = addVar();
m_argumentsRegister->ref();
}
if (needsArguments && !ecmaMode.isStrict() && isSimpleParameterList) {
// If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we
// use DirectArguments. With ScopedArguments, we lift all of our arguments into the
// activation.
if (capturesAnyArgumentByName) {
bool success = functionSymbolTable->trySetArgumentsLength(vm, parameters.size());
if (UNLIKELY(!success)) {
m_outOfMemoryDuringConstruction = true;
return;
}
// For each parameter, we have two possibilities:
// Either it's a binding node with no function overlap, in which case it gets a name
// in the symbol table - or it just gets space reserved in the symbol table. Either
// way we lift the value into the scope.
for (unsigned i = 0; i < parameters.size(); ++i) {
ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
bool success = functionSymbolTable->trySetArgumentOffset(vm, i, offset);
if (UNLIKELY(!success)) {
m_outOfMemoryDuringConstruction = true;
return;
}
if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) {
VarOffset varOffset(offset);
SymbolTableEntry entry(varOffset);
// Stores to these variables via the ScopedArguments object will not do
// notifyWrite(), since that would be cumbersome. Also, watching formal
// parameters when "arguments" is in play is unlikely to be super profitable.
// So, we just disable it.
entry.disableWatching(m_vm);
functionSymbolTable->set(NoLockingNecessary, name, entry);
}
OpPutToScope::emit(this, m_lexicalEnvironmentRegister, UINT_MAX, virtualRegisterForArgumentIncludingThis(1 + i), GetPutInfo(ThrowIfNotFound, ResolvedClosureVar, InitializationMode::NotInitialization, ecmaMode), SymbolTableOrScopeDepth::symbolTable(VirtualRegister { symbolTableConstantIndex }), offset.offset());
}
// This creates a scoped arguments object and copies the overflow arguments into the
// scope. It's the equivalent of calling ScopedArguments::createByCopying().
OpCreateScopedArguments::emit(this, m_argumentsRegister, m_lexicalEnvironmentRegister);
} else {
// We're going to put all parameters into the DirectArguments object. First ensure
// that the symbol table knows that this is happening.
for (unsigned i = 0; i < parameters.size(); ++i) {
if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first))
functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i))));
}
OpCreateDirectArguments::emit(this, m_argumentsRegister);
}
} else if (isSimpleParameterList) {
// Create the formal parameters the normal way. Any of them could be captured, or not. If
// captured, lift them into the scope. We cannot do this if we have default parameter expressions
// because when default parameter expressions exist, they belong in their own lexical environment
// separate from the "var" lexical environment.
for (unsigned i = 0; i < parameters.size(); ++i) {
UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
if (!name)
continue;
if (!captures(name)) {
// This is the easy case - just tell the symbol table about the argument. It will
// be accessed directly.
functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(virtualRegisterForArgumentIncludingThis(1 + i))));
continue;
}
ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
IGNORE_GCC_WARNINGS_BEGIN("dangling-reference")
const Identifier& ident =
static_cast<const BindingNode*>(parameters.at(i).first)->boundProperty();
IGNORE_GCC_WARNINGS_END
functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(offset)));
OpPutToScope::emit(this, m_lexicalEnvironmentRegister, addConstant(ident), virtualRegisterForArgumentIncludingThis(1 + i), GetPutInfo(ThrowIfNotFound, ResolvedClosureVar, InitializationMode::NotInitialization, ecmaMode), SymbolTableOrScopeDepth::symbolTable(VirtualRegister { symbolTableConstantIndex }), offset.offset());
}
}
if (needsArguments && (ecmaMode.isStrict() || !isSimpleParameterList)) {
// Allocate a cloned arguments object.
OpCreateClonedArguments::emit(this, m_argumentsRegister);
}
// There are some variables that need to be preinitialized to something other than Undefined:
//
// - "arguments": unless it's used as a function or parameter, this should refer to the
// arguments object.
//
// - functions: these always override everything else.
//
// The most logical way to do all of this is to initialize none of the variables until now,
// and then initialize them in BytecodeGenerator::generate() in such an order that the rules
// for how these things override each other end up holding. We would initialize "arguments" first,
// then all arguments, then the functions.
//
// But some arguments are already initialized by default, since if they aren't captured and we
// don't have "arguments" then we just point the symbol table at the stack slot of those
// arguments. We end up initializing the rest of the arguments that have an uncomplicated
// binding (i.e. don't involve destructuring) above when figuring out how to lay them out,
// because that's just the simplest thing. This means that when we initialize them, we have to
// watch out for the things that override arguments (namely, functions).
// This is our final act of weirdness. "arguments" is overridden by everything except the
// callee. We add it to the symbol table if it's not already there and it's not an argument.
bool shouldCreateArgumentsVariableInParameterScope = false;
if (needsArguments) {
// If "arguments" is overridden by a function or destructuring parameter name, then it's
// OK for us to call createVariable() because it won't change anything. It's also OK for
// us to them tell BytecodeGenerator::generate() to write to it because it will do so
// before it initializes functions and destructuring parameters. But if "arguments" is
// overridden by a "simple" function parameter, then we have to bail: createVariable()
// would assert and BytecodeGenerator::generate() would write the "arguments" after the
// argument value had already been properly initialized.
bool haveParameterNamedArguments = false;
for (unsigned i = 0; i < parameters.size(); ++i) {
UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
if (name == propertyNames().arguments.impl()) {
haveParameterNamedArguments = true;
break;
}
}
bool shouldCreateArgumensVariable = !haveParameterNamedArguments
&& !SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode, SourceParseMode::ClassFieldInitializerMode).contains(m_codeBlock->parseMode());
shouldCreateArgumentsVariableInParameterScope = shouldCreateArgumensVariable && !isSimpleParameterList;
// Do not create arguments variable in case of Arrow function. Value will be loaded from parent scope
if (shouldCreateArgumensVariable && !shouldCreateArgumentsVariableInParameterScope) {
createVariable(
propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
m_needToInitializeArguments = true;
}
}
for (FunctionMetadataNode* function : functionNode->functionStack()) {
const Identifier& ident = function->ident();
createVariable(ident, varKind(ident.impl()), functionSymbolTable);
m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
}
for (auto& entry : functionNode->varDeclarations()) {
ASSERT(!entry.value.isLet() && !entry.value.isConst());
if (!entry.value.isVar()) // This is either a parameter or callee.
continue;
if (shouldCreateArgumentsVariableInParameterScope && entry.key.get() == propertyNames().arguments.impl())
continue;
createVariable(Identifier::fromUid(m_vm, entry.key.get()), varKind(entry.key.get()), functionSymbolTable, IgnoreExisting);
}
if (functionNode->needsNewTargetRegisterForThisScope() || isNewTargetUsedInInnerArrowFunction() || usesEval())
m_newTargetRegister = addVar();
switch (parseMode) {
case SourceParseMode::GeneratorWrapperFunctionMode:
case SourceParseMode::GeneratorWrapperMethodMode: {
m_generatorRegister = addVar();
// FIXME: Emit to_this only when Generator uses it.
// https://bugs.webkit.org/show_bug.cgi?id=151586
emitToThis();
emitCreateGenerator(m_generatorRegister, &m_calleeRegister);
break;
}
case SourceParseMode::AsyncGeneratorWrapperMethodMode:
case SourceParseMode::AsyncGeneratorWrapperFunctionMode: {
m_generatorRegister = addVar();
// FIXME: Emit to_this only when Generator uses it.
// https://bugs.webkit.org/show_bug.cgi?id=151586
emitToThis();
emitCreateAsyncGenerator(m_generatorRegister, &m_calleeRegister);
break;
}
case SourceParseMode::AsyncArrowFunctionMode:
case SourceParseMode::AsyncMethodMode:
case SourceParseMode::AsyncFunctionMode: {
ASSERT(!isConstructor());
ASSERT(constructorKind() == ConstructorKind::None);
m_generatorRegister = addVar();
m_promiseRegister = addVar();
if (parseMode != SourceParseMode::AsyncArrowFunctionMode) {
// FIXME: Emit to_this only when AsyncFunctionBody uses it.
// https://bugs.webkit.org/show_bug.cgi?id=151586
emitToThis();
}
emitNewGenerator(m_generatorRegister);
bool isInternalPromise = false;
if (m_isBuiltinFunction)
isInternalPromise = !functionNode->ident().string().startsWith("defaultAsync"_s);
emitNewPromise(promiseRegister(), isInternalPromise);
emitPutInternalField(generatorRegister(), static_cast<unsigned>(JSGenerator::Field::Context), promiseRegister());
break;
}
case SourceParseMode::AsyncGeneratorBodyMode:
case SourceParseMode::AsyncFunctionBodyMode:
case SourceParseMode::AsyncArrowFunctionBodyMode:
case SourceParseMode::GeneratorBodyMode: {
// |this| is already filled correctly before here.
if (m_newTargetRegister)
emitLoad(m_newTargetRegister, jsUndefined());
break;
}
case SourceParseMode::ArrowFunctionMode:
break;
default: {
if (isConstructor()) {
if (m_newTargetRegister)
move(m_newTargetRegister, &m_thisRegister);
switch (constructorKind()) {
case ConstructorKind::Naked:
// Naked constructor not create |this| automatically.
break;
case ConstructorKind::None:
case ConstructorKind::Base:
emitCreateThis(&m_thisRegister);
if (privateBrandRequirement() == PrivateBrandRequirement::Needed)
emitInstallPrivateBrand(&m_thisRegister);
emitInstanceFieldInitializationIfNeeded(&m_thisRegister, &m_calleeRegister, m_scopeNode->position(), m_scopeNode->position(), m_scopeNode->position());
break;
case ConstructorKind::Extends:
moveEmptyValue(&m_thisRegister);
break;
}
} else {
switch (constructorKind()) {
case ConstructorKind::None: {
bool shouldEmitToThis = false;
if (functionNode->usesThis() || usesEval() || m_scopeNode->doAnyInnerArrowFunctionsUseThis() || m_scopeNode->doAnyInnerArrowFunctionsUseEval())
shouldEmitToThis = true;
else if ((functionNode->usesSuperProperty() || m_scopeNode->doAnyInnerArrowFunctionsUseSuperProperty()) && !ecmaMode.isStrict()) {
// We must emit to_this when we're not in strict mode because we
// will convert |this| to an object, and that object may be passed
// to a strict function as |this|. This is observable because that
// strict function's to_this will just return the object.
//
// We don't need to emit this for strict-mode code because
// strict-mode code may call another strict function, which will
// to_this if it directly uses this; this is OK, because we defer
// to_this until |this| is used directly. Strict-mode code might
// also call a sloppy mode function, and that will to_this, which
// will defer the conversion, again, until necessary.
shouldEmitToThis = true;
}
if (shouldEmitToThis)
emitToThis();
break;
}
case ConstructorKind::Naked:
case ConstructorKind::Base:
case ConstructorKind::Extends:
RELEASE_ASSERT_NOT_REACHED();
break;
}
}
break;
}
}
// We need load |super| & |this| for arrow function before initializeDefaultParameterValuesAndSetupFunctionScopeStack
// if we have default parameter expression. Because |super| & |this| values can be used there
if ((SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && !isSimpleParameterList) || parseMode == SourceParseMode::AsyncArrowFunctionBodyMode) {
if (functionNode->usesThis() || functionNode->usesSuperProperty())
emitLoadThisFromArrowFunctionLexicalEnvironment();
if (m_scopeNode->needsNewTargetRegisterForThisScope())
emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
}
if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunction()) {
bool canReuseLexicalEnvironment = isSimpleParameterList;
initializeArrowFunctionContextScopeIfNeeded(functionSymbolTable, canReuseLexicalEnvironment);
emitPutThisToArrowFunctionContextScope();
emitPutNewTargetToArrowFunctionContextScope();
emitPutDerivedConstructorToArrowFunctionContextScope();
}
if (isAsyncFunctionWrapperParseMode(parseMode) && !isSimpleParameterList)
m_asyncFuncParametersTryCatchInfo = { newLabel(), newTemporary() };
asyncFuncParametersTryCatchWrap([&]() {
// All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
// because a function's default parameter ExpressionNodes will use temporary registers.
initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, isSimpleParameterList, functionNode, functionSymbolTable, symbolTableConstantIndex, captures, shouldCreateArgumentsVariableInParameterScope);
});
// If we don't have default parameter expression, then loading |this| inside an arrow function must be done
// after initializeDefaultParameterValuesAndSetupFunctionScopeStack() because that function sets up the
// SymbolTable stack and emitLoadThisFromArrowFunctionLexicalEnvironment() consults the SymbolTable stack
if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && isSimpleParameterList) {
if (functionNode->usesThis() || functionNode->usesSuperProperty())
emitLoadThisFromArrowFunctionLexicalEnvironment();
if (m_scopeNode->needsNewTargetRegisterForThisScope())
emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
}
// Set up the lexical environment scope as the generator frame. We store the saved and resumed generator registers into this scope with the symbol keys.
// Since they are symbol keyed, these variables cannot be reached from the usual code.
if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
m_generatorFrameSymbolTable.set(m_vm, functionSymbolTable);
m_generatorFrameSymbolTableIndex = symbolTableConstantIndex;
if (m_lexicalEnvironmentRegister)
move(generatorFrameRegister(), m_lexicalEnvironmentRegister);
else {
// It would be possible that generator does not need to suspend and resume any registers.
// In this case, we would like to avoid creating a lexical environment as much as possible.
// op_create_generator_frame_environment is a marker, which is similar to op_yield.
// Generatorification inserts lexical environment creation if necessary. Otherwise, we convert it to op_mov frame, `undefined`.
OpCreateGeneratorFrameEnvironment::emit(this, generatorFrameRegister(), scopeRegister(), VirtualRegister { symbolTableConstantIndex }, addConstantValue(jsUndefined()));
}
static_assert(static_cast<unsigned>(JSGenerator::Field::Frame) == static_cast<unsigned>(JSAsyncGenerator::Field::Frame));
emitPutInternalField(generatorRegister(), static_cast<unsigned>(JSGenerator::Field::Frame), generatorFrameRegister());
}
bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
pushLexicalScope(m_scopeNode, ScopeType::LetConstScope, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
}
BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, OptionSet<CodeGenerationMode> codeGenerationMode, const RefPtr<TDZEnvironmentLink>& parentScopeTDZVariables, const PrivateNameEnvironment* parentPrivateNameEnvironment)
: BytecodeGeneratorBase(makeUnique<UnlinkedCodeBlockGenerator>(vm, codeBlock), CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters())
, m_codeGenerationMode(codeGenerationMode)
, m_scopeNode(evalNode)
, m_thisRegister(CallFrame::thisArgumentOffset())
, m_codeType(EvalCode)
, m_vm(vm)
, m_usesExceptions(false)
, m_expressionTooDeep(false)
, m_isBuiltinFunction(false)
, m_usesNonStrictEval(evalNode->usesEval() && !evalNode->isStrictMode())
, m_inTailPosition(false)
, m_needsToUpdateArrowFunctionContext(evalNode->usesArrowFunction() || evalNode->usesEval())
, m_ecmaMode(ECMAMode::fromBool(evalNode->isStrictMode()))
, m_derivedContextType(codeBlock->derivedContextType())
{
m_codeBlock->setNumParameters(1);
pushPrivateAccessNames(parentPrivateNameEnvironment);
m_cachedParentTDZ = parentScopeTDZVariables;
emitEnter();
allocateAndEmitScope();
emitCheckTraps();
for (FunctionMetadataNode* function : evalNode->functionStack()) {
m_codeBlock->addFunctionDecl(makeFunction(function));
m_functionsToInitialize.append(std::make_pair(function, TopLevelFunctionVariable));
}
const VariableEnvironment& varDeclarations = evalNode->varDeclarations();
Vector<Identifier, 0, UnsafeVectorOverflow> variables;
Vector<Identifier, 0, UnsafeVectorOverflow> hoistedFunctions;
for (auto& entry : varDeclarations) {
ASSERT(entry.value.isVar());
ASSERT(entry.key->isAtom() || entry.key->isSymbol());
if (entry.value.isSloppyModeHoistingCandidate())
hoistedFunctions.append(Identifier::fromUid(m_vm, entry.key.get()));
else
variables.append(Identifier::fromUid(m_vm, entry.key.get()));
}
codeBlock->adoptVariables(WTFMove(variables));
codeBlock->adoptFunctionHoistingCandidates(WTFMove(hoistedFunctions));
if (evalNode->needsNewTargetRegisterForThisScope())
m_newTargetRegister = addVar();
if (codeBlock->isArrowFunctionContext() && (evalNode->usesThis() || evalNode->usesSuperProperty()))
emitLoadThisFromArrowFunctionLexicalEnvironment();
if (evalNode->needsNewTargetRegisterForThisScope())
emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunctionContext() && !isDerivedConstructorContext()) {
initializeArrowFunctionContextScopeIfNeeded();
emitPutThisToArrowFunctionContextScope();
}
bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
pushLexicalScope(m_scopeNode, ScopeType::LetConstScope, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
}
BytecodeGenerator::BytecodeGenerator(VM& vm, ModuleProgramNode* moduleProgramNode, UnlinkedModuleProgramCodeBlock* codeBlock, OptionSet<CodeGenerationMode> codeGenerationMode, const RefPtr<TDZEnvironmentLink>& parentScopeTDZVariables, const PrivateNameEnvironment*)
: BytecodeGeneratorBase(makeUnique<UnlinkedCodeBlockGenerator>(vm, codeBlock), CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters())
, m_codeGenerationMode(codeGenerationMode)
, m_scopeNode(moduleProgramNode)
, m_thisRegister(CallFrame::thisArgumentOffset())
, m_codeType(ModuleCode)
, m_vm(vm)
, m_usesExceptions(false)
, m_expressionTooDeep(false)
, m_isBuiltinFunction(false)
, m_usesNonStrictEval(false)
, m_inTailPosition(false)
, m_needsToUpdateArrowFunctionContext(moduleProgramNode->usesArrowFunction() || moduleProgramNode->usesEval())
, m_ecmaMode(ECMAMode::strict())
{
ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables);
SymbolTable* moduleEnvironmentSymbolTable = SymbolTable::create(m_vm);
moduleEnvironmentSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
moduleEnvironmentSymbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
bool shouldCaptureAllOfTheThings = shouldEmitDebugHooks() || usesEval();
if (shouldCaptureAllOfTheThings)
moduleProgramNode->varDeclarations().markAllVariablesAsCaptured();
auto captures = [&] (UniquedStringImpl* uid) -> bool {
return moduleProgramNode->captures(uid);
};
auto lookUpVarKind = [&] (UniquedStringImpl* uid, const VariableEnvironmentEntry& entry) -> VarKind {
// Allocate the exported variables in the module environment.
if (entry.isExported())
return VarKind::Scope;
// Allocate the namespace variables in the module environment to instantiate
// it from the outside of the module code.
if (entry.isImportedNamespace())
return VarKind::Scope;
if (entry.isCaptured())
return VarKind::Scope;
return captures(uid) ? VarKind::Scope : VarKind::Stack;
};
if (moduleProgramNode->usesAwait()) {
m_isAsync = true;