-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathParser.h
More file actions
2327 lines (2001 loc) · 100 KB
/
Parser.h
File metadata and controls
2327 lines (2001 loc) · 100 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
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) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003-2024 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#pragma once
#include "ExecutableInfo.h"
#include "Lexer.h"
#include "ModuleScopeData.h"
#include "Nodes.h"
#include "ParseHash.h"
#include "ParserArena.h"
#include "ParserError.h"
#include "ParserFunctionInfo.h"
#include "ParserTokens.h"
#include "SourceProvider.h"
#include "SourceProviderCache.h"
#include "SourceProviderCacheItem.h"
#include "VariableEnvironment.h"
#include <wtf/FixedVector.h>
#include <wtf/Forward.h>
#include <wtf/IterationStatus.h>
#include <wtf/Noncopyable.h>
#include <wtf/RefPtr.h>
#include <wtf/SegmentedVector.h>
#include <wtf/TZoneMalloc.h>
#include <wtf/text/MakeString.h>
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
namespace JSC {
class FunctionMetadataNode;
class FunctionParameters;
class Identifier;
class VM;
class SourceCode;
class SyntaxChecker;
struct DebuggerParseData;
// Macros to make the more common TreeBuilder types a little less verbose
#define TreeStatement typename TreeBuilder::Statement
#define TreeExpression typename TreeBuilder::Expression
#define TreeFormalParameterList typename TreeBuilder::FormalParameterList
#define TreeSourceElements typename TreeBuilder::SourceElements
#define TreeClause typename TreeBuilder::Clause
#define TreeClauseList typename TreeBuilder::ClauseList
#define TreeArguments typename TreeBuilder::Arguments
#define TreeArgumentsList typename TreeBuilder::ArgumentsList
#define TreeFunctionBody typename TreeBuilder::FunctionBody
#define TreeClassExpression typename TreeBuilder::ClassExpression
#define TreeProperty typename TreeBuilder::Property
#define TreePropertyList typename TreeBuilder::PropertyList
#define TreeDestructuringPattern typename TreeBuilder::DestructuringPattern
static_assert(LastUntaggedToken < 64, "Less than 64 untagged tokens");
enum SourceElementsMode { CheckForStrictMode, DontCheckForStrictMode };
enum FunctionBodyType { ArrowFunctionBodyExpression, ArrowFunctionBodyBlock, StandardFunctionBodyBlock };
enum class FunctionNameRequirements { None, Named, Unnamed };
enum class DestructuringKind {
DestructureToVariables,
DestructureToLet,
DestructureToConst,
DestructureToCatchParameters,
DestructureToParameters,
DestructureToExpressions
};
enum class DeclarationType {
VarDeclaration,
LetDeclaration,
ConstDeclaration,
UsingDeclaration,
AwaitUsingDeclaration,
};
enum class DeclarationImportType {
Imported,
ImportedNamespace,
NotImported
};
enum DeclarationResult {
Valid = 0,
InvalidStrictMode = 1 << 0,
InvalidDuplicateDeclaration = 1 << 1,
InvalidPrivateStaticNonStatic = 1 << 2
};
typedef uint8_t DeclarationResultMask;
enum class DeclarationDefaultContext {
Standard,
ExportDefault,
};
enum class InferName {
Allowed,
Disallowed,
};
template <typename T> inline bool isEvalNode() { return false; }
template <> inline bool isEvalNode<EvalNode>() { return true; }
struct ScopeLabelInfo {
UniquedStringImpl* uid;
bool isLoop;
};
ALWAYS_INLINE static bool isArguments(const VM& vm, const Identifier* ident)
{
return vm.propertyNames->arguments == *ident;
}
ALWAYS_INLINE static bool isEval(const VM& vm, const Identifier* ident)
{
return vm.propertyNames->eval == *ident;
}
ALWAYS_INLINE static bool isEvalOrArgumentsIdentifier(const VM& vm, const Identifier* ident)
{
return isEval(vm, ident) || isArguments(vm, ident);
}
ALWAYS_INLINE static bool isIdentifierOrKeyword(const JSToken& token)
{
return token.m_type == IDENT || token.m_type & KeywordTokenFlag;
}
// "let", "yield", and "await" may be keywords or identifiers depending on context.
ALWAYS_INLINE static bool isContextualKeyword(const JSToken& token)
{
return token.m_type >= FirstContextualKeywordToken && token.m_type <= LastContextualKeywordToken;
}
JS_EXPORT_PRIVATE extern std::atomic<unsigned> globalParseCount;
struct Scope {
WTF_MAKE_NONCOPYABLE(Scope);
public:
Scope(const VM& vm, Scope* containingScope, ImplementationVisibility implementationVisibility, LexicallyScopedFeatures lexicallyScopedFeatures, bool isFunction, bool isGeneratorFunction, bool isArrowFunction, bool isAsyncFunction, bool isStaticBlock)
: m_vm(vm)
, m_containingScope(containingScope)
, m_implementationVisibility(implementationVisibility)
, m_lexicallyScopedFeatures(lexicallyScopedFeatures)
, m_isFunction(isFunction)
, m_isGeneratorFunction(isGeneratorFunction)
, m_isArrowFunction(isArrowFunction)
, m_isAsyncFunction(isAsyncFunction)
, m_isStaticBlock(isStaticBlock)
{
m_usedVariables.append(UniquedStringImplPtrSet());
}
Scope(Scope&&) = default;
ImplementationVisibility implementationVisibility() const { return m_implementationVisibility; }
void resetImplementationVisibility()
{
setImplementationVisibility(ImplementationVisibility::Public);
}
void setImplementationVisibility(ImplementationVisibility implementationVisibility)
{
m_implementationVisibility = implementationVisibility;
}
void startSwitch() { m_switchDepth++; }
void endSwitch() { m_switchDepth--; }
void startLoop() { m_loopDepth++; }
void endLoop() { ASSERT(m_loopDepth); m_loopDepth--; }
bool inLoop() { return !!m_loopDepth; }
bool breakIsValid() { return m_loopDepth || m_switchDepth; }
bool continueIsValid() { return m_loopDepth; }
void pushLabel(const Identifier* label, bool isLoop)
{
if (!m_labels)
m_labels = makeUnique<LabelStack>();
m_labels->append(ScopeLabelInfo { label->impl(), isLoop });
}
void popLabel()
{
ASSERT(m_labels);
ASSERT(m_labels->size());
m_labels->removeLast();
}
ScopeLabelInfo* getLabel(const Identifier* label)
{
if (!m_labels)
return nullptr;
for (int i = m_labels->size(); i > 0; i--) {
if (m_labels->at(i - 1).uid == label->impl())
return &m_labels->at(i - 1);
}
return nullptr;
}
Scope* containingScope() const { return m_containingScope; }
bool hasContainingScope() const { return m_containingScope && !isFunctionBoundary(); }
void setSourceParseMode(SourceParseMode mode)
{
switch (mode) {
case SourceParseMode::AsyncGeneratorBodyMode:
setIsAsyncGeneratorFunctionBody();
break;
case SourceParseMode::AsyncArrowFunctionBodyMode:
setIsAsyncArrowFunctionBody();
break;
case SourceParseMode::AsyncFunctionBodyMode:
setIsAsyncFunctionBody();
break;
case SourceParseMode::GeneratorBodyMode:
setIsGeneratorFunctionBody();
break;
case SourceParseMode::GeneratorWrapperFunctionMode:
case SourceParseMode::GeneratorWrapperMethodMode:
setIsGeneratorFunction();
break;
case SourceParseMode::AsyncGeneratorWrapperMethodMode:
case SourceParseMode::AsyncGeneratorWrapperFunctionMode:
setIsAsyncGeneratorFunction();
break;
case SourceParseMode::NormalFunctionMode:
case SourceParseMode::GetterMode:
case SourceParseMode::SetterMode:
case SourceParseMode::MethodMode:
case SourceParseMode::ClassFieldInitializerMode:
setIsFunction();
break;
case SourceParseMode::ClassStaticBlockMode:
setIsFunction();
setIsStaticBlock();
break;
case SourceParseMode::ArrowFunctionMode:
setIsArrowFunction();
break;
case SourceParseMode::AsyncFunctionMode:
case SourceParseMode::AsyncMethodMode:
setIsAsyncFunction();
break;
case SourceParseMode::AsyncArrowFunctionMode:
setIsAsyncArrowFunction();
break;
case SourceParseMode::ProgramMode:
setIsGlobalCode();
break;
case SourceParseMode::ModuleAnalyzeMode:
case SourceParseMode::ModuleEvaluateMode:
setIsModuleCode();
break;
}
}
bool isFunction() const { return m_isFunction; }
bool isFunctionBoundary() const { return m_isFunctionBoundary; }
bool isGeneratorFunction() const { return m_isGeneratorFunction; }
bool isGeneratorFunctionBoundary() const { return m_isGeneratorFunctionBoundary; }
bool isAsyncFunction() const { return m_isAsyncFunction; }
bool isAsyncFunctionBoundary() const { return m_isAsyncFunctionBoundary; }
bool isPrivateNameScope() const { return m_isClassScope; }
bool isClassScope() const { return m_isClassScope; }
bool isGlobalCode() const { return m_isGlobalCode; }
bool isModuleCode() const { return m_isModuleCode; }
bool hasArguments() const { return m_hasArguments; }
void setIsSimpleCatchParameterScope() { m_isSimpleCatchParameterScope = true; }
bool isSimpleCatchParameterScope() { return m_isSimpleCatchParameterScope; }
void setIsCatchBlockScope() { m_isCatchBlockScope = true; }
bool isCatchBlockScope() { return m_isCatchBlockScope; }
void setIsStaticBlock()
{
m_isStaticBlock = true;
m_isStaticBlockBoundary = true;
}
bool isStaticBlock() { return m_isStaticBlock; }
bool isStaticBlockBoundary() { return m_isStaticBlockBoundary; }
void setIsLexicalScope()
{
m_isLexicalScope = true;
m_allowsLexicalDeclarations = true;
}
void setIsPrivateNameScope()
{
// FIXME: Currently, isPrivateNameScope is an alias for isClassScope --- This is potentially misleading,
// particularly when parsing direct eval code which occurs within a class.
setIsClassScope();
}
void setIsClassScope()
{
m_isClassScope = true;
}
bool isLexicalScope() const { return m_isLexicalScope; }
bool usesEval() const { return m_usesEval; }
bool usesImportMeta() const { return m_usesImportMeta; }
const UncheckedKeyHashSet<UniquedStringImpl*>& closedVariableCandidates() const LIFETIME_BOUND { return m_closedVariableCandidates; }
VariableEnvironment& declaredVariables() LIFETIME_BOUND { return m_declaredVariables; }
VariableEnvironment& lexicalVariables() LIFETIME_BOUND { return m_lexicalVariables; }
void finalizeLexicalEnvironment()
{
if (m_usesEval || m_needsFullActivation)
m_lexicalVariables.markAllVariablesAsCaptured();
else
computeLexicallyCapturedVariablesAndPurgeCandidates();
}
VariableEnvironment takeLexicalEnvironment() { return WTF::move(m_lexicalVariables); }
VariableEnvironment takeDeclaredVariables() { return WTF::move(m_declaredVariables); }
void computeLexicallyCapturedVariablesAndPurgeCandidates()
{
// Because variables may be defined at any time in the range of a lexical scope, we must
// track lexical variables that might be captured. Then, when we're preparing to pop the top
// lexical scope off the stack, we should find which variables are truly captured, and which
// variable still may be captured in a parent scope.
if (m_lexicalVariables.size() && m_closedVariableCandidates.size()) {
for (UniquedStringImpl* impl : m_closedVariableCandidates)
m_lexicalVariables.markVariableAsCapturedIfDefined(impl);
}
// We can now purge values from the captured candidates because they're captured in this scope.
{
for (const auto& entry : m_lexicalVariables) {
if (entry.value.isCaptured())
m_closedVariableCandidates.remove(entry.key.get());
}
}
}
DeclarationResultMask declareCallee(const Identifier* ident)
{
auto addResult = m_declaredVariables.add(ident->impl());
// We want to track if callee is captured, but we don't want to act like it's a 'var'
// because that would cause the BytecodeGenerator to emit bad code.
addResult.iterator->value.clearIsVar();
DeclarationResultMask result = DeclarationResult::Valid;
if (isEvalOrArgumentsIdentifier(m_vm, ident))
result |= DeclarationResult::InvalidStrictMode;
return result;
}
DeclarationResultMask declareVariable(const Identifier* ident)
{
ASSERT(m_allowsVarDeclarations);
DeclarationResultMask result = DeclarationResult::Valid;
bool isValidStrictMode = !isEvalOrArgumentsIdentifier(m_vm, ident);
m_isValidStrictMode = m_isValidStrictMode && isValidStrictMode;
auto addResult = m_declaredVariables.add(ident->impl());
addResult.iterator->value.setIsVar();
if (!isValidStrictMode)
result |= DeclarationResult::InvalidStrictMode;
return result;
}
DeclarationResultMask declareFunctionAsVar(const Identifier* ident)
{
ASSERT(m_allowsVarDeclarations);
DeclarationResultMask result = DeclarationResult::Valid;
bool isValidStrictMode = !isEvalOrArgumentsIdentifier(m_vm, ident);
if (!isValidStrictMode)
result |= DeclarationResult::InvalidStrictMode;
m_isValidStrictMode = m_isValidStrictMode && isValidStrictMode;
auto addResult = m_declaredVariables.add(ident->impl());
addResult.iterator->value.setIsVar();
addResult.iterator->value.setIsFunction();
if (m_lexicalVariables.contains(ident->impl()))
result |= DeclarationResult::InvalidDuplicateDeclaration;
return result;
}
DeclarationResultMask declareFunctionAsLet(const Identifier* ident, bool isFunctionDeclaration)
{
ASSERT(m_allowsLexicalDeclarations);
DeclarationResultMask result = DeclarationResult::Valid;
bool isValidStrictMode = !isEvalOrArgumentsIdentifier(m_vm, ident);
if (!isValidStrictMode)
result |= DeclarationResult::InvalidStrictMode;
m_isValidStrictMode = m_isValidStrictMode && isValidStrictMode;
auto addResult = m_lexicalVariables.add(ident->impl());
if (!addResult.isNewEntry) {
if (strictMode() || !addResult.iterator->value.isFunctionDeclaration() || !isFunctionDeclaration)
result |= DeclarationResult::InvalidDuplicateDeclaration;
}
if (m_declaredVariables.contains(ident->impl()) || m_variablesBeingHoisted.contains(ident->impl()))
result |= DeclarationResult::InvalidDuplicateDeclaration;
addResult.iterator->value.setIsLet();
addResult.iterator->value.setIsFunction();
if (isFunctionDeclaration)
addResult.iterator->value.setIsFunctionDeclaration();
return result;
}
void addVariableBeingHoisted(const Identifier* ident)
{
ASSERT(!m_allowsVarDeclarations);
m_variablesBeingHoisted.add(ident->impl());
}
enum class NeedsDuplicateDeclarationCheck : bool { No, Yes };
template<NeedsDuplicateDeclarationCheck needsCheck>
void addSloppyModeFunctionHoistingCandidate(FunctionMetadataNode* node)
{
ASSERT(node);
ASSERT(!strictMode());
m_sloppyModeFunctionHoistingCandidates.set(node, needsCheck);
}
void appendFunction(FunctionMetadataNode* node)
{
ASSERT(node);
m_functionDeclarations.append(node);
}
DeclarationStacks::FunctionStack takeFunctionDeclarations() { return WTF::move(m_functionDeclarations); }
DeclarationResultMask declareLexicalVariable(const Identifier* ident, bool isConstant, DeclarationImportType importType = DeclarationImportType::NotImported, bool isUsing = false, bool isAwaitUsing = false)
{
ASSERT(m_allowsLexicalDeclarations);
DeclarationResultMask result = DeclarationResult::Valid;
bool isValidStrictMode = !isEvalOrArgumentsIdentifier(m_vm, ident);
m_isValidStrictMode = m_isValidStrictMode && isValidStrictMode;
auto addResult = m_lexicalVariables.add(ident->impl());
if (isConstant)
addResult.iterator->value.setIsConst();
else
addResult.iterator->value.setIsLet();
if (isUsing)
addResult.iterator->value.setIsUsing();
if (isAwaitUsing)
m_lexicalVariables.setHasAwaitUsingDeclaration();
if (importType == DeclarationImportType::Imported)
addResult.iterator->value.setIsImported();
else if (importType == DeclarationImportType::ImportedNamespace) {
addResult.iterator->value.setIsImported();
addResult.iterator->value.setIsImportedNamespace();
}
if (!addResult.isNewEntry || m_variablesBeingHoisted.contains(ident->impl()))
result |= DeclarationResult::InvalidDuplicateDeclaration;
if (!isValidStrictMode)
result |= DeclarationResult::InvalidStrictMode;
return result;
}
ALWAYS_INLINE bool hasDeclaredGlobalArguments()
{
const Identifier& ident = m_vm.propertyNames->arguments;
return hasLexicallyDeclaredVariable(ident) || hasDeclaredVariable(ident) || shadowsArguments();
}
ALWAYS_INLINE bool hasDeclaredVariable(const Identifier& ident)
{
return hasDeclaredVariable(ident.impl());
}
bool hasDeclaredVariable(const UniquedStringImpl* ident)
{
auto iter = m_declaredVariables.find(ident);
if (iter == m_declaredVariables.end())
return false;
VariableEnvironmentEntry entry = iter->value;
return entry.isVar(); // The callee isn't a "var".
}
ALWAYS_INLINE bool hasLexicallyDeclaredVariable(const Identifier& ident)
{
return hasLexicallyDeclaredVariable(ident.impl());
}
bool hasLexicallyDeclaredVariable(const UniquedStringImpl* ident) const
{
return m_lexicalVariables.contains(ident);
}
bool hasVariableBeingHoisted(UniquedStringImpl* ident) const
{
return m_variablesBeingHoisted.contains(ident);
}
bool hasPrivateName(const Identifier& ident)
{
return m_lexicalVariables.hasPrivateName(ident);
}
DeclarationResultMask declarePrivateMethod(const Identifier& ident, ClassElementTag tag)
{
ASSERT(m_allowsLexicalDeclarations);
DeclarationResultMask result = DeclarationResult::Valid;
bool addResult = tag == ClassElementTag::Static ? m_lexicalVariables.declareStaticPrivateMethod(ident) : m_lexicalVariables.declarePrivateMethod(ident);
if (!addResult) {
result |= DeclarationResult::InvalidDuplicateDeclaration;
return result;
}
return result;
}
enum class PrivateAccessorType { Setter, Getter };
DeclarationResultMask declarePrivateAccessor(const Identifier& ident, ClassElementTag tag, PrivateAccessorType accessorType)
{
DeclarationResultMask result = DeclarationResult::Valid;
VariableEnvironment::PrivateDeclarationResult addResult;
if (accessorType == PrivateAccessorType::Setter)
addResult = tag == ClassElementTag::Static ? m_lexicalVariables.declareStaticPrivateSetter(ident) : m_lexicalVariables.declarePrivateSetter(ident);
else
addResult = tag == ClassElementTag::Static ? m_lexicalVariables.declareStaticPrivateGetter(ident) : m_lexicalVariables.declarePrivateGetter(ident);
if (addResult == VariableEnvironment::PrivateDeclarationResult::DuplicatedName)
result |= DeclarationResult::InvalidDuplicateDeclaration;
if (addResult == VariableEnvironment::PrivateDeclarationResult::InvalidStaticNonStatic)
result |= DeclarationResult::InvalidPrivateStaticNonStatic;
return result;
}
DeclarationResultMask declarePrivateSetter(const Identifier& ident, ClassElementTag tag)
{
ASSERT(m_allowsLexicalDeclarations);
return declarePrivateAccessor(ident, tag, PrivateAccessorType::Setter);
}
DeclarationResultMask declarePrivateGetter(const Identifier& ident, ClassElementTag tag)
{
ASSERT(m_allowsLexicalDeclarations);
return declarePrivateAccessor(ident, tag, PrivateAccessorType::Getter);
}
DeclarationResultMask declarePrivateField(const Identifier& ident)
{
ASSERT(m_allowsLexicalDeclarations);
DeclarationResultMask result = DeclarationResult::Valid;
auto addResult = m_lexicalVariables.declarePrivateField(ident);
if (!addResult.isNewEntry)
result |= DeclarationResult::InvalidDuplicateDeclaration;
return result;
}
ALWAYS_INLINE bool hasDeclaredParameter(const Identifier& ident)
{
return hasDeclaredParameter(ident.impl());
}
bool hasDeclaredParameter(UniquedStringImpl* ident)
{
return m_declaredParameters.contains(ident) || hasDeclaredVariable(ident);
}
void preventAllVariableDeclarations()
{
m_allowsVarDeclarations = false;
m_allowsLexicalDeclarations = false;
}
void preventVarDeclarations() { m_allowsVarDeclarations = false; }
bool allowsVarDeclarations() const { return m_allowsVarDeclarations; }
bool allowsLexicalDeclarations() const { return m_allowsLexicalDeclarations; }
DeclarationResultMask declareParameter(const Identifier* ident)
{
ASSERT(m_allowsVarDeclarations);
DeclarationResultMask result = DeclarationResult::Valid;
bool isArgumentsIdent = isArguments(m_vm, ident);
auto addResult = m_declaredVariables.add(ident->impl());
bool isDuplicateParameter = !addResult.isNewEntry && addResult.iterator->value.isParameter();
bool isValidStrictMode = !isDuplicateParameter && m_vm.propertyNames->eval != *ident && !isArgumentsIdent;
addResult.iterator->value.clearIsVar();
addResult.iterator->value.setIsParameter();
m_isValidStrictMode = m_isValidStrictMode && isValidStrictMode;
m_declaredParameters.add(ident->impl());
if (!isValidStrictMode)
result |= DeclarationResult::InvalidStrictMode;
if (isArgumentsIdent)
m_shadowsArguments = true;
if (isDuplicateParameter)
result |= DeclarationResult::InvalidDuplicateDeclaration;
return result;
}
bool usedVariablesContains(UniquedStringImpl* impl) const
{
for (const UniquedStringImplPtrSet& set : m_usedVariables) {
if (set.contains(impl))
return true;
}
return false;
}
template <typename Func>
void forEachUsedVariable(const Func& func)
{
for (const UniquedStringImplPtrSet& set : m_usedVariables) {
for (UniquedStringImpl* impl : set) {
if (func(impl) == IterationStatus::Done)
return;
}
}
}
void useVariable(const Identifier* ident, bool isEval)
{
useVariable(ident->impl(), isEval);
}
void useVariable(UniquedStringImpl* impl, bool isEval)
{
m_usesEval |= isEval;
m_usedVariables.last().add(impl);
}
void usePrivateName(const Identifier& ident)
{
useVariable(&ident, false);
}
void setUsesImportMeta() { m_usesImportMeta = true; }
void pushUsedVariableSet() { m_usedVariables.append(UniquedStringImplPtrSet()); }
size_t currentUsedVariablesSize() { return m_usedVariables.size(); }
void revertToPreviousUsedVariables(size_t size) { m_usedVariables.resize(size); }
void setNeedsFullActivation() { m_needsFullActivation = true; }
bool needsFullActivation() const { return m_needsFullActivation; }
bool isArrowFunctionBoundary() { return m_isArrowFunctionBoundary; }
bool isArrowFunction() { return m_isArrowFunction; }
void setAsyncFunctionBodyDoesNotUseAwait() { m_asyncFunctionBodyDoesNotUseAwait = true; }
bool asyncFunctionBodyDoesNotUseAwait() const { return m_asyncFunctionBodyDoesNotUseAwait; }
void setUsesAwait() { m_usesAwait = true; }
bool usesAwait() const { return m_usesAwait; }
bool hasUsingDeclaration() const { return m_lexicalVariables.hasUsingDeclaration(); }
bool hasDirectSuper() const { return m_hasDirectSuper; }
void setHasDirectSuper() { m_hasDirectSuper = true; }
bool needsSuperBinding() const { return m_needsSuperBinding; }
void setNeedsSuperBinding() { m_needsSuperBinding = true; }
void setEvalContextType(EvalContextType evalContextType) { m_evalContextType = evalContextType; }
EvalContextType evalContextType() { return m_evalContextType; }
void setDerivedContextType(DerivedContextType derivedContextType) { m_derivedContextType = derivedContextType; }
DerivedContextType derivedContextType() const { return m_derivedContextType; }
InnerArrowFunctionCodeFeatures innerArrowFunctionFeatures() { return m_innerArrowFunctionFeatures; }
void setExpectedSuperBinding(SuperBinding superBinding) { m_expectedSuperBinding = superBinding; }
SuperBinding expectedSuperBinding() const { return m_expectedSuperBinding; }
void setConstructorKind(ConstructorKind constructorKind) { m_constructorKind = constructorKind; }
ConstructorKind constructorKind() const { return m_constructorKind; }
void setInnerArrowFunctionUsesSuperCall() { m_innerArrowFunctionFeatures |= SuperCallInnerArrowFunctionFeature; }
void setInnerArrowFunctionUsesSuperProperty() { m_innerArrowFunctionFeatures |= SuperPropertyInnerArrowFunctionFeature; }
void setInnerArrowFunctionUsesEval() { m_innerArrowFunctionFeatures |= EvalInnerArrowFunctionFeature; }
void setInnerArrowFunctionUsesThis() { m_innerArrowFunctionFeatures |= ThisInnerArrowFunctionFeature; }
void setInnerArrowFunctionUsesNewTarget() { m_innerArrowFunctionFeatures |= NewTargetInnerArrowFunctionFeature; }
void setInnerArrowFunctionUsesArguments() { m_innerArrowFunctionFeatures |= ArgumentsInnerArrowFunctionFeature; }
bool isEvalContext() const { return m_isEvalContext; }
void setIsEvalContext(bool isEvalContext) { m_isEvalContext = isEvalContext; }
void setInnerArrowFunctionUsesEvalAndUseArgumentsIfNeeded()
{
ASSERT(m_isArrowFunction);
if (m_usesEval)
setInnerArrowFunctionUsesEval();
if (usedVariablesContains(m_vm.propertyNames->arguments.impl()))
setInnerArrowFunctionUsesArguments();
}
void addClosedVariableCandidateUnconditionally(UniquedStringImpl* impl)
{
m_closedVariableCandidates.add(impl);
}
void markLastUsedVariablesSetAsCaptured(unsigned from)
{
for (unsigned index = from; index < m_usedVariables.size(); ++index) {
for (UniquedStringImpl* impl : m_usedVariables[index])
m_closedVariableCandidates.add(impl);
}
}
void collectFreeVariables(Scope* nestedScope, bool shouldTrackClosedVariables)
{
if (nestedScope->m_usesEval)
m_usesEval = true;
if (nestedScope->m_usesImportMeta)
m_usesImportMeta = true;
{
UniquedStringImplPtrSet& destinationSet = m_usedVariables.last();
for (const UniquedStringImplPtrSet& usedVariablesSet : nestedScope->m_usedVariables) {
for (UniquedStringImpl* impl : usedVariablesSet) {
if (nestedScope->m_declaredVariables.contains(impl) || nestedScope->m_lexicalVariables.contains(impl))
continue;
// "arguments" reference should be resolved at function boudary.
if (nestedScope->isFunctionBoundary() && nestedScope->hasArguments() && impl == m_vm.propertyNames->arguments.impl() && !nestedScope->isArrowFunctionBoundary())
continue;
destinationSet.add(impl);
// We don't want a declared variable that is used in an inner scope to be thought of as captured if
// that inner scope is both a lexical scope and not a function. Only inner functions and "catch"
// statements can cause variables to be captured.
if (shouldTrackClosedVariables && (nestedScope->m_isFunctionBoundary || !nestedScope->m_isLexicalScope))
m_closedVariableCandidates.add(impl);
}
}
}
// Propagate closed variable candidates downwards within the same function.
// Cross function captures will be realized via m_usedVariables propagation.
if (shouldTrackClosedVariables && !nestedScope->m_isFunctionBoundary && nestedScope->m_closedVariableCandidates.size())
m_closedVariableCandidates.addAll(nestedScope->m_closedVariableCandidates);
}
void mergeInnerArrowFunctionFeatures(InnerArrowFunctionCodeFeatures arrowFunctionCodeFeatures)
{
m_innerArrowFunctionFeatures = m_innerArrowFunctionFeatures | arrowFunctionCodeFeatures;
}
void finalizeSloppyModeFunctionHoisting()
{
ASSERT(allowsVarDeclarations());
ASSERT(!isSimpleCatchParameterScope());
for (const auto& iter : m_sloppyModeFunctionHoistingCandidates) {
// ES6 Annex B.3.3. The only time we can't hoist a function is if a syntax error would
// be caused by declaring a var with that function's name or if we have a parameter with
// that function's name. Note that we would only cause a syntax error if we had a let/const/class
// variable with the same name.
FunctionMetadataNode* metadata = iter.key;
auto* function = metadata->ident().impl();
if (!m_lexicalVariables.contains(function)) {
auto addResult = m_declaredVariables.add(function);
if (addResult.isNewEntry)
addResult.iterator->value.setIsSloppyModeHoistedFunction();
else if (addResult.iterator->value.isParameter())
continue;
addResult.iterator->value.setIsVar();
metadata->setIsSloppyModeHoistedFunction();
}
}
}
NEVER_INLINE void bubbleSloppyModeFunctionHoistingCandidates(Scope* parentScope)
{
for (const auto& iter : m_sloppyModeFunctionHoistingCandidates) {
FunctionMetadataNode* metadata = iter.key;
bool needsCheck = iter.value == NeedsDuplicateDeclarationCheck::Yes;
if (!needsCheck || !m_lexicalVariables.contains(metadata->ident().impl()) || isSimpleCatchParameterScope())
parentScope->addSloppyModeFunctionHoistingCandidate<NeedsDuplicateDeclarationCheck::Yes>(metadata);
}
}
void getCapturedVars(IdentifierSet& capturedVariables)
{
if (m_needsFullActivation || m_usesEval) {
for (auto& entry : m_declaredVariables)
capturedVariables.add(entry.key);
return;
}
for (UniquedStringImpl* impl : m_closedVariableCandidates) {
// We refer to m_declaredVariables here directly instead of a hasDeclaredVariable because we want to mark the callee as captured.
if (!m_declaredVariables.contains(impl))
continue;
capturedVariables.add(impl);
}
}
LexicallyScopedFeatures lexicallyScopedFeatures() const { return m_lexicallyScopedFeatures; }
void setLexicallyScopedFeatures(LexicallyScopedFeatures features) { m_lexicallyScopedFeatures = features; }
void setStrictMode() { m_lexicallyScopedFeatures |= StrictModeLexicallyScopedFeature; }
void setTaintedByWithScope() { m_lexicallyScopedFeatures |= TaintedByWithScopeLexicallyScopedFeature; }
bool strictMode() const { return m_lexicallyScopedFeatures & StrictModeLexicallyScopedFeature; }
bool isValidStrictMode() const { return m_isValidStrictMode; }
bool shadowsArguments() const { return m_shadowsArguments; }
void setHasNonSimpleParameterList()
{
m_isValidStrictMode = false;
m_hasNonSimpleParameterList = true;
}
bool hasNonSimpleParameterList() const { return m_hasNonSimpleParameterList; }
bool hasSloppyModeFunctionHoistingCandidates() const { return !m_sloppyModeFunctionHoistingCandidates.isEmpty(); }
void copyCapturedVariablesToVector(const UniquedStringImplPtrSet& usedVariables, Vector<UniquedStringImpl*, 8>& vector)
{
for (UniquedStringImpl* impl : usedVariables) {
if (m_declaredVariables.contains(impl) || m_lexicalVariables.contains(impl))
continue;
vector.append(impl);
}
}
void fillParametersForSourceProviderCache(SourceProviderCacheItemCreationParameters& parameters, const UniquedStringImplPtrSet& capturesFromParameterExpressions)
{
ASSERT(m_isFunction);
parameters.usesEval = m_usesEval;
parameters.usesImportMeta = m_usesImportMeta;
parameters.lexicallyScopedFeatures = m_lexicallyScopedFeatures;
parameters.needsFullActivation = m_needsFullActivation;
parameters.innerArrowFunctionFeatures = m_innerArrowFunctionFeatures;
parameters.needsSuperBinding = m_needsSuperBinding;
for (const UniquedStringImplPtrSet& set : m_usedVariables)
copyCapturedVariablesToVector(set, parameters.usedVariables);
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=156962
// We add these unconditionally because we currently don't keep a separate
// declaration scope for a function's parameters and its var/let/const declarations.
// This is somewhat unfortunate and we should refactor to do this at some point
// because parameters logically form a parent scope to var/let/const variables.
// But because we don't do this, we must grab capture candidates from a parameter
// list before we parse the body of a function because the body's declarations
// might make us believe something isn't actually a capture candidate when it really
// is.
for (UniquedStringImpl* impl : capturesFromParameterExpressions)
parameters.usedVariables.append(impl);
}
void restoreFromSourceProviderCache(const SourceProviderCacheItem* info)
{
ASSERT(m_isFunction);
m_usesEval = info->usesEval;
m_usesImportMeta = info->usesImportMeta;
m_lexicallyScopedFeatures = info->lexicallyScopedFeatures();
m_innerArrowFunctionFeatures = info->innerArrowFunctionFeatures;
m_implementationVisibility = static_cast<ImplementationVisibility>(info->implementationVisibility);
m_needsFullActivation = info->needsFullActivation;
m_needsSuperBinding = info->needsSuperBinding;
UniquedStringImplPtrSet& destSet = m_usedVariables.last();
for (unsigned i = 0; i < info->usedVariablesCount; ++i)
destSet.add(info->usedVariables()[i].get());
}
class MaybeParseAsGeneratorFunctionForScope;
private:
void setIsFunction()
{
m_isFunction = true;
m_isFunctionBoundary = true;
m_hasArguments = true;
setIsLexicalScope();
m_isGeneratorFunction = false;
m_isGeneratorFunctionBoundary = false;
m_isArrowFunctionBoundary = false;
m_isArrowFunction = false;
m_isAsyncFunction = false;
m_isAsyncFunctionBoundary = false;
m_isStaticBlock = false;
m_isStaticBlockBoundary = false;
}
void setIsGeneratorFunction()
{
setIsFunction();
m_isGeneratorFunction = true;
}
void setIsGeneratorFunctionBody()
{
setIsFunction();
m_hasArguments = false;
m_isGeneratorFunction = true;
m_isGeneratorFunctionBoundary = true;
}
void setIsArrowFunction()
{
setIsFunction();
m_isArrowFunctionBoundary = true;
m_isArrowFunction = true;
}
void setIsAsyncArrowFunction()
{
setIsArrowFunction();
m_isAsyncFunction = true;
}
void setIsAsyncFunction()
{
setIsFunction();
m_isAsyncFunction = true;
}
void setIsAsyncGeneratorFunction()
{
setIsFunction();
m_isAsyncFunction = true;
m_isGeneratorFunction = true;
}
void setIsAsyncGeneratorFunctionBody()
{
setIsFunction();
m_hasArguments = false;
m_isGeneratorFunction = true;
m_isGeneratorFunctionBoundary = true;
m_isAsyncFunction = true;
m_isAsyncFunctionBoundary = true;
}
void setIsAsyncFunctionBody()
{
setIsFunction();
m_hasArguments = false;
m_isAsyncFunction = true;
m_isAsyncFunctionBoundary = true;
}
void setIsAsyncArrowFunctionBody()
{
setIsArrowFunction();
m_hasArguments = false;
m_isAsyncFunction = true;
m_isAsyncFunctionBoundary = true;
}
void setIsGlobalCode()
{
m_isGlobalCode = true;
}
void setIsModuleCode()
{
setIsGlobalCode();
m_isModuleCode = true;
}
const VM& m_vm;
Scope* m_containingScope;
ImplementationVisibility m_implementationVisibility;
LexicallyScopedFeatures m_lexicallyScopedFeatures;
bool m_shadowsArguments : 1 { false };
bool m_usesEval : 1 { false };
bool m_usesImportMeta : 1 { false };
bool m_needsFullActivation : 1 { false };
bool m_hasDirectSuper : 1 { false };
bool m_needsSuperBinding : 1 { false };
bool m_allowsVarDeclarations : 1 { true };
bool m_allowsLexicalDeclarations : 1 { true };
bool m_isFunction : 1;
bool m_isGeneratorFunction : 1;
bool m_isGeneratorFunctionBoundary : 1 { false };
bool m_isArrowFunction : 1;
bool m_isArrowFunctionBoundary : 1 { false };
bool m_isAsyncFunction : 1;
bool m_isAsyncFunctionBoundary : 1 { false };
bool m_isLexicalScope : 1 { false };
bool m_isGlobalCode : 1 { false };