forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSParserImpl.cpp
7075 lines (6327 loc) · 210 KB
/
JSParserImpl.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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "JSParserImpl.h"
#include "hermes/AST/ESTreeJSONDumper.h"
#include "hermes/Support/PerfSection.h"
#include "llvh/Support/SaveAndRestore.h"
using llvh::cast;
using llvh::dyn_cast;
using llvh::isa;
namespace hermes {
namespace parser {
namespace detail {
JSParserImpl::JSParserImpl(
Context &context,
std::unique_ptr<llvh::MemoryBuffer> input)
: context_(context),
sm_(context.getSourceErrorManager()),
lexer_(
std::move(input),
context.getSourceErrorManager(),
context.getAllocator(),
&context.getStringTable(),
context.isStrictMode()),
pass_(FullParse) {
initializeIdentifiers();
}
JSParserImpl::JSParserImpl(Context &context, uint32_t bufferId, ParserPass pass)
: context_(context),
sm_(context.getSourceErrorManager()),
lexer_(
bufferId,
context.getSourceErrorManager(),
context.getAllocator(),
&context.getStringTable(),
context.isStrictMode()),
pass_(pass) {
preParsed_ = context.getPreParsedBufferInfo(bufferId);
initializeIdentifiers();
}
void JSParserImpl::initializeIdentifiers() {
getIdent_ = lexer_.getIdentifier("get");
setIdent_ = lexer_.getIdentifier("set");
initIdent_ = lexer_.getIdentifier("init");
useStrictIdent_ = lexer_.getIdentifier("use strict");
showSourceIdent_ = lexer_.getIdentifier("show source");
hideSourceIdent_ = lexer_.getIdentifier("hide source");
sensitiveIdent_ = lexer_.getIdentifier("sensitive");
useStaticBuiltinIdent_ = lexer_.getIdentifier("use static builtin");
letIdent_ = lexer_.getIdentifier("let");
ofIdent_ = lexer_.getIdentifier("of");
fromIdent_ = lexer_.getIdentifier("from");
asIdent_ = lexer_.getIdentifier("as");
implementsIdent_ = lexer_.getIdentifier("implements");
interfaceIdent_ = lexer_.getIdentifier("interface");
packageIdent_ = lexer_.getIdentifier("package");
privateIdent_ = lexer_.getIdentifier("private");
protectedIdent_ = lexer_.getIdentifier("protected");
publicIdent_ = lexer_.getIdentifier("public");
staticIdent_ = lexer_.getIdentifier("static");
methodIdent_ = lexer_.getIdentifier("method");
constructorIdent_ = lexer_.getIdentifier("constructor");
yieldIdent_ = lexer_.getIdentifier("yield");
newIdent_ = lexer_.getIdentifier("new");
targetIdent_ = lexer_.getIdentifier("target");
importIdent_ = lexer_.getIdentifier("import");
metaIdent_ = lexer_.getIdentifier("meta");
valueIdent_ = lexer_.getIdentifier("value");
typeIdent_ = lexer_.getIdentifier("type");
asyncIdent_ = lexer_.getIdentifier("async");
awaitIdent_ = lexer_.getIdentifier("await");
assertIdent_ = lexer_.getIdentifier("assert");
#if HERMES_PARSE_FLOW
typeofIdent_ = lexer_.getIdentifier("typeof");
keyofIdent_ = lexer_.getIdentifier("keyof");
declareIdent_ = lexer_.getIdentifier("declare");
protoIdent_ = lexer_.getIdentifier("proto");
opaqueIdent_ = lexer_.getIdentifier("opaque");
plusIdent_ = lexer_.getIdentifier("plus");
minusIdent_ = lexer_.getIdentifier("minus");
moduleIdent_ = lexer_.getIdentifier("module");
exportsIdent_ = lexer_.getIdentifier("exports");
esIdent_ = lexer_.getIdentifier("ES");
commonJSIdent_ = lexer_.getIdentifier("CommonJS");
mixinsIdent_ = lexer_.getIdentifier("mixins");
thisIdent_ = lexer_.getIdentifier("this");
anyIdent_ = lexer_.getIdentifier("any");
mixedIdent_ = lexer_.getIdentifier("mixed");
emptyIdent_ = lexer_.getIdentifier("empty");
booleanIdent_ = lexer_.getIdentifier("boolean");
boolIdent_ = lexer_.getIdentifier("bool");
numberIdent_ = lexer_.getIdentifier("number");
stringIdent_ = lexer_.getIdentifier("string");
voidIdent_ = lexer_.getIdentifier("void");
nullIdent_ = lexer_.getIdentifier("null");
symbolIdent_ = lexer_.getIdentifier("symbol");
bigintIdent_ = lexer_.getIdentifier("bigint");
mappedTypeOptionalIdent_ = lexer_.getIdentifier("Optional");
mappedTypePlusOptionalIdent_ = lexer_.getIdentifier("PlusOptional");
mappedTypeMinusOptionalIdent_ = lexer_.getIdentifier("MinusOptional");
checksIdent_ = lexer_.getIdentifier("%checks");
assertsIdent_ = lexer_.getIdentifier("asserts");
impliesIdent_ = lexer_.getIdentifier("implies");
// Flow Component syntax
componentIdent_ = lexer_.getIdentifier("component");
rendersIdent_ = lexer_.getIdentifier("renders");
rendersMaybeOperator_ = lexer_.getIdentifier("renders?");
rendersStarOperator_ = lexer_.getIdentifier("renders*");
hookIdent_ = lexer_.getIdentifier("hook");
// Flow match expressions and statements
matchIdent_ = lexer_.getIdentifier("match");
underscoreIdent_ = lexer_.getIdentifier("_");
#endif
#if HERMES_PARSE_TS
readonlyIdent_ = lexer_.getIdentifier("readonly");
neverIdent_ = lexer_.getIdentifier("never");
undefinedIdent_ = lexer_.getIdentifier("undefined");
unknownIdent_ = lexer_.getIdentifier("unknown");
#endif
#if HERMES_PARSE_FLOW || HERMES_PARSE_TS
namespaceIdent_ = lexer_.getIdentifier("namespace");
isIdent_ = lexer_.getIdentifier("is");
inferIdent_ = lexer_.getIdentifier("infer");
constIdent_ = lexer_.getIdentifier("const");
#endif
// Generate the string representation of all tokens.
for (unsigned i = 0; i != NUM_JS_TOKENS; ++i)
tokenIdent_[i] = lexer_.getIdentifier(tokenKindStr((TokenKind)i));
}
Optional<ESTree::ProgramNode *> JSParserImpl::parse() {
PerfSection parsing("Parsing JavaScript");
tok_ = lexer_.advance();
auto res = parseProgram();
if (!res)
return None;
if (lexer_.getSourceMgr().getErrorCount() != 0)
return None;
return res.getValue();
}
void JSParserImpl::errorExpected(
ArrayRef<TokenKind> toks,
const char *where,
const char *what,
SMLoc whatLoc) {
llvh::SmallString<4> str;
llvh::raw_svector_ostream ss{str};
for (unsigned i = 0; i < toks.size(); ++i) {
// Insert a separator after the first token.
if (i > 0) {
// Use " or " instead of ", " before the last token.
if (i == toks.size() - 1)
ss << " or ";
else
ss << ", ";
}
ss << "'" << tokenKindStr(toks[i]) << "'";
}
ss << " expected";
// Optionally append the 'where' description.
if (where)
ss << " " << where;
SMLoc errorLoc = tok_->getStartLoc();
SourceErrorManager::SourceCoords curCoords;
SourceErrorManager::SourceCoords whatCoords;
// If the location of 'what' is provided, find its and the error's source
// coordinates.
if (whatLoc.isValid()) {
sm_.findBufferLineAndLoc(errorLoc, curCoords);
sm_.findBufferLineAndLoc(whatLoc, whatCoords);
}
if (whatCoords.isSameSourceLineAs(curCoords)) {
// If the what source coordinates are on the same line as the error, show
// them both.
sm_.error(
errorLoc,
SourceErrorManager::combineIntoRange(whatLoc, errorLoc),
ss.str(),
Subsystem::Parser);
} else {
sm_.error(errorLoc, ss.str(), Subsystem::Parser);
if (what && whatCoords.isValid())
sm_.note(whatLoc, what, Subsystem::Parser);
}
}
bool JSParserImpl::need(
TokenKind kind,
const char *where,
const char *what,
SMLoc whatLoc) {
if (tok_->getKind() == kind) {
return true;
}
errorExpected(kind, where, what, whatLoc);
return false;
}
bool JSParserImpl::eat(
TokenKind kind,
JSLexer::GrammarContext grammarContext,
const char *where,
const char *what,
SMLoc whatLoc) {
if (need(kind, where, what, whatLoc)) {
advance(grammarContext);
return true;
}
return false;
}
bool JSParserImpl::checkAndEat(
TokenKind kind,
JSLexer::GrammarContext grammarContext) {
if (tok_->getKind() == kind) {
advance(grammarContext);
return true;
}
return false;
}
bool JSParserImpl::checkAndEat(
UniqueString *ident,
JSLexer::GrammarContext grammarContext) {
if (check(ident)) {
advance(grammarContext);
return true;
}
return false;
}
bool JSParserImpl::checkAssign() const {
return checkN(
TokenKind::equal,
TokenKind::starequal,
TokenKind::slashequal,
TokenKind::percentequal,
TokenKind::plusequal,
TokenKind::minusequal,
TokenKind::lesslessequal,
TokenKind::greatergreaterequal,
TokenKind::greatergreatergreaterequal,
TokenKind::starstarequal,
TokenKind::pipepipeequal,
TokenKind::ampampequal,
TokenKind::questionquestionequal,
TokenKind::ampequal,
TokenKind::caretequal,
TokenKind::pipeequal);
}
bool JSParserImpl::checkEndAssignmentExpression(
OfEndsAssignment ofEndsAssignment) const {
return checkN(
TokenKind::rw_in,
TokenKind::r_paren,
TokenKind::r_brace,
TokenKind::r_square,
TokenKind::comma,
TokenKind::semi,
TokenKind::colon,
TokenKind::eof) ||
(ofEndsAssignment == OfEndsAssignment::Yes && check(ofIdent_)) ||
lexer_.isNewLineBeforeCurrentToken();
}
bool JSParserImpl::checkAsyncFunction() {
// async [no LineTerminator here] function
// ^
assert(
check(asyncIdent_) && "check for async function must occur at 'async'");
// Avoid passing TokenKind::rw_function here, because parseFunctionHelper
// relies on seeing `async` in order to construct its AST node.
// This function must also be idempotent to allow for branching based on its
// result in parseStatementListItem without having to store another flag,
// for example.
OptValue<TokenKind> optNext = lexer_.lookahead1(llvh::None);
return optNext.hasValue() && *optNext == TokenKind::rw_function;
}
bool JSParserImpl::eatSemi(bool optional) {
if (tok_->getKind() == TokenKind::semi) {
advance();
return true;
}
if (tok_->getKind() == TokenKind::r_brace ||
tok_->getKind() == TokenKind::eof ||
lexer_.isNewLineBeforeCurrentToken()) {
return true;
}
if (!optional)
error(tok_->getStartLoc(), "';' expected");
return false;
}
void JSParserImpl::processDirective(UniqueString *directive) {
seenDirectives_.push_back(directive);
if (directive == useStrictIdent_)
setStrictMode(true);
if (directive == useStaticBuiltinIdent_)
setUseStaticBuiltin();
}
bool JSParserImpl::recursionDepthExceeded() {
error(
tok_->getStartLoc(),
"Too many nested expressions/statements/declarations");
return true;
}
Optional<ESTree::ProgramNode *> JSParserImpl::parseProgram() {
SMLoc startLoc = tok_->getStartLoc();
SaveStrictModeAndSeenDirectives saveStrictModeAndSeenDirectives{this};
ESTree::NodeList stmtList;
if (!parseStatementList(
Param{}, TokenKind::eof, true, AllowImportExport::Yes, stmtList))
return None;
SMLoc endLoc = startLoc;
if (!stmtList.empty()) {
endLoc = stmtList.back().getEndLoc();
}
auto *program = setLocation(
startLoc,
endLoc,
new (context_) ESTree::ProgramNode(std::move(stmtList)));
return program;
}
Optional<ESTree::FunctionDeclarationNode *>
JSParserImpl::parseFunctionDeclaration(Param param, bool forceEagerly) {
auto optRes = parseFunctionHelper(param, true, forceEagerly);
if (!optRes)
return None;
return cast<ESTree::FunctionDeclarationNode>(*optRes);
}
Optional<ESTree::FunctionLikeNode *> JSParserImpl::parseFunctionHelper(
Param param,
bool isDeclaration,
bool forceEagerly) {
// function or async function
assert(check(TokenKind::rw_function) || check(asyncIdent_));
bool isAsync = check(asyncIdent_);
SMLoc startLoc = advance().Start;
if (isAsync) {
// async function
// ^
advance();
}
bool isGenerator = checkAndEat(TokenKind::star);
// newParamYield setting per the grammar:
// FunctionDeclaration: BindingIdentifier[?Yield, ?Await]
// FunctionExpression: BindingIdentifier[~Yield, ~Await]
// GeneratorFunctionDeclaration: BindingIdentifier[?Yield, ?Await]
// GeneratorFunctionExpression: BindingIdentifier[+Yield, ~Await]
// AsyncFunctionDeclaration: BindingIdentifier[?Yield, ?Await]
// AsyncFunctionExpression: BindingIdentifier[+Yield, +Await]
// AsyncGeneratorDeclaration: BindingIdentifier[?Yield, ?Await]
// AsyncGeneratorExpression: BindingIdentifier[+Yield, +Await]
bool nameParamYield = isDeclaration ? paramYield_ : isGenerator;
llvh::SaveAndRestore<bool> saveNameParamYield(paramYield_, nameParamYield);
bool nameParamAwait = isDeclaration ? paramAwait_ : isAsync;
llvh::SaveAndRestore<bool> saveNameParamAwait(paramAwait_, nameParamAwait);
// identifier
auto optId = parseBindingIdentifier(Param{});
// If this is a default function declaration, then we can match
// [+Default] function ( FormalParameters ) { FunctionBody }
// so the identifier is optional and we can make it nullptr.
if (isDeclaration && !param.has(ParamDefault) && !optId) {
errorExpected(
TokenKind::identifier,
"after 'function'",
"location of 'function'",
startLoc);
return None;
}
ESTree::Node *typeParams = nullptr;
#if HERMES_PARSE_FLOW
if (context_.getParseFlow() && check(TokenKind::less)) {
auto optTypeParams = parseTypeParamsFlow();
if (!optTypeParams)
return None;
typeParams = *optTypeParams;
}
#endif
#if HERMES_PARSE_TS
if (context_.getParseTS() && check(TokenKind::less)) {
auto optTypeParams = parseTSTypeParameters();
if (!optTypeParams)
return None;
typeParams = *optTypeParams;
}
#endif
// (
if (!need(
TokenKind::l_paren,
"at start of function parameter list",
isDeclaration ? "function declaration starts here"
: "function expression starts here",
startLoc)) {
return None;
}
ESTree::NodeList paramList;
llvh::SaveAndRestore<bool> saveArgsAndBodyParamYield(
paramYield_, isGenerator);
llvh::SaveAndRestore<bool> saveArgsAndBodyParamAwait(paramAwait_, isAsync);
if (!parseFormalParameters(param, paramList))
return None;
ESTree::Node *returnType = nullptr;
ESTree::Node *predicate = nullptr;
#if HERMES_PARSE_FLOW
if (context_.getParseFlow() && check(TokenKind::colon)) {
SMLoc annotStart = advance(JSLexer::GrammarContext::Type).Start;
if (!check(checksIdent_)) {
auto optRet = parseReturnTypeAnnotationFlow(annotStart);
if (!optRet)
return None;
returnType = *optRet;
}
if (check(checksIdent_)) {
auto optPred = parsePredicateFlow();
if (!optPred)
return None;
predicate = *optPred;
}
}
#endif
#if HERMES_PARSE_TS
if (context_.getParseTS() && check(TokenKind::colon)) {
SMLoc annotStart = advance(JSLexer::GrammarContext::Type).Start;
if (!check(checksIdent_)) {
auto optRet = parseTypeAnnotationTS(annotStart);
if (!optRet)
return None;
returnType = *optRet;
}
}
#endif
// {
if (!need(
TokenKind::l_brace,
isDeclaration ? "in function declaration" : "in function expression",
isDeclaration ? "start of function declaration"
: "start of function expression",
startLoc)) {
return None;
}
SaveStrictModeAndSeenDirectives saveStrictModeAndSeenDirectives{this};
// Grammar context to be used when lexing the closing brace.
auto grammarContext =
isDeclaration ? JSLexer::AllowRegExp : JSLexer::AllowDiv;
if (pass_ == PreParse) {
// Create the nodes we want to keep before the AllocationScope.
ESTree::FunctionLikeNode *node;
if (isDeclaration) {
auto *decl = new (context_) ESTree::FunctionDeclarationNode(
optId ? *optId : nullptr,
std::move(paramList),
nullptr,
typeParams,
returnType,
predicate,
isGenerator,
isAsync);
// Initialize the node with a blank body.
decl->_body = new (context_) ESTree::BlockStatementNode({});
node = decl;
} else {
auto *expr = new (context_) ESTree::FunctionExpressionNode(
optId ? *optId : nullptr,
std::move(paramList),
nullptr,
typeParams,
returnType,
predicate,
isGenerator,
isAsync);
// Initialize the node with a blank body.
expr->_body = new (context_) ESTree::BlockStatementNode({});
node = expr;
}
AllocationScope scope(context_.getAllocator());
auto body = parseFunctionBody(
Param{},
false,
saveArgsAndBodyParamYield.get(),
saveArgsAndBodyParamAwait.get(),
grammarContext,
true);
if (!body)
return None;
return setLocation(startLoc, body.getValue(), node);
}
auto parsedBody = parseFunctionBody(
Param{},
forceEagerly,
saveArgsAndBodyParamYield.get(),
saveArgsAndBodyParamAwait.get(),
grammarContext,
true);
if (!parsedBody)
return None;
auto *body = parsedBody.getValue();
ESTree::FunctionLikeNode *node;
if (isDeclaration) {
auto *decl = new (context_) ESTree::FunctionDeclarationNode(
optId ? *optId : nullptr,
std::move(paramList),
body,
typeParams,
returnType,
predicate,
isGenerator,
isAsync);
node = decl;
} else {
auto *expr = new (context_) ESTree::FunctionExpressionNode(
optId ? *optId : nullptr,
std::move(paramList),
body,
typeParams,
returnType,
predicate,
isGenerator,
isAsync);
node = expr;
}
return setLocation(startLoc, body, node);
}
bool JSParserImpl::parseFormalParameters(
Param param,
ESTree::NodeList ¶mList) {
assert(check(TokenKind::l_paren) && "FormalParameters must start with '('");
// (
SMLoc lparenLoc = advance().Start;
#if HERMES_PARSE_FLOW || HERMES_PARSE_TS
// The first parameter can be 'this' in Flow and TypeScript.
if (context_.getParseTypes() && check(TokenKind::rw_this)) {
auto *name = tok_->getResWordIdentifier();
SMLoc thisParamStart = advance().Start;
SMLoc annotStart = tok_->getStartLoc();
if (!eat(
TokenKind::colon,
JSLexer::GrammarContext::Type,
"in 'this' type annotation",
"start of 'this'",
thisParamStart))
return false;
auto optType = parseTypeAnnotation(annotStart);
if (!optType)
return false;
ESTree::Node *type = *optType;
paramList.push_back(*setLocation(
thisParamStart,
getPrevTokenEndLoc(),
new (context_) ESTree::IdentifierNode(name, type, false)));
checkAndEat(TokenKind::comma);
}
#endif
while (!check(TokenKind::r_paren)) {
if (check(TokenKind::dotdotdot)) {
// BindingRestElement.
auto optRestElem = parseBindingRestElement(param);
if (!optRestElem)
return false;
paramList.push_back(*optRestElem.getValue());
break;
}
// BindingElement.
auto optElem = parseBindingElement(param);
if (!optElem)
return false;
paramList.push_back(*optElem.getValue());
if (!checkAndEat(TokenKind::comma))
break;
}
// )
if (!eat(
TokenKind::r_paren,
JSLexer::AllowRegExp,
"at end of function parameter list",
"start of parameter list",
lparenLoc)) {
return false;
}
return true;
}
Optional<ESTree::Node *> JSParserImpl::parseStatement(Param param) {
CHECK_RECURSION;
#define _RET(parseFunc) \
if (auto res = (parseFunc)) \
return res.getValue(); \
else \
return None;
switch (tok_->getKind()) {
case TokenKind::l_brace:
_RET(parseBlock(param));
case TokenKind::rw_var:
_RET(parseVariableStatement(Param{}));
case TokenKind::semi:
_RET(parseEmptyStatement());
case TokenKind::rw_if:
_RET(parseIfStatement(param.get(ParamReturn)));
case TokenKind::rw_while:
_RET(parseWhileStatement(param.get(ParamReturn)));
case TokenKind::rw_do:
_RET(parseDoWhileStatement(param.get(ParamReturn)));
case TokenKind::rw_for:
_RET(parseForStatement(param.get(ParamReturn)));
case TokenKind::rw_continue:
_RET(parseContinueStatement());
case TokenKind::rw_break:
_RET(parseBreakStatement());
case TokenKind::rw_return:
if (!param.has(ParamReturn) && !context_.allowReturnOutsideFunction()) {
// Illegal location for a return statement, but we can keep parsing.
error(tok_->getSourceRange(), "'return' not in a function");
}
_RET(parseReturnStatement());
case TokenKind::rw_with:
_RET(parseWithStatement(param.get(ParamReturn)));
case TokenKind::rw_switch:
_RET(parseSwitchStatement(param.get(ParamReturn)));
case TokenKind::rw_throw:
_RET(parseThrowStatement(Param{}));
case TokenKind::rw_try:
_RET(parseTryStatement(param.get(ParamReturn)));
case TokenKind::rw_debugger:
_RET(parseDebuggerStatement());
default:
#if HERMES_PARSE_FLOW
if (context_.getParseFlow() && context_.getParseFlowMatch() &&
LLVM_UNLIKELY(checkMaybeFlowMatch())) {
auto optMatch = tryParseMatchStatementFlow(param.get(ParamReturn));
if (!optMatch)
return None;
if (*optMatch)
return *optMatch;
}
#endif
_RET(parseExpressionOrLabelledStatement(param.get(ParamReturn)));
}
#undef _RET
}
llvh::SmallVector<llvh::SmallString<24>, 1> JSParserImpl::copySeenDirectives()
const {
llvh::SmallVector<llvh::SmallString<24>, 1> copies;
for (UniqueString *directive : seenDirectives_) {
copies.emplace_back(directive->str());
}
return copies;
}
Optional<ESTree::BlockStatementNode *> JSParserImpl::parseFunctionBody(
Param param,
bool eagerly,
bool paramYield,
bool paramAwait,
JSLexer::GrammarContext grammarContext,
bool parseDirectives) {
if (pass_ == LazyParse && !eagerly) {
auto startLoc = tok_->getStartLoc();
assert(
preParsed_->functionInfo.count(startLoc) == 1 &&
"no function info stored during preparse");
PreParsedFunctionInfo functionInfo = preParsed_->functionInfo[startLoc];
SMLoc endLoc = functionInfo.end;
if ((unsigned)(endLoc.getPointer() - startLoc.getPointer()) >=
context_.getPreemptiveFunctionCompilationThreshold()) {
lexer_.seek(endLoc);
advance(grammarContext);
// Emulate parsing the "use strict" directive in parseBlock.
setStrictMode(functionInfo.strictMode);
// PreParse collected directives idents into \c PreParsedFunctionInfo,
// iterate on them and fabricate directive nodes into the body node so
// the semantic validator can scan them back.
ESTree::NodeList stmtList;
for (const llvh::SmallString<24> &directive : functionInfo.directives) {
auto *strLit = new (context_)
ESTree::StringLiteralNode(lexer_.getIdentifier(directive));
auto *dirStmt = new (context_)
ESTree::ExpressionStatementNode(strLit, strLit->_value);
stmtList.push_back(*dirStmt);
}
auto *body =
new (context_) ESTree::BlockStatementNode(std::move(stmtList));
body->isLazyFunctionBody = true;
// Set params based on what they were at the _start_ of the function's
// source, not what they are now, because they might have changed.
// For example,
// get [yield]() {}
// means different things based on the value of paramYield at `get`,
// not at the `{`.
body->paramYield = paramYield;
body->paramAwait = paramAwait;
body->bufferId = lexer_.getBufferId();
return setLocation(startLoc, endLoc, body);
}
}
auto body = parseBlock(ParamReturn, grammarContext, parseDirectives);
if (!body)
return None;
if (pass_ == PreParse) {
preParsed_->functionInfo[(*body)->getStartLoc()] = PreParsedFunctionInfo{
(*body)->getEndLoc(), isStrictMode(), copySeenDirectives()};
}
return body;
}
Optional<ESTree::Node *> JSParserImpl::parseDeclaration(Param param) {
CHECK_RECURSION;
assert(checkDeclaration() && "invalid start for declaration");
if (check(TokenKind::rw_function) || check(asyncIdent_)) {
auto fdecl = parseFunctionDeclaration(Param{});
if (!fdecl)
return None;
return *fdecl;
}
if (check(TokenKind::rw_class)) {
auto optClass = parseClassDeclaration(Param{});
if (!optClass)
return None;
return *optClass;
}
if (checkN(TokenKind::rw_const, letIdent_)) {
auto optLexDecl = parseLexicalDeclaration(ParamIn);
if (!optLexDecl)
return None;
return *optLexDecl;
}
#if HERMES_PARSE_FLOW
if (context_.getParseFlow()) {
auto optDecl = parseFlowDeclaration();
if (!optDecl)
return None;
return *optDecl;
}
#endif
#if HERMES_PARSE_TS
if (context_.getParseTS()) {
auto optDecl = parseTSDeclaration();
if (!optDecl)
return None;
return *optDecl;
}
#endif
assert(false && "checkDeclaration() returned true without a declaration");
return None;
}
bool JSParserImpl::parseStatementListItem(
Param param,
AllowImportExport allowImportExport,
ESTree::NodeList &stmtList) {
if (checkDeclaration()) {
auto decl = parseDeclaration(Param{});
if (!decl)
return false;
stmtList.push_back(*decl.getValue());
#if HERMES_PARSE_FLOW
} else if (context_.getParseFlow() && checkDeclareType()) {
// declare var, declare function, declare interface, etc.
SMLoc start = advance(JSLexer::GrammarContext::Type).Start;
auto decl = parseDeclareFLow(start);
if (!decl)
return false;
stmtList.push_back(*decl.getValue());
#endif
} else if (tok_->getKind() == TokenKind::rw_import) {
// 'import' can indicate an import declaration, but it's also possible a
// Statement begins with a call to `import()`, so do a lookahead to see if
// the next token is '('.
// It can also be import.meta, so check for '.'.
auto optNext = lexer_.lookahead1(None);
if (optNext.hasValue() &&
(*optNext == TokenKind::l_paren || *optNext == TokenKind::period)) {
auto stmt = parseStatement(param.get(ParamReturn));
if (!stmt)
return false;
stmtList.push_back(*stmt.getValue());
} else {
auto importDecl = parseImportDeclaration();
if (!importDecl) {
return false;
}
stmtList.push_back(*importDecl.getValue());
if (allowImportExport == AllowImportExport::No) {
error(
importDecl.getValue()->getSourceRange(),
"import declaration must be at top level of module");
}
}
} else if (tok_->getKind() == TokenKind::rw_export) {
auto exportDecl = parseExportDeclaration();
if (!exportDecl) {
return false;
}
if (allowImportExport == AllowImportExport::Yes) {
stmtList.push_back(**exportDecl);
} else {
error(
exportDecl.getValue()->getSourceRange(),
"export declaration must be at top level of module");
}
} else {
auto stmt = parseStatement(param.get(ParamReturn));
if (!stmt)
return false;
stmtList.push_back(*stmt.getValue());
}
return true;
}
template <typename... Tail>
Optional<bool> JSParserImpl::parseStatementList(
Param param,
TokenKind until,
bool parseDirectives,
AllowImportExport allowImportExport,
ESTree::NodeList &stmtList,
Tail... otherUntil) {
if (parseDirectives) {
ESTree::ExpressionStatementNode *dirStmt;
while (check(TokenKind::string_literal) &&
(dirStmt = parseDirective()) != nullptr) {
stmtList.push_back(*dirStmt);
}
}
while (!check(TokenKind::eof) && !checkN(until, otherUntil...)) {
if (!parseStatementListItem(param, allowImportExport, stmtList)) {
return None;
}
}
return true;
}
Optional<ESTree::BlockStatementNode *> JSParserImpl::parseBlock(
Param param,
JSLexer::GrammarContext grammarContext,
bool parseDirectives) {
// {
assert(check(TokenKind::l_brace));
SMLoc startLoc = advance().Start;
ESTree::NodeList stmtList;
if (!parseStatementList(
param,
TokenKind::r_brace,
parseDirectives,
AllowImportExport::No,
stmtList)) {
return None;
}
// }
auto *body = setLocation(
startLoc,
tok_,
new (context_) ESTree::BlockStatementNode(std::move(stmtList)));
if (!eat(
TokenKind::r_brace,
grammarContext,
"at end of block",
"block starts here",
startLoc))
return None;
return body;
}
bool JSParserImpl::validateBindingIdentifier(
Param param,
SMRange range,
UniqueString *id,
TokenKind kind) {
if (id == yieldIdent_) {
// yield is permitted as BindingIdentifier in the grammar,
// and prohibited with static semantics.
if (isStrictMode() || paramYield_) {
error(range, "Unexpected usage of 'yield' as an identifier");
}
}
if (id == awaitIdent_) {
// await is permitted as BindingIdentifier in the grammar,
// and prohibited with static semantics.
if (paramAwait_) {
error(range, "Unexpected usage of 'await' as an identifier");
}
}
if (isStrictMode() && id == letIdent_) {
// ES9.0 12.1.1
// BindingIdentifier : Identifier
// Identifier : IdentifierName (but not ReservedWord)
// It is a Syntax Error if this phrase is contained in strict mode code
// and the StringValue of IdentifierName is: "implements", "interface",
// "let", "package", "private", "protected", "public", "static", or
// "yield".
// NOTE: All except 'let' are scanned as reserved words instead of
// identifiers, so we only check for `let` here.
error(