-
Notifications
You must be signed in to change notification settings - Fork 649
/
Copy pathSemanticValidator.cpp
1541 lines (1345 loc) · 51.7 KB
/
SemanticValidator.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 "SemanticValidator.h"
#include "hermes/AST/ESTree.h"
#include "hermes/Regex/RegexSerialization.h"
#include "llvh/ADT/ScopeExit.h"
#include "llvh/ADT/SmallSet.h"
#include "llvh/Support/SaveAndRestore.h"
using llvh::cast_or_null;
using llvh::dyn_cast;
using llvh::isa;
using llvh::SaveAndRestore;
namespace hermes {
namespace sem {
//===----------------------------------------------------------------------===//
// Keywords
Keywords::Keywords(Context &astContext)
: identArguments(
astContext.getIdentifier("arguments").getUnderlyingPointer()),
identEval(astContext.getIdentifier("eval").getUnderlyingPointer()),
identDelete(astContext.getIdentifier("delete").getUnderlyingPointer()),
identThis(astContext.getIdentifier("this").getUnderlyingPointer()),
identUseStrict(
astContext.getIdentifier("use strict").getUnderlyingPointer()),
identShowSource(
astContext.getIdentifier("show source").getUnderlyingPointer()),
identHideSource(
astContext.getIdentifier("hide source").getUnderlyingPointer()),
identSensitive(
astContext.getIdentifier("sensitive").getUnderlyingPointer()),
identVar(astContext.getIdentifier("var").getUnderlyingPointer()),
identLet(astContext.getIdentifier("let").getUnderlyingPointer()),
identConst(astContext.getIdentifier("const").getUnderlyingPointer()),
identPlus(astContext.getIdentifier("+").getUnderlyingPointer()),
identMinus(astContext.getIdentifier("-").getUnderlyingPointer()),
identAssign(astContext.getIdentifier("=").getUnderlyingPointer()) {}
//===----------------------------------------------------------------------===//
// SemanticValidator
SemanticValidator::SemanticValidator(
Context &astContext,
sem::SemContext &semCtx,
bool compile)
: astContext_(astContext),
sm_(astContext.getSourceErrorManager()),
bufferMessages_{&sm_},
semCtx_(semCtx),
initialErrorCount_(sm_.getErrorCount()),
kw_(astContext),
compile_(compile) {}
bool SemanticValidator::doIt(Node *rootNode) {
visitESTreeNode(*this, rootNode);
return sm_.getErrorCount() == initialErrorCount_;
}
bool SemanticValidator::doFunction(Node *function, bool strict) {
// Create a wrapper context since a function always assumes there is an
// existing context.
FunctionContext wrapperContext(this, strict, nullptr, nullptr);
assert(
wrapperContext.scopedClosures == nullptr &&
"current context doesnt have a body, so it shouldn't have closures.");
// Create a dummy closures array that will contain the closure for \p
// function.
FunctionInfo::BlockClosures dummyClosures;
wrapperContext.scopedClosures = &dummyClosures;
FunctionInfo::BlockDecls dummyDecls;
wrapperContext.scopedDecls = &dummyDecls;
visitESTreeNode(*this, function);
return sm_.getErrorCount() == initialErrorCount_;
}
void SemanticValidator::visit(ProgramNode *node) {
FunctionContext newFuncCtx{this, astContext_.isStrictMode(), node, node};
scanDirectivePrologue(node->_body);
setDirectiveDerivedInfo(node);
visitESTreeChildren(*this, node);
}
void SemanticValidator::visit(VariableDeclaratorNode *varDecl, Node *parent) {
auto *declaration = cast<VariableDeclarationNode>(parent);
FunctionInfo::VarDecl::Kind declKind;
if (declaration->_kind == kw_.identLet)
declKind = FunctionInfo::VarDecl::Kind::Let;
else if (declaration->_kind == kw_.identConst)
declKind = FunctionInfo::VarDecl::Kind::Const;
else {
assert(declaration->_kind == kw_.identVar);
declKind = FunctionInfo::VarDecl::Kind::Var;
}
validateDeclarationNames(
declKind,
varDecl->_id,
curFunction()->varDecls,
curFunction()->scopedDecls);
visitESTreeChildren(*this, varDecl);
}
void SemanticValidator::visit(MetaPropertyNode *metaProp) {
auto *meta = cast<IdentifierNode>(metaProp->_meta);
auto *property = cast<IdentifierNode>(metaProp->_property);
if (meta->_name->str() == "new" && property->_name->str() == "target") {
if (curFunction()->isGlobalScope()) {
// ES9.0 15.1.1:
// It is a Syntax Error if StatementList Contains NewTarget unless the
// source code containing NewTarget is eval code that is being processed
// by a direct eval.
// Hermes does not support local eval, so we assume that this is not
// inside a local eval call.
sm_.error(metaProp->getSourceRange(), "'new.target' not in a function");
}
return;
}
if (meta->_name->str() == "import" && property->_name->str() == "meta") {
if (compile_) {
sm_.error(
metaProp->getSourceRange(), "'import.meta' is currently unsupported");
}
return;
}
sm_.error(
metaProp->getSourceRange(),
"invalid meta property " + meta->_name->str() + "." +
property->_name->str());
}
void SemanticValidator::visit(IdentifierNode *identifier) {
if (identifier->_name == kw_.identEval && !astContext_.getEnableEval())
sm_.error(identifier->getSourceRange(), "'eval' is disabled");
if (identifier->_name == kw_.identArguments) {
if (forbidArguments_)
sm_.error(identifier->getSourceRange(), "invalid use of 'arguments'");
curFunction()->semInfo->usesArguments = true;
}
}
/// Process a function declaration by creating a new FunctionContext.
void SemanticValidator::visit(FunctionDeclarationNode *funcDecl) {
curFunction()->addHoistingCandidate(funcDecl);
visitFunction(funcDecl, funcDecl->_id, funcDecl->_params, funcDecl->_body);
}
/// Process a function expression by creating a new FunctionContext.
void SemanticValidator::visit(FunctionExpressionNode *funcExpr) {
visitFunction(funcExpr, funcExpr->_id, funcExpr->_params, funcExpr->_body);
}
void SemanticValidator::visit(ArrowFunctionExpressionNode *arrowFunc) {
// Convert expression functions to a full-body to simplify IRGen.
if (compile_ && arrowFunc->_expression) {
auto *retStmt = new (astContext_) ReturnStatementNode(arrowFunc->_body);
retStmt->copyLocationFrom(arrowFunc->_body);
ESTree::NodeList stmtList;
stmtList.push_back(*retStmt);
auto *blockStmt = new (astContext_) BlockStatementNode(std::move(stmtList));
blockStmt->copyLocationFrom(arrowFunc->_body);
arrowFunc->_body = blockStmt;
arrowFunc->_expression = false;
}
visitFunction(arrowFunc, nullptr, arrowFunc->_params, arrowFunc->_body);
curFunction()->semInfo->containsArrowFunctions = true;
curFunction()->semInfo->containsArrowFunctionsUsingArguments =
curFunction()->semInfo->containsArrowFunctionsUsingArguments ||
arrowFunc->getSemInfo()->containsArrowFunctionsUsingArguments ||
arrowFunc->getSemInfo()->usesArguments;
}
#if HERMES_PARSE_FLOW
/// Process a component declaration by creating a new FunctionContext.
void SemanticValidator::visit(ComponentDeclarationNode *componentDecl) {
visitFunction(
componentDecl,
componentDecl->_id,
componentDecl->_params,
componentDecl->_body);
}
/// Process a hook declaration by creating a new FunctionContext.
void SemanticValidator::visit(HookDeclarationNode *hookDecl) {
visitFunction(hookDecl, hookDecl->_id, hookDecl->_params, hookDecl->_body);
}
#endif
/// Ensure that the left side of for-in is an l-value.
void SemanticValidator::visit(ForInStatementNode *forIn) {
visitForInOf(forIn, forIn->_left);
}
void SemanticValidator::visit(ForOfStatementNode *forOf) {
if (compile_ && forOf->_await)
sm_.error(
forOf->getSourceRange(),
"for await..of loops are currently unsupported");
visitForInOf(forOf, forOf->_left);
}
void SemanticValidator::visitForInOf(LoopStatementNode *loopNode, Node *left) {
loopNode->setLabelIndex(curFunction()->allocateLabel());
SaveAndRestore<LoopStatementNode *> saveLoop(
curFunction()->activeLoop, loopNode);
SaveAndRestore<StatementNode *> saveSwitch(
curFunction()->activeSwitchOrLoop, loopNode);
if (auto *VD = dyn_cast<VariableDeclarationNode>(left)) {
assert(
VD->_declarations.size() == 1 &&
"for-in/for-of must have a single binding");
auto *declarator =
cast<ESTree::VariableDeclaratorNode>(&VD->_declarations.front());
if (declarator->_init) {
if (isa<ESTree::PatternNode>(declarator->_id)) {
sm_.error(
declarator->_init->getSourceRange(),
"destructuring declaration cannot be initialized in for-in/for-of loop");
} else if (!(isa<ForInStatementNode>(loopNode) &&
!curFunction()->strictMode && VD->_kind == kw_.identVar)) {
sm_.error(
declarator->_init->getSourceRange(),
"for-in/for-of variable declaration may not be initialized");
}
}
} else {
validateAssignmentTarget(left);
}
visitESTreeChildren(*this, loopNode);
}
void SemanticValidator::visit(BinaryExpressionNode *bin) {
// Handle nested +/- non-recursively.
if (bin->_operator == kw_.identPlus || bin->_operator == kw_.identMinus) {
auto list = linearizeLeft(bin, {"+", "-"});
if (list.size() > MAX_NESTED_BINARY) {
recursionDepthExceeded(bin);
return;
}
visitESTreeNode(*this, list[0]->_left, list[0]);
for (auto *e : list) {
visitESTreeNode(*this, e->_right, e);
}
return;
}
visitESTreeChildren(*this, bin);
}
/// Ensure that the left side of assgnments is an l-value.
void SemanticValidator::visit(AssignmentExpressionNode *assignment) {
// Handle nested "=" non-recursively.
if (assignment->_operator == kw_.identAssign) {
auto list = linearizeRight(assignment, {"="});
if (list.size() > MAX_NESTED_ASSIGNMENTS) {
recursionDepthExceeded(assignment);
return;
}
for (auto *e : list) {
validateAssignmentTarget(e->_left);
visitESTreeNode(*this, e->_left, e);
}
visitESTreeNode(*this, list.back()->_right, list.back());
return;
}
validateAssignmentTarget(assignment->_left);
visitESTreeChildren(*this, assignment);
}
/// Ensure that the operand of ++/-- is an l-value.
void SemanticValidator::visit(UpdateExpressionNode *update) {
// Check if the left-hand side is valid.
if (!isLValue(update->_argument)) {
sm_.error(
update->_argument->getSourceRange(),
"invalid operand in update operation");
}
visitESTreeChildren(*this, update);
}
/// Declare named labels, checking for duplicates, etc.
void SemanticValidator::visit(LabeledStatementNode *labelStmt) {
auto id = cast<IdentifierNode>(labelStmt->_label);
labelStmt->setLabelIndex(curFunction()->allocateLabel());
// Determine the target statement. We need to check if it directly encloses
// a loop or another label enclosing a loop.
StatementNode *targetStmt = labelStmt;
{
LabeledStatementNode *curStmt = labelStmt;
do {
if (auto *LS = dyn_cast<LoopStatementNode>(curStmt->_body)) {
targetStmt = LS;
break;
}
} while ((curStmt = dyn_cast<LabeledStatementNode>(curStmt->_body)));
}
// Define the new label, checking for a previous definition.
auto insertRes =
curFunction()->labelMap.insert({id->_name, {id, targetStmt}});
if (!insertRes.second) {
sm_.error(
id->getSourceRange(),
llvh::Twine("label '") + id->_name->str() + "' is already defined");
sm_.note(
insertRes.first->second.declarationNode->getSourceRange(),
"previous definition");
}
// Auto-erase the label on exit, if we inserted it.
const auto &deleter = llvh::make_scope_exit([=]() {
if (insertRes.second)
curFunction()->labelMap.erase(id->_name);
});
(void)deleter;
visitESTreeChildren(*this, labelStmt);
}
/// Check RegExp syntax.
void SemanticValidator::visit(RegExpLiteralNode *regexp) {
llvh::StringRef regexpError;
if (compile_) {
if (auto compiled = CompiledRegExp::tryCompile(
regexp->_pattern->str(), regexp->_flags->str(), ®expError)) {
astContext_.addCompiledRegExp(
regexp->_pattern, regexp->_flags, std::move(*compiled));
} else {
sm_.error(
regexp->getSourceRange(),
"Invalid regular expression: " + Twine(regexpError));
}
}
visitESTreeChildren(*this, regexp);
}
void SemanticValidator::validateCatchClause(const Node *catchClause) {
// The catch clause is optional, so bail early if it doesn't exist.
if (!catchClause) {
return;
}
auto *castedCatch = llvh::dyn_cast<ESTree::CatchClauseNode>(catchClause);
if (!castedCatch) {
return;
}
// Bail early if there is no identifier in the parameter of the catch.
if (!castedCatch->_param ||
!llvh::isa<ESTree::IdentifierNode>(castedCatch->_param)) {
return;
}
auto *idNode = cast<ESTree::IdentifierNode>(castedCatch->_param);
if (!isValidDeclarationName(idNode)) {
sm_.error(
idNode->getSourceRange(),
"cannot bind to " + idNode->_name->str() +
" in the catch clause in strict mode");
}
}
void SemanticValidator::visit(TryStatementNode *tryStatement) {
if (curFunction()->strictMode) {
validateCatchClause(tryStatement->_handler);
}
// The catch parameter cannot bind to 'eval' or 'arguments' in strict mode.
// A try statement with both catch and finally handlers is technically
// two nested try statements. Transform:
//
// try {
// tryBody;
// } catch {
// catchBody;
// } finally {
// finallyBody;
// }
//
// into
//
// try {
// try {
// tryBody;
// } catch {
// catchBody;
// }
// } finally {
// finallyBody;
// }
if (compile_ && tryStatement->_handler && tryStatement->_finalizer) {
auto *nestedTry = new (astContext_)
TryStatementNode(tryStatement->_block, tryStatement->_handler, nullptr);
nestedTry->copyLocationFrom(tryStatement);
nestedTry->setEndLoc(nestedTry->_handler->getEndLoc());
ESTree::NodeList stmtList;
stmtList.push_back(*nestedTry);
tryStatement->_block =
new (astContext_) BlockStatementNode(std::move(stmtList));
tryStatement->_block->copyLocationFrom(nestedTry);
tryStatement->_handler = nullptr;
}
visitESTreeNode(*this, tryStatement->_block, tryStatement);
if (!blockScopingEnabled()) {
visitESTreeNode(*this, tryStatement->_handler, tryStatement);
} else {
visitTryHandler(tryStatement);
}
visitESTreeNode(*this, tryStatement->_finalizer, tryStatement);
}
void SemanticValidator::visitTryHandler(TryStatementNode *tryStatement) {
if (auto *handler =
llvh::dyn_cast_or_null<CatchClauseNode>(tryStatement->_handler)) {
auto *param = llvh::dyn_cast_or_null<IdentifierNode>(handler->_param);
BlockContext blockScope(this, curFunction(), handler);
if (auto *block = llvh::dyn_cast<BlockStatementNode>(handler->_body)) {
for (auto &stmt : block->_body) {
visitESTreeNode(*this, &stmt, block);
}
} else {
visitESTreeNode(*this, tryStatement->_handler, tryStatement);
}
blockScope.ensureScopedNamesAreUnique(
BlockContext::IsFunctionBody::No, param);
// Delay adding the catch param until now to prevent Syntax Errors if the
// handler has a var that with the same ID as the catch param (as specified
// in ES2023 B.3.4).
validateDeclarationNames(
FunctionInfo::VarDecl::Kind::Let,
param,
curFunction()->varDecls,
curFunction()->scopedDecls);
}
}
void SemanticValidator::visit(BlockStatementNode *block) {
BlockContext blockScope(this, curFunction(), block);
visitESTreeChildren(*this, block);
blockScope.ensureScopedNamesAreUnique(BlockContext::IsFunctionBody::No);
}
void SemanticValidator::visit(DoWhileStatementNode *loop) {
loop->setLabelIndex(curFunction()->allocateLabel());
SaveAndRestore<LoopStatementNode *> saveLoop(curFunction()->activeLoop, loop);
SaveAndRestore<StatementNode *> saveSwitch(
curFunction()->activeSwitchOrLoop, loop);
visitESTreeChildren(*this, loop);
}
void SemanticValidator::visit(ForStatementNode *loop) {
loop->setLabelIndex(curFunction()->allocateLabel());
SaveAndRestore<LoopStatementNode *> saveLoop(curFunction()->activeLoop, loop);
SaveAndRestore<StatementNode *> saveSwitch(
curFunction()->activeSwitchOrLoop, loop);
visitESTreeChildren(*this, loop);
}
void SemanticValidator::visit(WhileStatementNode *loop) {
loop->setLabelIndex(curFunction()->allocateLabel());
SaveAndRestore<LoopStatementNode *> saveLoop(curFunction()->activeLoop, loop);
SaveAndRestore<StatementNode *> saveSwitch(
curFunction()->activeSwitchOrLoop, loop);
visitESTreeChildren(*this, loop);
}
void SemanticValidator::visit(SwitchStatementNode *switchStmt) {
switchStmt->setLabelIndex(curFunction()->allocateLabel());
BlockContext switchContext(this, curFunction(), switchStmt);
SaveAndRestore<StatementNode *> saveSwitch(
curFunction()->activeSwitchOrLoop, switchStmt);
visitESTreeChildren(*this, switchStmt);
switchContext.ensureScopedNamesAreUnique(BlockContext::IsFunctionBody::No);
}
void SemanticValidator::visit(BreakStatementNode *breakStmt) {
if (auto id = cast_or_null<IdentifierNode>(breakStmt->_label)) {
// A labeled break.
// Find the label in the label map.
auto labelIt = curFunction()->labelMap.find(id->_name);
if (labelIt != curFunction()->labelMap.end()) {
auto labelIndex = getLabelDecorationBase(labelIt->second.targetStatement)
->getLabelIndex();
breakStmt->setLabelIndex(labelIndex);
} else {
sm_.error(
id->getSourceRange(),
Twine("label '") + id->_name->str() + "' is not defined");
}
} else {
// Anonymous break.
if (curFunction()->activeSwitchOrLoop) {
auto labelIndex =
getLabelDecorationBase(curFunction()->activeSwitchOrLoop)
->getLabelIndex();
breakStmt->setLabelIndex(labelIndex);
} else {
sm_.error(
breakStmt->getSourceRange(), "'break' not within a loop or a switch");
}
}
visitESTreeChildren(*this, breakStmt);
}
void SemanticValidator::visit(ContinueStatementNode *continueStmt) {
if (auto id = cast_or_null<IdentifierNode>(continueStmt->_label)) {
// A labeled continue.
// Find the label in the label map.
auto labelIt = curFunction()->labelMap.find(id->_name);
if (labelIt != curFunction()->labelMap.end()) {
if (isa<LoopStatementNode>(labelIt->second.targetStatement)) {
auto labelIndex =
getLabelDecorationBase(labelIt->second.targetStatement)
->getLabelIndex();
continueStmt->setLabelIndex(labelIndex);
} else {
sm_.error(
id->getSourceRange(),
llvh::Twine("continue label '") + id->_name->str() +
"' is not a loop label");
sm_.note(
labelIt->second.declarationNode->getSourceRange(),
"label defined here");
}
} else {
sm_.error(
id->getSourceRange(),
Twine("label '") + id->_name->str() + "' is not defined");
}
} else {
// Anonymous continue.
if (curFunction()->activeLoop) {
auto labelIndex = curFunction()->activeLoop->getLabelIndex();
continueStmt->setLabelIndex(labelIndex);
} else {
sm_.error(continueStmt->getSourceRange(), "'continue' not within a loop");
}
}
visitESTreeChildren(*this, continueStmt);
}
void SemanticValidator::visit(ReturnStatementNode *returnStmt) {
if (curFunction()->isGlobalScope() &&
!astContext_.allowReturnOutsideFunction())
sm_.error(returnStmt->getSourceRange(), "'return' not in a function");
visitESTreeChildren(*this, returnStmt);
}
void SemanticValidator::visit(YieldExpressionNode *yieldExpr) {
if (curFunction()->isGlobalScope() ||
(curFunction()->node && !ESTree::isGenerator(curFunction()->node)))
sm_.error(
yieldExpr->getSourceRange(), "'yield' not in a generator function");
if (isFormalParams_) {
// For generators functions (the only time YieldExpression is parsed):
// It is a Syntax Error if UniqueFormalParameters Contains YieldExpression
// is true.
sm_.error(
yieldExpr->getSourceRange(),
"'yield' not allowed in a formal parameter");
}
visitESTreeChildren(*this, yieldExpr);
}
void SemanticValidator::visit(AwaitExpressionNode *awaitExpr) {
if (forbidAwaitExpression_)
sm_.error(awaitExpr->getSourceRange(), "'await' not in an async function");
visitESTreeChildren(*this, awaitExpr);
}
void SemanticValidator::visit(UnaryExpressionNode *unaryExpr) {
// Check for unqualified delete in strict mode.
if (unaryExpr->_operator == kw_.identDelete) {
if (curFunction()->strictMode &&
isa<IdentifierNode>(unaryExpr->_argument)) {
sm_.error(
unaryExpr->getSourceRange(),
"'delete' of a variable is not allowed in strict mode");
}
}
visitESTreeChildren(*this, unaryExpr);
}
void SemanticValidator::visit(ArrayPatternNode *AP) {
visitESTreeChildren(*this, AP);
}
void SemanticValidator::visit(SpreadElementNode *S, Node *parent) {
if (!isa<ESTree::ObjectExpressionNode>(parent) &&
!isa<ESTree::ArrayExpressionNode>(parent) &&
!isa<ESTree::CallExpressionNode>(parent) &&
!isa<ESTree::OptionalCallExpressionNode>(parent) &&
!isa<ESTree::NewExpressionNode>(parent))
sm_.error(S->getSourceRange(), "spread operator is not supported");
visitESTreeChildren(*this, S);
}
void SemanticValidator::visit(ClassExpressionNode *node) {
SaveAndRestore<bool> oldStrictMode{curFunction()->strictMode, true};
visitESTreeChildren(*this, node);
}
void SemanticValidator::visit(ClassDeclarationNode *node) {
SaveAndRestore<bool> oldStrictMode{curFunction()->strictMode, true};
visitESTreeChildren(*this, node);
}
void SemanticValidator::visit(PrivateNameNode *node) {
if (compile_)
sm_.error(node->getSourceRange(), "private properties are not supported");
visitESTreeChildren(*this, node);
}
void SemanticValidator::visit(ClassPrivatePropertyNode *node) {
if (compile_)
sm_.error(node->getSourceRange(), "private properties are not supported");
visitESTreeNode(*this, node->_key);
{
SaveAndRestore<bool> oldForbidAwait{forbidAwaitExpression_, true};
// ES14.0 15.7.1
// It is a Syntax Error if Initializer is present and ContainsArguments of
// Initializer is true.
SaveAndRestore<bool> oldForbidArguments{forbidArguments_, true};
visitESTreeNode(*this, node->_value);
}
}
void SemanticValidator::visit(ClassPropertyNode *node) {
visitESTreeNode(*this, node->_key);
{
SaveAndRestore<bool> oldForbidAwait{forbidAwaitExpression_, true};
// ES14.0 15.7.1
// It is a Syntax Error if Initializer is present and ContainsArguments of
// Initializer is true.
SaveAndRestore<bool> oldForbidArguments{forbidArguments_, true};
visitESTreeNode(*this, node->_value);
}
}
void SemanticValidator::visit(StaticBlockNode *node) {
if (compile_)
sm_.error(node->getSourceRange(), "class static blocks are not supported");
// ES14.0 15.7.1
// It is a Syntax Error if ClassStaticBlockStatementList Contains await is
// true.
llvh::SaveAndRestore<bool> oldForbidAwait{forbidAwaitExpression_, true};
visitESTreeChildren(*this, node);
}
void SemanticValidator::visit(ImportDeclarationNode *importDecl) {
// Like variable declarations, imported names must be hoisted.
if (!astContext_.getTransformCJSModules()) {
sm_.error(
importDecl->getSourceRange(),
"'import' statement requires module mode");
}
if (compile_ && !importDecl->_assertions.empty()) {
sm_.error(
importDecl->getSourceRange(), "import assertions are not supported");
}
curFunction()->semInfo->imports.push_back(importDecl);
visitESTreeChildren(*this, importDecl);
}
void SemanticValidator::visit(ImportDefaultSpecifierNode *importDecl) {
// import defaultProperty from 'file.js';
validateDeclarationNames(
FunctionInfo::VarDecl::Kind::Var,
importDecl->_local,
curFunction()->varDecls,
curFunction()->scopedDecls);
visitESTreeChildren(*this, importDecl);
}
void SemanticValidator::visit(ImportNamespaceSpecifierNode *importDecl) {
// import * as File from 'file.js';
validateDeclarationNames(
FunctionInfo::VarDecl::Kind::Var,
importDecl->_local,
curFunction()->varDecls,
curFunction()->scopedDecls);
visitESTreeChildren(*this, importDecl);
}
void SemanticValidator::visit(ImportSpecifierNode *importDecl) {
// import {x as y} as File from 'file.js';
// import {x} as File from 'file.js';
validateDeclarationNames(
FunctionInfo::VarDecl::Kind::Var,
importDecl->_local,
curFunction()->varDecls,
curFunction()->scopedDecls);
visitESTreeChildren(*this, importDecl);
}
void SemanticValidator::visit(ExportNamedDeclarationNode *exportDecl) {
if (!astContext_.getTransformCJSModules()) {
sm_.error(
exportDecl->getSourceRange(),
"'export' statement requires module mode");
}
visitESTreeChildren(*this, exportDecl);
}
void SemanticValidator::visit(ExportDefaultDeclarationNode *exportDecl) {
if (!astContext_.getTransformCJSModules() &&
!astContext_.getTransformCJSModules()) {
sm_.error(
exportDecl->getSourceRange(),
"'export' statement requires module mode");
}
if (auto *funcDecl =
dyn_cast<ESTree::FunctionDeclarationNode>(exportDecl->_declaration)) {
if (compile_ && !funcDecl->_id) {
// If the default function declaration has no name, then change it to a
// FunctionExpression node for cleaner IRGen.
auto *funcExpr = new (astContext_) ESTree::FunctionExpressionNode(
funcDecl->_id,
std::move(funcDecl->_params),
funcDecl->_body,
funcDecl->_typeParameters,
funcDecl->_returnType,
funcDecl->_predicate,
funcDecl->_generator,
/* async */ false);
funcExpr->strictness = funcDecl->strictness;
funcExpr->copyLocationFrom(funcDecl);
exportDecl->_declaration = funcExpr;
}
}
visitESTreeChildren(*this, exportDecl);
}
void SemanticValidator::visit(ExportAllDeclarationNode *exportDecl) {
if (!astContext_.getTransformCJSModules()) {
sm_.error(
exportDecl->getSourceRange(),
"'export' statement requires CommonJS module mode");
}
visitESTreeChildren(*this, exportDecl);
}
void SemanticValidator::visit(CoverEmptyArgsNode *CEA) {
sm_.error(CEA->getSourceRange(), "invalid empty parentheses '( )'");
}
void SemanticValidator::visit(CoverTrailingCommaNode *CTC) {
sm_.error(CTC->getSourceRange(), "expression expected after ','");
}
void SemanticValidator::visit(CoverInitializerNode *CI) {
sm_.error(CI->getStartLoc(), "':' expected in property initialization");
}
void SemanticValidator::visit(CoverRestElementNode *R) {
sm_.error(R->getSourceRange(), "'...' not allowed in this context");
}
#if HERMES_PARSE_FLOW
void SemanticValidator::visit(CoverTypedIdentifierNode *CTI) {
sm_.error(CTI->getSourceRange(), "typecast not allowed in this context");
}
#endif
void SemanticValidator::visitFunction(
FunctionLikeNode *node,
Node *id,
NodeList ¶ms,
Node *body) {
FunctionContext newFuncCtx{
this,
haveActiveContext() && curFunction()->strictMode,
node,
body,
haveActiveContext() ? curFunction()->sourceVisibility
: SourceVisibility::Default};
if (compile_ && ESTree::isAsync(node) && ESTree::isGenerator(node)) {
sm_.error(node->getSourceRange(), "async generators are unsupported");
}
// It is a Syntax Error if UniqueFormalParameters Contains YieldExpression
// is true.
// NOTE: isFormalParams_ is reset to false on encountering a new function,
// because the semantics for "x Contains y" always return `false` when "x" is
// a function definition.
llvh::SaveAndRestore<bool> oldIsFormalParamsFn{isFormalParams_, false};
Node *useStrictNode = nullptr;
// Note that body might me empty (for lazy functions) or an expression (for
// arrow functions).
if (auto *bodyNode = dyn_cast<ESTree::BlockStatementNode>(body)) {
if (bodyNode->isLazyFunctionBody) {
// If it is a lazy function body, then the directive nodes in the body are
// fabricated without location, so don't set useStrictNode.
scanDirectivePrologue(bodyNode->_body);
} else {
useStrictNode = scanDirectivePrologue(bodyNode->_body);
}
setDirectiveDerivedInfo(node);
}
if (id)
validateDeclarationNames(
FunctionInfo::VarDecl::Kind::Var, id, nullptr, nullptr);
#if HERMES_PARSE_FLOW
if (astContext_.getParseFlow() && !params.empty()) {
// Skip 'this' parameter annotation, and error if it's an arrow parameter,
// because arrow functions inherit 'this'.
if (auto *ident = dyn_cast<ESTree::IdentifierNode>(¶ms.front())) {
if (ident->_name == kw_.identThis) {
if (isa<ArrowFunctionExpressionNode>(node)) {
sm_.error(
ident->getSourceRange(), "'this' not allowed as parameter name");
}
if (compile_) {
// Delete the node because it cannot be compiled.
params.erase(params.begin());
}
}
}
}
#endif
for (auto ¶m : params) {
#if HERMES_PARSE_FLOW
if (isa<ComponentParameterNode>(param)) {
validateDeclarationNames(
FunctionInfo::VarDecl::Kind::Var,
dyn_cast<ComponentParameterNode>(¶m)->_local,
&newFuncCtx.semInfo->paramNames,
nullptr);
continue;
}
#endif
validateDeclarationNames(
FunctionInfo::VarDecl::Kind::Var,
¶m,
&newFuncCtx.semInfo->paramNames,
nullptr);
}
bool simpleParameterList = ESTree::hasSimpleParams(node);
if (!simpleParameterList && useStrictNode) {
sm_.error(
useStrictNode->getSourceRange(),
"'use strict' not allowed inside function with non-simple parameter list");
}
// Check repeated parameter names when they are supposed to be unique.
if (!simpleParameterList || curFunction()->strictMode ||
isa<ArrowFunctionExpressionNode>(node)) {
llvh::SmallSet<NodeLabel, 8> paramNameSet;
for (const auto &curIdNode : newFuncCtx.semInfo->paramNames) {
auto insert_result = paramNameSet.insert(curIdNode.identifier->_name);
if (insert_result.second == false) {
sm_.error(
curIdNode.identifier->getSourceRange(),
"cannot declare two parameters with the same name '" +
curIdNode.identifier->_name->str() + "'");
}
}
}
// 'await' forbidden outside async functions.
llvh::SaveAndRestore<bool> oldForbidAwait{
forbidAwaitExpression_, !ESTree::isAsync(node)};
// Forbidden-ness of 'arguments' passes through arrow functions because they
// use the same 'arguments'.
llvh::SaveAndRestore<bool> oldForbidArguments{
forbidArguments_,
llvh::isa<ESTree::ArrowFunctionExpressionNode>(node) ? forbidArguments_
: false};
visitParamsAndBody(node);
}
void SemanticValidator::visitParamsAndBody(FunctionLikeNode *node) {
switch (node->getKind()) {
case NodeKind::FunctionExpression: {
auto *fe = cast<ESTree::FunctionExpressionNode>(node);
visitESTreeNode(*this, fe->_id, fe);
for (auto ¶m : fe->_params) {
llvh::SaveAndRestore<bool> oldIsFormalParams{isFormalParams_, true};
visitESTreeNode(*this, ¶m, fe);
}
visitBody(fe->_body, fe);
break;
}
case NodeKind::ArrowFunctionExpression: {
auto *fe = cast<ESTree::ArrowFunctionExpressionNode>(node);
visitESTreeNode(*this, fe->_id, fe);
for (auto ¶m : fe->_params) {
llvh::SaveAndRestore<bool> oldIsFormalParams{isFormalParams_, true};
visitESTreeNode(*this, ¶m, fe);
}
visitBody(fe->_body, fe);
break;
}
case NodeKind::FunctionDeclaration: {
auto *fe = cast<ESTree::FunctionDeclarationNode>(node);
visitESTreeNode(*this, fe->_id, fe);
for (auto ¶m : fe->_params) {
llvh::SaveAndRestore<bool> oldIsFormalParams{isFormalParams_, true};
visitESTreeNode(*this, ¶m, fe);
}
visitBody(fe->_body, fe);
visitESTreeNode(*this, fe->_returnType, fe);
break;
}
#if HERMES_PARSE_FLOW
case NodeKind::ComponentDeclaration: {
auto *fe = cast<ESTree::ComponentDeclarationNode>(node);
visitESTreeNode(*this, fe->_id, fe);
for (auto ¶m : fe->_params) {
llvh::SaveAndRestore<bool> oldIsFormalParams{isFormalParams_, true};
visitESTreeNode(*this, ¶m, fe);
}
visitBody(fe->_body, fe);
visitESTreeNode(*this, fe->_rendersType, fe);
break;
}
case NodeKind::HookDeclaration: {
auto *fe = cast<ESTree::HookDeclarationNode>(node);
visitESTreeNode(*this, fe->_id, fe);
for (auto ¶m : fe->_params) {
llvh::SaveAndRestore<bool> oldIsFormalParams{isFormalParams_, true};
visitESTreeNode(*this, ¶m, fe);
}
visitBody(fe->_body, fe);
visitESTreeNode(*this, fe->_returnType, fe);
break;
}
#endif
default:
visitESTreeChildren(*this, node);
}
}
void SemanticValidator::visitBody(Node *body, FunctionLikeNode *func) {
if (auto *block = dyn_cast<ESTree::BlockStatementNode>(body)) {
// Avoid creating yet another block scope for function declarations like
//
// (function func() { ... })
// ^ BlockStatementNode
//