-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathParser.cpp
More file actions
2367 lines (2162 loc) · 99.8 KB
/
Parser.cpp
File metadata and controls
2367 lines (2162 loc) · 99.8 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 ([email protected])
* Copyright (C) 2001 Peter Kelly ([email protected])
* Copyright (C) 2003, 2006, 2007, 2008, 2009, 2010, 2013 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.
*
*/
#include "config.h"
#include "Parser.h"
#include "ASTBuilder.h"
#include "CodeBlock.h"
#include "Debugger.h"
#include "JSCJSValueInlines.h"
#include "Lexer.h"
#include "NodeInfo.h"
#include "SourceProvider.h"
#include "VM.h"
#include <utility>
#include <wtf/HashFunctions.h>
#include <wtf/OwnPtr.h>
#include <wtf/StringPrintStream.h>
#include <wtf/WTFThreadData.h>
#define updateErrorMessage(shouldPrintToken, ...) do {\
propagateError(); \
logError(shouldPrintToken, __VA_ARGS__); \
} while (0)
#define propagateError() do { if (hasError()) return 0; } while (0)
#define internalFailWithMessage(shouldPrintToken, ...) do { updateErrorMessage(shouldPrintToken, __VA_ARGS__); return 0; } while (0)
#define handleErrorToken() do { if (m_token.m_type == EOFTOK || m_token.m_type & ErrorTokenFlag) { failDueToUnexpectedToken(); } } while (0)
#define failWithMessage(...) do { { handleErrorToken(); updateErrorMessage(true, __VA_ARGS__); } return 0; } while (0)
#define failWithStackOverflow() do { updateErrorMessage(false, "Stack exhausted"); m_hasStackOverflow = true; return 0; } while (0)
#define failIfFalse(cond, ...) do { if (!(cond)) { handleErrorToken(); internalFailWithMessage(true, __VA_ARGS__); } } while (0)
#define failIfTrue(cond, ...) do { if ((cond)) { handleErrorToken(); internalFailWithMessage(true, __VA_ARGS__); } } while (0)
#define failIfTrueIfStrict(cond, ...) do { if ((cond) && strictMode()) internalFailWithMessage(false, __VA_ARGS__); } while (0)
#define failIfFalseIfStrict(cond, ...) do { if ((!(cond)) && strictMode()) internalFailWithMessage(false, __VA_ARGS__); } while (0)
#define consumeOrFail(tokenType, ...) do { if (!consume(tokenType)) { handleErrorToken(); internalFailWithMessage(true, __VA_ARGS__); } } while (0)
#define consumeOrFailWithFlags(tokenType, flags, ...) do { if (!consume(tokenType, flags)) { handleErrorToken(); internalFailWithMessage(true, __VA_ARGS__); } } while (0)
#define matchOrFail(tokenType, ...) do { if (!match(tokenType)) { handleErrorToken(); internalFailWithMessage(true, __VA_ARGS__); } } while (0)
#define failIfStackOverflow() do { if (!canRecurse()) failWithStackOverflow(); } while (0)
#define semanticFail(...) do { internalFailWithMessage(false, __VA_ARGS__); } while (0)
#define semanticFailIfTrue(cond, ...) do { if ((cond)) internalFailWithMessage(false, __VA_ARGS__); } while (0)
#define semanticFailIfFalse(cond, ...) do { if (!(cond)) internalFailWithMessage(false, __VA_ARGS__); } while (0)
#define regexFail(failure) do { setErrorMessage(failure); return 0; } while (0)
#define failDueToUnexpectedToken() do {\
logError(true);\
return 0;\
} while (0)
#define handleProductionOrFail(token, tokenString, operation, production) do {\
consumeOrFail(token, "Expected '", tokenString, "' to ", operation, " a ", production);\
} while (0)
#define semanticFailureDueToKeyword(...) do { \
if (strictMode() && m_token.m_type == RESERVED_IF_STRICT) \
semanticFail("Cannot use the reserved word '", getToken(), "' as a ", __VA_ARGS__, " in strict mode"); \
if (m_token.m_type == RESERVED || m_token.m_type == RESERVED_IF_STRICT) \
semanticFail("Cannot use the reserved word '", getToken(), "' as a ", __VA_ARGS__); \
if (m_token.m_type & KeywordTokenFlag) \
semanticFail("Cannot use the keyword '", getToken(), "' as a ", __VA_ARGS__); \
} while (0)
using namespace std;
namespace JSC {
template <typename LexerType>
void Parser<LexerType>::logError(bool)
{
if (hasError())
return;
StringPrintStream stream;
printUnexpectedTokenText(stream);
setErrorMessage(stream.toString());
}
template <typename LexerType> template <typename A>
void Parser<LexerType>::logError(bool shouldPrintToken, const A& value1)
{
if (hasError())
return;
StringPrintStream stream;
if (shouldPrintToken) {
printUnexpectedTokenText(stream);
stream.print(". ");
}
stream.print(value1, ".");
setErrorMessage(stream.toString());
}
template <typename LexerType> template <typename A, typename B>
void Parser<LexerType>::logError(bool shouldPrintToken, const A& value1, const B& value2)
{
if (hasError())
return;
StringPrintStream stream;
if (shouldPrintToken) {
printUnexpectedTokenText(stream);
stream.print(". ");
}
stream.print(value1, value2, ".");
setErrorMessage(stream.toString());
}
template <typename LexerType> template <typename A, typename B, typename C>
void Parser<LexerType>::logError(bool shouldPrintToken, const A& value1, const B& value2, const C& value3)
{
if (hasError())
return;
StringPrintStream stream;
if (shouldPrintToken) {
printUnexpectedTokenText(stream);
stream.print(". ");
}
stream.print(value1, value2, value3, ".");
setErrorMessage(stream.toString());
}
template <typename LexerType> template <typename A, typename B, typename C, typename D>
void Parser<LexerType>::logError(bool shouldPrintToken, const A& value1, const B& value2, const C& value3, const D& value4)
{
if (hasError())
return;
StringPrintStream stream;
if (shouldPrintToken) {
printUnexpectedTokenText(stream);
stream.print(". ");
}
stream.print(value1, value2, value3, value4, ".");
setErrorMessage(stream.toString());
}
template <typename LexerType> template <typename A, typename B, typename C, typename D, typename E>
void Parser<LexerType>::logError(bool shouldPrintToken, const A& value1, const B& value2, const C& value3, const D& value4, const E& value5)
{
if (hasError())
return;
StringPrintStream stream;
if (shouldPrintToken) {
printUnexpectedTokenText(stream);
stream.print(". ");
}
stream.print(value1, value2, value3, value4, value5, ".");
setErrorMessage(stream.toString());
}
template <typename LexerType> template <typename A, typename B, typename C, typename D, typename E, typename F>
void Parser<LexerType>::logError(bool shouldPrintToken, const A& value1, const B& value2, const C& value3, const D& value4, const E& value5, const F& value6)
{
if (hasError())
return;
StringPrintStream stream;
if (shouldPrintToken) {
printUnexpectedTokenText(stream);
stream.print(". ");
}
stream.print(value1, value2, value3, value4, value5, value6, ".");
setErrorMessage(stream.toString());
}
template <typename LexerType> template <typename A, typename B, typename C, typename D, typename E, typename F, typename G>
void Parser<LexerType>::logError(bool shouldPrintToken, const A& value1, const B& value2, const C& value3, const D& value4, const E& value5, const F& value6, const G& value7)
{
if (hasError())
return;
StringPrintStream stream;
if (shouldPrintToken) {
printUnexpectedTokenText(stream);
stream.print(". ");
}
stream.print(value1, value2, value3, value4, value5, value6, value7, ".");
setErrorMessage(stream.toString());
}
template <typename LexerType>
Parser<LexerType>::Parser(VM* vm, const SourceCode& source, FunctionParameters* parameters, const Identifier& name, JSParserStrictness strictness, JSParserMode parserMode)
: m_vm(vm)
, m_source(&source)
, m_hasStackOverflow(false)
, m_allowsIn(true)
, m_assignmentCount(0)
, m_nonLHSCount(0)
, m_syntaxAlreadyValidated(source.provider()->isValid())
, m_statementDepth(0)
, m_nonTrivialExpressionCount(0)
, m_lastIdentifier(0)
, m_lastFunctionName(nullptr)
, m_sourceElements(0)
{
m_lexer = adoptPtr(new LexerType(vm));
m_arena = m_vm->parserArena.get();
m_lexer->setCode(source, m_arena);
m_token.m_location.line = source.firstLine();
m_token.m_location.startOffset = source.startOffset();
m_token.m_location.endOffset = source.startOffset();
m_token.m_location.lineStartOffset = source.startOffset();
m_functionCache = vm->addSourceProviderCache(source.provider());
ScopeRef scope = pushScope();
if (parserMode == JSParseFunctionCode)
scope->setIsFunction();
if (strictness == JSParseStrict)
scope->setStrictMode();
if (parameters) {
for (unsigned i = 0; i < parameters->size(); i++) {
auto parameter = parameters->at(i);
if (!parameter->isBindingNode())
continue;
scope->declareParameter(&static_cast<BindingNode*>(parameter)->boundProperty());
}
}
if (!name.isNull())
scope->declareCallee(&name);
next();
}
template <typename LexerType>
Parser<LexerType>::~Parser()
{
}
template <typename LexerType>
String Parser<LexerType>::parseInner()
{
String parseError = String();
ASTBuilder context(const_cast<VM*>(m_vm), const_cast<SourceCode*>(m_source));
if (m_lexer->isReparsing())
m_statementDepth--;
ScopeRef scope = currentScope();
SourceElements* sourceElements = parseSourceElements(context, CheckForStrictMode);
if (!sourceElements || !consume(EOFTOK)) {
if (hasError())
parseError = m_errorMessage;
else
parseError = ASCIILiteral("Parser error");
}
IdentifierSet capturedVariables;
bool modifiedParameter = false;
scope->getCapturedVariables(capturedVariables, modifiedParameter);
CodeFeatures features = context.features();
if (scope->strictMode())
features |= StrictModeFeature;
if (scope->shadowsArguments())
features |= ShadowsArgumentsFeature;
if (modifiedParameter)
features |= ModifiedParameterFeature;
didFinishParsing(sourceElements, context.varDeclarations(), context.funcDeclarations(), features,
context.numConstants(), capturedVariables);
return parseError;
}
template <typename LexerType>
void Parser<LexerType>::didFinishParsing(SourceElements* sourceElements, ParserArenaData<DeclarationStacks::VarStack>* varStack,
ParserArenaData<DeclarationStacks::FunctionStack>* funcStack, CodeFeatures features, int numConstants, IdentifierSet& capturedVars)
{
m_sourceElements = sourceElements;
m_varDeclarations = varStack;
m_funcDeclarations = funcStack;
m_capturedVariables.swap(capturedVars);
m_features = features;
m_numConstants = numConstants;
}
template <typename LexerType>
bool Parser<LexerType>::allowAutomaticSemicolon()
{
return match(CLOSEBRACE) || match(EOFTOK) || m_lexer->prevTerminator();
}
template <typename LexerType>
template <class TreeBuilder> TreeSourceElements Parser<LexerType>::parseSourceElements(TreeBuilder& context, SourceElementsMode mode)
{
const unsigned lengthOfUseStrictLiteral = 12; // "use strict".length
TreeSourceElements sourceElements = context.createSourceElements();
bool seenNonDirective = false;
const Identifier* directive = 0;
unsigned directiveLiteralLength = 0;
auto savePoint = createSavePoint();
bool hasSetStrict = false;
while (TreeStatement statement = parseStatement(context, directive, &directiveLiteralLength)) {
if (mode == CheckForStrictMode && !seenNonDirective) {
if (directive) {
// "use strict" must be the exact literal without escape sequences or line continuation.
if (!hasSetStrict && directiveLiteralLength == lengthOfUseStrictLiteral && m_vm->propertyNames->useStrictIdentifier == *directive) {
setStrictMode();
hasSetStrict = true;
if (!isValidStrictMode()) {
if (m_lastFunctionName) {
if (m_vm->propertyNames->arguments == *m_lastFunctionName)
semanticFail("Cannot name a function 'arguments' in strict mode");
if (m_vm->propertyNames->eval == *m_lastFunctionName)
semanticFail("Cannot name a function 'eval' in strict mode");
}
if (hasDeclaredVariable(m_vm->propertyNames->arguments))
semanticFail("Cannot declare a variable named 'arguments' in strict mode");
if (hasDeclaredVariable(m_vm->propertyNames->eval))
semanticFail("Cannot declare a variable named 'eval' in strict mode");
semanticFailIfFalse(isValidStrictMode(), "Invalid parameters or function name in strict mode");
}
restoreSavePoint(savePoint);
propagateError();
continue;
}
} else
seenNonDirective = true;
}
context.appendStatement(sourceElements, statement);
}
propagateError();
return sourceElements;
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseVarDeclaration(TreeBuilder& context)
{
ASSERT(match(VAR));
JSTokenLocation location(tokenLocation());
int start = tokenLine();
int end = 0;
int scratch;
TreeDeconstructionPattern scratch1 = 0;
TreeExpression scratch2 = 0;
JSTextPosition scratch3;
TreeExpression varDecls = parseVarDeclarationList(context, scratch, scratch1, scratch2, scratch3, scratch3, scratch3);
propagateError();
failIfFalse(autoSemiColon(), "Expected ';' after var declaration");
return context.createVarStatement(location, varDecls, start, end);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseConstDeclaration(TreeBuilder& context)
{
ASSERT(match(CONSTTOKEN));
JSTokenLocation location(tokenLocation());
int start = tokenLine();
int end = 0;
TreeConstDeclList constDecls = parseConstDeclarationList(context);
propagateError();
failIfFalse(autoSemiColon(), "Expected ';' after const declaration");
return context.createConstStatement(location, constDecls, start, end);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseDoWhileStatement(TreeBuilder& context)
{
ASSERT(match(DO));
int startLine = tokenLine();
next();
const Identifier* unused = 0;
startLoop();
TreeStatement statement = parseStatement(context, unused);
endLoop();
failIfFalse(statement, "Expected a statement following 'do'");
int endLine = tokenLine();
JSTokenLocation location(tokenLocation());
handleProductionOrFail(WHILE, "while", "end", "do-while loop");
handleProductionOrFail(OPENPAREN, "(", "start", "do-while loop condition");
semanticFailIfTrue(match(CLOSEPAREN), "Must provide an expression as a do-while loop condition");
TreeExpression expr = parseExpression(context);
failIfFalse(expr, "Unable to parse do-while loop condition");
handleProductionOrFail(CLOSEPAREN, ")", "end", "do-while loop condition");
if (match(SEMICOLON))
next(); // Always performs automatic semicolon insertion.
return context.createDoWhileStatement(location, statement, expr, startLine, endLine);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseWhileStatement(TreeBuilder& context)
{
ASSERT(match(WHILE));
JSTokenLocation location(tokenLocation());
int startLine = tokenLine();
next();
handleProductionOrFail(OPENPAREN, "(", "start", "while loop condition");
semanticFailIfTrue(match(CLOSEPAREN), "Must provide an expression as a while loop condition");
TreeExpression expr = parseExpression(context);
failIfFalse(expr, "Unable to parse while loop condition");
int endLine = tokenLine();
handleProductionOrFail(CLOSEPAREN, ")", "end", "while loop condition");
const Identifier* unused = 0;
startLoop();
TreeStatement statement = parseStatement(context, unused);
endLoop();
failIfFalse(statement, "Expected a statement as the body of a while loop");
return context.createWhileStatement(location, expr, statement, startLine, endLine);
}
template <typename LexerType>
template <class TreeBuilder> TreeExpression Parser<LexerType>::parseVarDeclarationList(TreeBuilder& context, int& declarations, TreeDeconstructionPattern& lastPattern, TreeExpression& lastInitializer, JSTextPosition& identStart, JSTextPosition& initStart, JSTextPosition& initEnd)
{
TreeExpression varDecls = 0;
const Identifier* lastIdent;
do {
lastIdent = 0;
lastPattern = 0;
JSTokenLocation location(tokenLocation());
next();
TreeExpression node = 0;
declarations++;
bool hasInitializer = false;
if (match(IDENT)) {
JSTextPosition varStart = tokenStartPosition();
identStart = varStart;
const Identifier* name = m_token.m_data.ident;
lastIdent = name;
next();
hasInitializer = match(EQUAL);
failIfFalseIfStrict(declareVariable(name), "Cannot declare a variable named ", name->impl(), " in strict mode");
context.addVar(name, (hasInitializer || (!m_allowsIn && (match(INTOKEN) || isofToken()))) ? DeclarationStacks::HasInitializer : 0);
if (hasInitializer) {
JSTextPosition varDivot = tokenStartPosition() + 1;
initStart = tokenStartPosition();
next(TreeBuilder::DontBuildStrings); // consume '='
TreeExpression initializer = parseAssignmentExpression(context);
initEnd = lastTokenEndPosition();
lastInitializer = initializer;
failIfFalse(initializer, "Expected expression as the intializer for the variable '", name->impl(), "'");
node = context.createAssignResolve(location, *name, initializer, varStart, varDivot, lastTokenEndPosition());
}
} else {
lastIdent = 0;
auto pattern = parseDeconstructionPattern(context, DeconstructToVariables);
failIfFalse(pattern, "Cannot parse this deconstruction pattern");
hasInitializer = match(EQUAL);
lastPattern = pattern;
if (hasInitializer) {
next(TreeBuilder::DontBuildStrings); // consume '='
TreeExpression rhs = parseExpression(context);
node = context.createDeconstructingAssignment(location, pattern, rhs);
}
}
if (hasInitializer) {
if (!varDecls)
varDecls = node;
else
varDecls = context.combineCommaNodes(location, varDecls, node);
}
} while (match(COMMA));
if (lastIdent)
lastPattern = createBindingPattern(context, DeconstructToVariables, *lastIdent, 0);
return varDecls;
}
template <typename LexerType>
template <class TreeBuilder> TreeDeconstructionPattern Parser<LexerType>::createBindingPattern(TreeBuilder& context, DeconstructionKind kind, const Identifier& name, int depth)
{
ASSERT(!name.isEmpty());
ASSERT(!name.isNull());
ASSERT(name.impl()->isIdentifier());
if (depth) {
if (kind == DeconstructToVariables)
failIfFalseIfStrict(declareVariable(&name), "Cannot deconstruct to a variable named '", name.impl(), "' in strict mode");
if (kind == DeconstructToParameters) {
auto bindingResult = declareBoundParameter(&name);
if (bindingResult == Scope::StrictBindingFailed && strictMode()) {
semanticFailIfTrue(m_vm->propertyNames->arguments == name || m_vm->propertyNames->eval == name, "Cannot deconstruct to a parameter name '", name.impl(), "' in strict mode");
if (m_lastFunctionName && name == *m_lastFunctionName)
semanticFail("Cannot deconstruct to '", name.impl(), "' as it shadows the name of a strict mode function");
semanticFailureDueToKeyword("bound parameter name");
if (hasDeclaredParameter(name))
semanticFail("Cannot deconstruct to '", name.impl(), "' as it has already been declared");
semanticFail("Cannot bind to a parameter named '", name.impl(), "' in strict mode");
}
if (bindingResult == Scope::BindingFailed) {
semanticFailureDueToKeyword("bound parameter name");
if (hasDeclaredParameter(name))
semanticFail("Cannot deconstruct to '", name.impl(), "' as it has already been declared");
semanticFail("Cannot deconstruct to a parameter named '", name.impl(), "'");
}
}
if (kind != DeconstructToExpressions)
context.addVar(&name, kind == DeconstructToParameters ? 0 : DeclarationStacks::HasInitializer);
} else {
if (kind == DeconstructToVariables) {
failIfFalseIfStrict(declareVariable(&name), "Cannot declare a variable named '", name.impl(), "' in strict mode");
context.addVar(&name, DeclarationStacks::HasInitializer);
}
if (kind == DeconstructToParameters) {
bool declarationResult = declareParameter(&name);
if (!declarationResult && strictMode()) {
semanticFailIfTrue(m_vm->propertyNames->arguments == name || m_vm->propertyNames->eval == name, "Cannot deconstruct to a parameter name '", name.impl(), "' in strict mode");
if (m_lastFunctionName && name == *m_lastFunctionName)
semanticFail("Cannot declare a parameter named '", name.impl(), "' as it shadows the name of a strict mode function");
semanticFailureDueToKeyword("parameter name");
if (hasDeclaredParameter(name))
semanticFail("Cannot declare a parameter named '", name.impl(), "' in strict mode as it has already been declared");
semanticFail("Cannot declare a parameter named '", name.impl(), "' in strict mode");
}
}
}
return context.createBindingLocation(m_token.m_location, name, m_token.m_endPosition, m_token.m_startPosition, m_token.m_endPosition);
}
template <typename LexerType>
template <class TreeBuilder> TreeDeconstructionPattern Parser<LexerType>::tryParseDeconstructionPatternExpression(TreeBuilder& context)
{
return parseDeconstructionPattern(context, DeconstructToExpressions);
}
template <typename LexerType>
template <class TreeBuilder> TreeDeconstructionPattern Parser<LexerType>::parseDeconstructionPattern(TreeBuilder& context, DeconstructionKind kind, int depth)
{
failIfStackOverflow();
int nonLHSCount = m_nonLHSCount;
TreeDeconstructionPattern pattern;
switch (m_token.m_type) {
case OPENBRACKET: {
auto arrayPattern = context.createArrayPattern(m_token.m_location);
next();
if (kind == DeconstructToExpressions && match(CLOSEBRACKET))
return 0;
failIfTrue(match(CLOSEBRACKET), "There must be at least one bound property in an array deconstruction pattern");
do {
while (match(COMMA)) {
context.appendArrayPatternSkipEntry(arrayPattern, m_token.m_location);
next();
}
propagateError();
JSTokenLocation location = m_token.m_location;
auto innerPattern = parseDeconstructionPattern(context, kind, depth + 1);
if (kind == DeconstructToExpressions && !innerPattern)
return 0;
failIfFalse(innerPattern, "Cannot parse this deconstruction pattern");
context.appendArrayPatternEntry(arrayPattern, location, innerPattern);
} while (consume(COMMA));
if (kind == DeconstructToExpressions && !match(CLOSEBRACKET))
return 0;
consumeOrFail(CLOSEBRACKET, "Expected either a closing ']' or a ',' following an element deconstruction pattern");
pattern = arrayPattern;
break;
}
case OPENBRACE: {
next();
if (kind == DeconstructToExpressions && match(CLOSEBRACE))
return 0;
failIfTrue(match(CLOSEBRACE), "There must be at least one bound property in an object deconstruction pattern");
auto objectPattern = context.createObjectPattern(m_token.m_location);
bool wasString = false;
do {
Identifier propertyName;
TreeDeconstructionPattern innerPattern = 0;
JSTokenLocation location = m_token.m_location;
if (match(IDENT)) {
propertyName = *m_token.m_data.ident;
next();
if (consume(COLON))
innerPattern = parseDeconstructionPattern(context, kind, depth + 1);
else
innerPattern = createBindingPattern(context, kind, propertyName, depth);
} else {
JSTokenType tokenType = m_token.m_type;
switch (m_token.m_type) {
case NUMBER:
propertyName = Identifier::from(m_vm, m_token.m_data.doubleValue);
break;
case STRING:
propertyName = *m_token.m_data.ident;
wasString = true;
break;
default:
if (m_token.m_type != RESERVED && m_token.m_type != RESERVED_IF_STRICT && !(m_token.m_type & KeywordTokenFlag)) {
if (kind == DeconstructToExpressions)
return 0;
failWithMessage("Expected a property name");
}
propertyName = *m_token.m_data.ident;
break;
}
next();
if (!consume(COLON)) {
if (kind == DeconstructToExpressions)
return 0;
semanticFailIfTrue(tokenType == RESERVED, "Cannot use abbreviated deconstruction syntax for reserved name '", propertyName.impl(), "'");
semanticFailIfTrue(tokenType == RESERVED_IF_STRICT, "Cannot use abbreviated deconstruction syntax for reserved name '", propertyName.impl(), "' in strict mode");
semanticFailIfTrue(tokenType & KeywordTokenFlag, "Cannot use abbreviated deconstruction syntax for keyword '", propertyName.impl(), "'");
failWithMessage("Expected a ':' prior to named property deconstruction");
}
innerPattern = parseDeconstructionPattern(context, kind, depth + 1);
}
if (kind == DeconstructToExpressions && !innerPattern)
return 0;
failIfFalse(innerPattern, "Cannot parse this deconstruction pattern");
context.appendObjectPatternEntry(objectPattern, location, wasString, propertyName, innerPattern);
} while (consume(COMMA));
if (kind == DeconstructToExpressions && !match(CLOSEBRACE))
return 0;
consumeOrFail(CLOSEBRACE, "Expected either a closing '}' or an ',' after a property deconstruction pattern");
pattern = objectPattern;
break;
}
default: {
if (!match(IDENT)) {
if (kind == DeconstructToExpressions)
return 0;
semanticFailureDueToKeyword("variable name");
failWithMessage("Expected a parameter pattern or a ')' in parameter list");
}
pattern = createBindingPattern(context, kind, *m_token.m_data.ident, depth);
next();
break;
}
}
m_nonLHSCount = nonLHSCount;
return pattern;
}
template <typename LexerType>
template <class TreeBuilder> TreeConstDeclList Parser<LexerType>::parseConstDeclarationList(TreeBuilder& context)
{
failIfTrue(strictMode(), "Const declarations are not supported in strict mode");
TreeConstDeclList constDecls = 0;
TreeConstDeclList tail = 0;
do {
JSTokenLocation location(tokenLocation());
next();
matchOrFail(IDENT, "Expected an identifier name in const declaration");
const Identifier* name = m_token.m_data.ident;
next();
bool hasInitializer = match(EQUAL);
declareVariable(name);
context.addVar(name, DeclarationStacks::IsConstant | (hasInitializer ? DeclarationStacks::HasInitializer : 0));
TreeExpression initializer = 0;
if (hasInitializer) {
next(TreeBuilder::DontBuildStrings); // consume '='
initializer = parseAssignmentExpression(context);
}
tail = context.appendConstDecl(location, tail, name, initializer);
if (!constDecls)
constDecls = tail;
} while (match(COMMA));
return constDecls;
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseForStatement(TreeBuilder& context)
{
ASSERT(match(FOR));
JSTokenLocation location(tokenLocation());
int startLine = tokenLine();
next();
handleProductionOrFail(OPENPAREN, "(", "start", "for-loop header");
int nonLHSCount = m_nonLHSCount;
int declarations = 0;
JSTextPosition declsStart;
JSTextPosition declsEnd;
TreeExpression decls = 0;
TreeDeconstructionPattern pattern = 0;
if (match(VAR)) {
/*
for (var IDENT in expression) statement
for (var varDeclarationList; expressionOpt; expressionOpt)
*/
TreeDeconstructionPattern forInTarget = 0;
TreeExpression forInInitializer = 0;
m_allowsIn = false;
JSTextPosition initStart;
JSTextPosition initEnd;
decls = parseVarDeclarationList(context, declarations, forInTarget, forInInitializer, declsStart, initStart, initEnd);
m_allowsIn = true;
propagateError();
// Remainder of a standard for loop is handled identically
if (match(SEMICOLON))
goto standardForLoop;
failIfFalse(declarations == 1, "must declare variables after 'var'");
failIfTrue(forInInitializer, "Cannot use initialiser syntax in a for-in loop");
// Handle for-in with var declaration
JSTextPosition inLocation = tokenStartPosition();
bool isOfEnumeration = false;
if (!consume(INTOKEN)) {
failIfFalse(match(IDENT) && *m_token.m_data.ident == m_vm->propertyNames->of, "Expected either 'in' or 'of' in enumeration syntax");
isOfEnumeration = true;
next();
}
TreeExpression expr = parseExpression(context);
failIfFalse(expr, "Expected expression to enumerate");
JSTextPosition exprEnd = lastTokenEndPosition();
int endLine = tokenLine();
handleProductionOrFail(CLOSEPAREN, ")", "end", (isOfEnumeration ? "for-of header" : "for-in header"));
const Identifier* unused = 0;
startLoop();
TreeStatement statement = parseStatement(context, unused);
endLoop();
failIfFalse(statement, "Expected statement as body of for-", isOfEnumeration ? "of" : "in", " statement");
if (isOfEnumeration)
return context.createForOfLoop(location, forInTarget, expr, statement, declsStart, inLocation, exprEnd, startLine, endLine);
return context.createForInLoop(location, forInTarget, expr, statement, declsStart, inLocation, exprEnd, startLine, endLine);
}
if (!match(SEMICOLON)) {
if (match(OPENBRACE) || match(OPENBRACKET)) {
SavePoint savePoint = createSavePoint();
declsStart = tokenStartPosition();
pattern = tryParseDeconstructionPatternExpression(context);
declsEnd = lastTokenEndPosition();
if (pattern && (match(INTOKEN) || (match(IDENT) && *m_token.m_data.ident == m_vm->propertyNames->of)))
goto enumerationLoop;
pattern = 0;
restoreSavePoint(savePoint);
}
m_allowsIn = false;
declsStart = tokenStartPosition();
decls = parseExpression(context);
declsEnd = lastTokenEndPosition();
m_allowsIn = true;
failIfFalse(decls, "Cannot parse for loop declarations");
}
if (match(SEMICOLON)) {
standardForLoop:
// Standard for loop
next();
TreeExpression condition = 0;
if (!match(SEMICOLON)) {
condition = parseExpression(context);
failIfFalse(condition, "Cannot parse for loop condition expression");
}
consumeOrFail(SEMICOLON, "Expected a ';' after the for loop condition expression");
TreeExpression increment = 0;
if (!match(CLOSEPAREN)) {
increment = parseExpression(context);
failIfFalse(increment, "Cannot parse for loop iteration expression");
}
int endLine = tokenLine();
handleProductionOrFail(CLOSEPAREN, ")", "end", "for-loop header");
const Identifier* unused = 0;
startLoop();
TreeStatement statement = parseStatement(context, unused);
endLoop();
failIfFalse(statement, "Expected a statement as the body of a for loop");
return context.createForLoop(location, decls, condition, increment, statement, startLine, endLine);
}
// For-in loop
enumerationLoop:
failIfFalse(nonLHSCount == m_nonLHSCount, "Expected a reference on the left hand side of an enumeration statement");
bool isOfEnumeration = false;
if (!consume(INTOKEN)) {
failIfFalse(match(IDENT) && *m_token.m_data.ident == m_vm->propertyNames->of, "Expected either 'in' or 'of' in enumeration syntax");
isOfEnumeration = true;
next();
}
TreeExpression expr = parseExpression(context);
failIfFalse(expr, "Cannot parse subject for-", isOfEnumeration ? "of" : "in", " statement");
JSTextPosition exprEnd = lastTokenEndPosition();
int endLine = tokenLine();
handleProductionOrFail(CLOSEPAREN, ")", "end", (isOfEnumeration ? "for-of header" : "for-in header"));
const Identifier* unused = 0;
startLoop();
TreeStatement statement = parseStatement(context, unused);
endLoop();
failIfFalse(statement, "Expected a statement as the body of a for-", isOfEnumeration ? "of" : "in", "loop");
if (pattern) {
ASSERT(!decls);
if (isOfEnumeration)
return context.createForOfLoop(location, pattern, expr, statement, declsStart, declsEnd, exprEnd, startLine, endLine);
return context.createForInLoop(location, pattern, expr, statement, declsStart, declsEnd, exprEnd, startLine, endLine);
}
if (isOfEnumeration)
return context.createForOfLoop(location, decls, expr, statement, declsStart, declsEnd, exprEnd, startLine, endLine);
return context.createForInLoop(location, decls, expr, statement, declsStart, declsEnd, exprEnd, startLine, endLine);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseBreakStatement(TreeBuilder& context)
{
ASSERT(match(BREAK));
JSTokenLocation location(tokenLocation());
JSTextPosition start = tokenStartPosition();
JSTextPosition end = tokenEndPosition();
next();
if (autoSemiColon()) {
semanticFailIfFalse(breakIsValid(), "'break' is only valid inside a switch or loop statement");
return context.createBreakStatement(location, start, end);
}
matchOrFail(IDENT, "Expected an identifier as the target for a break statement");
const Identifier* ident = m_token.m_data.ident;
semanticFailIfFalse(getLabel(ident), "Cannot use the undeclared label '", ident->impl(), "'");
end = tokenEndPosition();
next();
failIfFalse(autoSemiColon(), "Expected a ';' following a targeted break statement");
return context.createBreakStatement(location, ident, start, end);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseContinueStatement(TreeBuilder& context)
{
ASSERT(match(CONTINUE));
JSTokenLocation location(tokenLocation());
JSTextPosition start = tokenStartPosition();
JSTextPosition end = tokenEndPosition();
next();
if (autoSemiColon()) {
semanticFailIfFalse(continueIsValid(), "'continue' is only valid inside a loop statement");
return context.createContinueStatement(location, start, end);
}
matchOrFail(IDENT, "Expected an identifier as the target for a continue statement");
const Identifier* ident = m_token.m_data.ident;
ScopeLabelInfo* label = getLabel(ident);
semanticFailIfFalse(label, "Cannot use the undeclared label '", ident->impl(), "'");
semanticFailIfFalse(label->m_isLoop, "Cannot continue to the label '", ident->impl(), "' as it is not targeting a loop");
end = tokenEndPosition();
next();
failIfFalse(autoSemiColon(), "Expected a ';' following a targeted continue statement");
return context.createContinueStatement(location, ident, start, end);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseReturnStatement(TreeBuilder& context)
{
ASSERT(match(RETURN));
JSTokenLocation location(tokenLocation());
semanticFailIfFalse(currentScope()->isFunction(), "Return statements are only valid inside functions");
JSTextPosition start = tokenStartPosition();
JSTextPosition end = tokenEndPosition();
next();
// We do the auto semicolon check before attempting to parse expression
// as we need to ensure the a line break after the return correctly terminates
// the statement
if (match(SEMICOLON))
end = tokenEndPosition();
if (autoSemiColon())
return context.createReturnStatement(location, 0, start, end);
TreeExpression expr = parseExpression(context);
failIfFalse(expr, "Cannot parse the return expression");
end = lastTokenEndPosition();
if (match(SEMICOLON))
end = tokenEndPosition();
if (!autoSemiColon())
failWithMessage("Expected a ';' following a return statement");
return context.createReturnStatement(location, expr, start, end);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseThrowStatement(TreeBuilder& context)
{
ASSERT(match(THROW));
JSTokenLocation location(tokenLocation());
JSTextPosition start = tokenStartPosition();
next();
failIfTrue(match(SEMICOLON), "Expected expression after 'throw'");
semanticFailIfTrue(autoSemiColon(), "Cannot have a newline after 'throw'");
TreeExpression expr = parseExpression(context);
failIfFalse(expr, "Cannot parse expression for throw statement");
JSTextPosition end = lastTokenEndPosition();
failIfFalse(autoSemiColon(), "Expected a ';' after a throw statement");
return context.createThrowStatement(location, expr, start, end);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseWithStatement(TreeBuilder& context)
{
ASSERT(match(WITH));
JSTokenLocation location(tokenLocation());
semanticFailIfTrue(strictMode(), "'with' statements are not valid in strict mode");
currentScope()->setNeedsFullActivation();
int startLine = tokenLine();
next();
handleProductionOrFail(OPENPAREN, "(", "start", "subject of a 'with' statement");
int start = tokenStart();
TreeExpression expr = parseExpression(context);
failIfFalse(expr, "Cannot parse 'with' subject expression");
JSTextPosition end = lastTokenEndPosition();
int endLine = tokenLine();
handleProductionOrFail(CLOSEPAREN, ")", "start", "subject of a 'with' statement");
const Identifier* unused = 0;
TreeStatement statement = parseStatement(context, unused);
failIfFalse(statement, "A 'with' statement must have a body");
return context.createWithStatement(location, expr, statement, start, end, startLine, endLine);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseSwitchStatement(TreeBuilder& context)
{
ASSERT(match(SWITCH));
JSTokenLocation location(tokenLocation());
int startLine = tokenLine();
next();
handleProductionOrFail(OPENPAREN, "(", "start", "subject of a 'switch'");
TreeExpression expr = parseExpression(context);
failIfFalse(expr, "Cannot parse switch subject expression");
int endLine = tokenLine();
handleProductionOrFail(CLOSEPAREN, ")", "end", "subject of a 'switch'");
handleProductionOrFail(OPENBRACE, "{", "start", "body of a 'switch'");
startSwitch();
TreeClauseList firstClauses = parseSwitchClauses(context);
propagateError();
TreeClause defaultClause = parseSwitchDefaultClause(context);
propagateError();
TreeClauseList secondClauses = parseSwitchClauses(context);
propagateError();
endSwitch();
handleProductionOrFail(CLOSEBRACE, "}", "end", "body of a 'switch'");
return context.createSwitchStatement(location, expr, firstClauses, defaultClause, secondClauses, startLine, endLine);
}
template <typename LexerType>
template <class TreeBuilder> TreeClauseList Parser<LexerType>::parseSwitchClauses(TreeBuilder& context)
{
if (!match(CASE))
return 0;
next();
TreeExpression condition = parseExpression(context);
failIfFalse(condition, "Cannot parse switch clause");
consumeOrFail(COLON, "Expected a ':' after switch clause expression");
TreeSourceElements statements = parseSourceElements(context, DontCheckForStrictMode);
failIfFalse(statements, "Cannot parse the body of a switch clause");
TreeClause clause = context.createClause(condition, statements);
TreeClauseList clauseList = context.createClauseList(clause);
TreeClauseList tail = clauseList;
while (match(CASE)) {
next();
TreeExpression condition = parseExpression(context);
failIfFalse(condition, "Cannot parse switch case expression");
consumeOrFail(COLON, "Expected a ':' after switch clause expression");
TreeSourceElements statements = parseSourceElements(context, DontCheckForStrictMode);
failIfFalse(statements, "Cannot parse the body of a switch clause");
clause = context.createClause(condition, statements);
tail = context.createClauseList(tail, clause);
}
return clauseList;
}
template <typename LexerType>
template <class TreeBuilder> TreeClause Parser<LexerType>::parseSwitchDefaultClause(TreeBuilder& context)
{
if (!match(DEFAULT))
return 0;
next();
consumeOrFail(COLON, "Expected a ':' after switch default clause");
TreeSourceElements statements = parseSourceElements(context, DontCheckForStrictMode);
failIfFalse(statements, "Cannot parse the body of a switch default clause");
return context.createClause(0, statements);
}
template <typename LexerType>
template <class TreeBuilder> TreeStatement Parser<LexerType>::parseTryStatement(TreeBuilder& context)
{
ASSERT(match(TRY));
JSTokenLocation location(tokenLocation());
TreeStatement tryBlock = 0;