-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathParseStmt.cpp
2813 lines (2468 loc) · 98.3 KB
/
ParseStmt.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
//===--- ParseStmt.cpp - Swift Language Parser for Statements -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Statement Parsing and AST Building
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Attr.h"
#include "swift/AST/AvailabilitySpec.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/FileUnit.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Version.h"
#include "swift/Parse/IDEInspectionCallbacks.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
/// isStartOfStmt - Return true if the current token starts a statement.
///
bool Parser::isStartOfStmt(bool preferExpr) {
// This needs to be kept in sync with `Parser::parseStmt()`. If a new token
// kind is accepted here as start of statement, it should also be handled in
// `Parser::parseStmt()`.
switch (Tok.getKind()) {
default: return false;
case tok::kw_return:
case tok::kw_throw:
case tok::kw_defer:
case tok::kw_if:
case tok::kw_guard:
case tok::kw_while:
case tok::kw_do:
case tok::kw_for:
case tok::kw_break:
case tok::kw_continue:
case tok::kw_fallthrough:
case tok::kw_switch:
case tok::kw_case:
case tok::kw_default:
case tok::kw_yield:
case tok::kw_discard:
case tok::pound_assert:
case tok::pound_if:
case tok::pound_warning:
case tok::pound_error:
case tok::pound_sourceLocation:
return true;
case tok::kw_repeat:
// 'repeat' followed by anything other than a brace stmt
// is a pack expansion expression.
// FIXME: 'repeat' followed by '{' could be a pack expansion
// with a closure pattern.
return peekToken().is(tok::l_brace);
case tok::pound_line:
// #line at the start of a line is a directive, when within, it is an expr.
return Tok.isAtStartOfLine();
case tok::kw_try: {
// "try" cannot actually start any statements, but we parse it there for
// better recovery in cases like 'try return'.
// For 'if', 'switch', and 'do' we can parse as an expression.
if (peekToken().isAny(tok::kw_if, tok::kw_switch) ||
(peekToken().is(tok::kw_do) &&
Context.LangOpts.hasFeature(Feature::DoExpressions))) {
return false;
}
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::kw_try);
return isStartOfStmt(preferExpr);
}
case tok::identifier: {
// "identifier ':' for/while/do/switch" is a label on a loop/switch.
if (!peekToken().is(tok::colon)) {
// "yield", "discard", and "then" in the right context begins a statement.
if (isContextualYieldKeyword() || isContextualDiscardKeyword() ||
isContextualThenKeyword(preferExpr)) {
return true;
}
return false;
}
// To disambiguate other cases of "identifier :", which might be part of a
// question colon expression or something else, we look ahead to the second
// token.
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::identifier);
consumeToken(tok::colon);
// We treating IDENTIFIER: { as start of statement to provide missed 'do'
// diagnostics. This case will be handled in parseStmt().
if (Tok.is(tok::l_brace)) {
return true;
}
// For better recovery, we just accept a label on any statement. We reject
// putting a label on something inappropriate in parseStmt().
return isStartOfStmt(preferExpr);
}
case tok::at_sign: {
// Might be a statement or case attribute. The only one of these we have
// right now is `@unknown default`, so hardcode a check for an attribute
// without any parens.
if (!peekToken().is(tok::identifier))
return false;
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::at_sign);
consumeToken(tok::identifier);
return isStartOfStmt(preferExpr);
}
}
}
ParserStatus Parser::parseExprOrStmt(ASTNode &Result) {
if (Tok.is(tok::semi)) {
diagnose(Tok, diag::illegal_semi_stmt)
.fixItRemove(SourceRange(Tok.getLoc()));
consumeToken();
return makeParserError();
}
if (Tok.is(tok::pound) && Tok.isAtStartOfLine() &&
peekToken().is(tok::code_complete)) {
consumeToken();
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeAfterPoundDirective();
}
consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
}
if (isStartOfStmt(/*preferExpr*/ false)) {
ParserResult<Stmt> Res = parseStmt();
if (Res.isNonNull()) {
auto *S = Res.get();
// Special case: An 'if' or 'switch' statement followed by an 'as' must
// be an if/switch expression in a coercion.
// We could also achieve this by more eagerly attempting to parse an 'if'
// or 'switch' as an expression when in statement position, but that
// could result in less useful recovery behavior.
if ((isa<IfStmt>(S) || isa<SwitchStmt>(S) ||
((isa<DoStmt>(S) || isa<DoCatchStmt>(S)) &&
Context.LangOpts.hasFeature(Feature::DoExpressions))) &&
Tok.is(tok::kw_as)) {
auto *SVE = SingleValueStmtExpr::createWithWrappedBranches(
Context, S, CurDeclContext, /*mustBeExpr*/ true);
auto As = parseExprAs();
if (As.isParseErrorOrHasCompletion())
return As;
Result = SequenceExpr::create(Context, {SVE, As.get(), As.get()});
} else {
Result = S;
}
}
return Res;
}
// Note that we're parsing a statement.
StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(),
StructureMarkerKind::Statement);
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->setExprBeginning(getParserPosition());
}
if (Tok.is(tok::code_complete)) {
auto *CCE = new (Context) CodeCompletionExpr(Tok.getLoc());
Result = CCE;
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeStmtOrExpr(CCE);
}
consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
}
ParserResult<Expr> ResultExpr = parseExpr(diag::expected_expr);
if (ResultExpr.isNonNull()) {
Result = ResultExpr.get();
} else if (!ResultExpr.hasCodeCompletion()) {
// If we've consumed any tokens at all, build an error expression
// covering the consumed range.
SourceLoc startLoc = StructureMarkers.back().Loc;
if (startLoc != Tok.getLoc()) {
Result = new (Context) ErrorExpr(SourceRange(startLoc, PreviousLoc));
}
}
return ResultExpr;
}
/// Returns whether the parser's current position is the start of a switch case,
/// given that we're in the middle of a switch already.
static bool isAtStartOfSwitchCase(Parser &parser,
bool needsToBacktrack = true) {
std::optional<Parser::BacktrackingScope> backtrack;
// Check for and consume attributes. The only valid attribute is `@unknown`
// but that's a semantic restriction.
while (parser.Tok.is(tok::at_sign)) {
if (!parser.peekToken().is(tok::identifier))
return false;
if (needsToBacktrack && !backtrack)
backtrack.emplace(parser);
parser.consumeToken(tok::at_sign);
parser.consumeToken(tok::identifier);
if (parser.Tok.is(tok::l_paren))
parser.skipSingle();
}
return parser.Tok.isAny(tok::kw_case, tok::kw_default);
}
bool Parser::isTerminatorForBraceItemListKind(BraceItemListKind Kind,
ArrayRef<ASTNode> ParsedDecls) {
switch (Kind) {
case BraceItemListKind::Brace:
case BraceItemListKind::TopLevelCode:
case BraceItemListKind::TopLevelLibrary:
case BraceItemListKind::MacroExpansion:
return false;
case BraceItemListKind::Case: {
if (Tok.is(tok::pound_if)) {
// Backtracking scopes are expensive, so avoid setting one up if possible.
Parser::BacktrackingScope Backtrack(*this);
// '#if' here could be to guard 'case:' or statements in cases.
// If the next non-directive line starts with 'case' or 'default', it is
// for 'case's.
do {
consumeToken();
// just find the end of the line
skipUntilTokenOrEndOfLine(tok::NUM_TOKENS);
} while (Tok.isAny(tok::pound_if, tok::pound_elseif, tok::pound_else));
return isAtStartOfSwitchCase(*this, /*needsToBacktrack*/false);
}
return isAtStartOfSwitchCase(*this);
}
case BraceItemListKind::ActiveConditionalBlock:
case BraceItemListKind::InactiveConditionalBlock:
return Tok.isNot(tok::pound_else) && Tok.isNot(tok::pound_endif) &&
Tok.isNot(tok::pound_elseif);
}
llvm_unreachable("Unhandled BraceItemListKind in switch.");
}
void Parser::consumeTopLevelDecl(ParserPosition BeginParserPosition,
TopLevelCodeDecl *TLCD) {
SourceLoc EndLoc = PreviousLoc;
backtrackToPosition(BeginParserPosition);
SourceLoc BeginLoc = Tok.getLoc();
State->setIDEInspectionDelayedDeclState(
SourceMgr, L->getBufferID(),
IDEInspectionDelayedDeclKind::TopLevelCodeDecl, TLCD, {BeginLoc, EndLoc},
BeginParserPosition.PreviousLoc);
// Skip the rest of the file to prevent the parser from constructing the AST
// for it. Forward references are not allowed at the top level.
while (!Tok.is(tok::eof))
consumeToken();
}
/// brace-item:
/// decl
/// expr
/// stmt
/// stmt:
/// ';'
/// stmt-assign
/// stmt-if
/// stmt-guard
/// stmt-for-c-style
/// stmt-for-each
/// stmt-switch
/// stmt-control-transfer
/// stmt-control-transfer:
/// stmt-return
/// stmt-break
/// stmt-continue
/// stmt-fallthrough
/// stmt-assign:
/// expr '=' expr
ParserStatus Parser::parseBraceItems(SmallVectorImpl<ASTNode> &Entries,
BraceItemListKind Kind,
BraceItemListKind ConditionalBlockKind,
bool &IsFollowingGuard) {
bool IsTopLevel = (Kind == BraceItemListKind::TopLevelCode) ||
(Kind == BraceItemListKind::TopLevelLibrary ||
(Kind == BraceItemListKind::MacroExpansion &&
isa<FileUnit>(CurDeclContext)));
bool isActiveConditionalBlock =
ConditionalBlockKind == BraceItemListKind::ActiveConditionalBlock;
bool isConditionalBlock = isActiveConditionalBlock ||
ConditionalBlockKind == BraceItemListKind::InactiveConditionalBlock;
ParserStatus BraceItemsStatus;
bool PreviousHadSemi = true;
while ((IsTopLevel || Tok.isNot(tok::r_brace)) &&
Tok.isNot(tok::pound_endif) &&
Tok.isNot(tok::pound_elseif) &&
Tok.isNot(tok::pound_else) &&
Tok.isNot(tok::eof) &&
!isStartOfSILDecl() &&
(isConditionalBlock ||
!isTerminatorForBraceItemListKind(Kind, Entries))) {
if (Tok.is(tok::r_brace)) {
assert(IsTopLevel);
diagnose(Tok, diag::extra_rbrace)
.fixItRemove(Tok.getLoc());
consumeToken();
continue;
}
// Eat invalid tokens instead of allowing them to produce downstream errors.
if (Tok.is(tok::unknown)) {
if (startsWithMultilineStringDelimiter(Tok)) {
// This was due to unterminated multi-line string.
IsInputIncomplete = true;
}
consumeToken();
continue;
}
bool NeedParseErrorRecovery = false;
ASTNode Result;
// If the previous statement didn't have a semicolon and this new
// statement doesn't start a line, complain.
const bool IsAtStartOfLineOrPreviousHadSemi =
PreviousHadSemi || Tok.isAtStartOfLine();
if (!IsAtStartOfLineOrPreviousHadSemi) {
SourceLoc EndOfPreviousLoc = getEndOfPreviousLoc();
diagnose(EndOfPreviousLoc, diag::statement_same_line_without_semi)
.fixItInsert(EndOfPreviousLoc, ";");
// FIXME: Add semicolon to the AST?
}
ParserPosition BeginParserPosition;
if (isIDEInspectionFirstPass())
BeginParserPosition = getParserPosition();
// Parse the decl, stmt, or expression.
PreviousHadSemi = false;
if (Tok.is(tok::pound_if) && !isStartOfSwiftDecl()) {
SmallVector<ASTNode, 16> activeElements;
auto IfConfigResult = parseIfConfig(
IfConfigContext::BraceItems,
[&](bool IsActive) {
SmallVector<ASTNode, 16> elements;
parseBraceItems(elements, Kind,
IsActive
? BraceItemListKind::ActiveConditionalBlock
: BraceItemListKind::InactiveConditionalBlock,
IsFollowingGuard);
if (IsActive)
activeElements.append(elements);
});
if (IfConfigResult.hasCodeCompletion() && isIDEInspectionFirstPass()) {
consumeDecl(BeginParserPosition, IsTopLevel);
return IfConfigResult;
}
BraceItemsStatus |= IfConfigResult;
if (IfConfigResult.isError()) {
NeedParseErrorRecovery = true;
continue;
}
Entries.append(activeElements);
} else if (Tok.is(tok::pound_line)) {
ParserStatus Status = parseLineDirective(true);
BraceItemsStatus |= Status;
NeedParseErrorRecovery = Status.isErrorOrHasCompletion();
} else if (Tok.is(tok::pound_sourceLocation)) {
ParserStatus Status = parseLineDirective(false);
BraceItemsStatus |= Status;
NeedParseErrorRecovery = Status.isErrorOrHasCompletion();
} else if (isStartOfSwiftDecl()) {
SmallVector<Decl*, 8> TmpDecls;
ParserStatus DeclResult =
parseDecl(IsAtStartOfLineOrPreviousHadSemi,
/*IfConfigsAreDeclAttrs=*/true, [&](Decl *D) {
TmpDecls.push_back(D);
// Any function after a 'guard' statement is marked as
// possibly having local captures. This allows SILGen
// to correctly determine its capture list, since
// otherwise it would be skipped because it is not
// defined inside a local context.
if (IsFollowingGuard)
if (auto *FD = dyn_cast<FuncDecl>(D))
FD->setHasTopLevelLocalContextCaptures();
});
BraceItemsStatus |= DeclResult;
if (DeclResult.isErrorOrHasCompletion()) {
NeedParseErrorRecovery = true;
if (DeclResult.hasCodeCompletion() && IsTopLevel &&
isIDEInspectionFirstPass()) {
consumeDecl(BeginParserPosition, IsTopLevel);
return DeclResult;
}
}
Entries.append(TmpDecls.begin(), TmpDecls.end());
// HACK: If any declarations were parsed, make the last one the "result".
// We should know whether this was in an #if or not.
if (!TmpDecls.empty()) {
Result = TmpDecls.back();
}
} else if (IsTopLevel) {
// If this is a statement or expression at the top level of the module,
// Parse it as a child of a TopLevelCodeDecl.
auto *TLCD = new (Context) TopLevelCodeDecl(CurDeclContext);
ContextChange CC(*this, TLCD);
SourceLoc StartLoc = Tok.getLoc();
// Expressions can't begin with a closure literal at statement position.
// This prevents potential ambiguities with trailing closure syntax.
if (Tok.is(tok::l_brace)) {
diagnose(Tok, diag::statement_begins_with_closure);
}
ParserStatus Status = parseExprOrStmt(Result);
BraceItemsStatus |= Status;
if (Status.hasCodeCompletion() && isIDEInspectionFirstPass()) {
consumeTopLevelDecl(BeginParserPosition, TLCD);
auto Brace = BraceStmt::create(Context, StartLoc, {}, PreviousLoc);
TLCD->setBody(Brace);
Entries.push_back(TLCD);
return Status;
}
if (Status.isErrorOrHasCompletion())
NeedParseErrorRecovery = true;
else if (!allowTopLevelCode()) {
diagnose(StartLoc,
Result.is<Stmt*>() ? diag::illegal_top_level_stmt
: diag::illegal_top_level_expr);
}
if (!Result.isNull()) {
// NOTE: this is a 'virtual' brace statement which does not have
// explicit '{' or '}', so the start and end locations should be
// the same as those of the result node, plus any junk consumed
// afterwards
auto Brace = BraceStmt::create(Context, Result.getStartLoc(),
Result, PreviousLoc, /*Implicit=*/true);
TLCD->setBody(Brace);
Entries.push_back(TLCD);
// A top-level 'guard' statement can introduce local bindings, so we
// must mark all functions following one. This makes them behave
// as if they were in local context for the purposes of capture
// emission in SILGen.
if (auto *stmt = Result.dyn_cast<Stmt *>())
if (isa<GuardStmt>(stmt))
IsFollowingGuard = true;
}
} else {
ParserStatus ExprOrStmtStatus = parseExprOrStmt(Result);
BraceItemsStatus |= ExprOrStmtStatus;
if (ExprOrStmtStatus.isError())
NeedParseErrorRecovery = true;
if (!Result.isNull())
Entries.push_back(Result);
}
if (!NeedParseErrorRecovery && Tok.is(tok::semi)) {
PreviousHadSemi = true;
if (auto *E = Result.dyn_cast<Expr*>())
E->TrailingSemiLoc = consumeToken(tok::semi);
else if (auto *S = Result.dyn_cast<Stmt*>())
S->TrailingSemiLoc = consumeToken(tok::semi);
else if (auto *D = Result.dyn_cast<Decl*>())
D->TrailingSemiLoc = consumeToken(tok::semi);
else
assert(!Result && "Unsupported AST node");
}
if (NeedParseErrorRecovery) {
// If we had a parse error, skip to the start of the next stmt or decl.
//
// It would be ideal to stop at the start of the next expression (e.g.
// "X = 4"), but distinguishing the start of an expression from the middle
// of one is "hard".
skipUntilDeclStmtRBrace();
// If we have to recover, pretend that we had a semicolon; it's less
// noisy that way.
PreviousHadSemi = true;
}
}
return BraceItemsStatus;
}
/// Recover from a 'case' or 'default' outside of a 'switch' by consuming up to
/// the next ':' or '}'.
static ParserResult<Stmt> recoverFromInvalidCase(Parser &P) {
assert(P.Tok.is(tok::kw_case) || P.Tok.is(tok::kw_default)
&& "not case or default?!");
P.diagnose(P.Tok, diag::case_outside_of_switch, P.Tok.getText());
P.skipUntil(tok::colon, tok::r_brace);
// FIXME: Return an ErrorStmt?
return nullptr;
}
/// parseStmt
ParserResult<Stmt> Parser::parseStmt() {
AssertParserMadeProgressBeforeLeavingScopeRAII apmp(*this);
// If this is a label on a loop/switch statement, consume it and pass it into
// parsing logic below.
LabeledStmtInfo LabelInfo;
if (Tok.is(tok::identifier) && peekToken().is(tok::colon)) {
LabelInfo.Loc = consumeIdentifier(LabelInfo.Name,
/*diagnoseDollarPrefix=*/true);
consumeToken(tok::colon);
}
// Note that we're parsing a statement.
StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(),
StructureMarkerKind::Statement);
SourceLoc tryLoc;
(void)consumeIf(tok::kw_try, tryLoc);
// Claim contextual statement keywords now that we've committed
// to parsing a statement.
if (isContextualYieldKeyword()) {
Tok.setKind(tok::kw_yield);
} else if (isContextualDiscardKeyword()) {
Tok.setKind(tok::kw_discard);
}
if (isContextualThenKeyword(/*preferExpr*/ false))
Tok.setKind(tok::kw_then);
// This needs to handle everything that `Parser::isStartOfStmt()` accepts as
// start of statement.
switch (Tok.getKind()) {
case tok::pound_line:
case tok::pound_sourceLocation:
case tok::pound_if:
case tok::pound_error:
case tok::pound_warning:
assert((LabelInfo || tryLoc.isValid()) &&
"unlabeled directives should be handled earlier");
// Bailout, and let parseBraceItems() parse them.
LLVM_FALLTHROUGH;
default:
diagnose(Tok, tryLoc.isValid() ? diag::expected_expr : diag::expected_stmt);
if (Tok.is(tok::at_sign)) {
// Recover from erroneously placed attribute.
consumeToken(tok::at_sign);
consumeIf(tok::identifier);
}
return nullptr;
case tok::kw_return:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtReturn(tryLoc);
case tok::kw_yield:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtYield(tryLoc);
case tok::kw_then:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtThen(tryLoc);
case tok::kw_throw:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtThrow(tryLoc);
case tok::kw_defer:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtDefer();
case tok::kw_if:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtIf(LabelInfo);
case tok::kw_guard:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtGuard();
case tok::kw_while:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtWhile(LabelInfo);
case tok::kw_repeat:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtRepeat(LabelInfo);
case tok::kw_do:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtDo(LabelInfo);
case tok::kw_for:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtForEach(LabelInfo);
case tok::kw_discard:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtDiscard();
case tok::kw_switch:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtSwitch(LabelInfo);
/// 'case' and 'default' are only valid at the top level of a switch.
case tok::kw_case:
case tok::kw_default:
return recoverFromInvalidCase(*this);
case tok::kw_break:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtBreak();
case tok::kw_continue:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtContinue();
case tok::kw_fallthrough: {
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
auto loc = consumeToken(tok::kw_fallthrough);
return makeParserResult(FallthroughStmt::createParsed(loc, CurDeclContext));
}
case tok::pound_assert:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtPoundAssert();
case tok::l_brace:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
SourceLoc colonLoc = Tok.getLoc();
diagnose(colonLoc, diag::labeled_block_needs_do)
.fixItInsert(colonLoc, "do ");
return parseStmtDo(LabelInfo, /*shouldSkipDoTokenConsume*/ true);
}
}
/// parseBraceItemList - A brace enclosed expression/statement/decl list. For
/// example { 1; 4+5; } or { 1; 2 }. Always occurs as part of some other stmt
/// or decl.
///
/// brace-item-list:
/// '{' brace-item* '}'
///
ParserResult<BraceStmt> Parser::parseBraceItemList(Diag<> ID) {
if (Tok.isNot(tok::l_brace)) {
diagnose(Tok, ID);
// Attempt to recover by looking for a left brace on the same line
if (!skipUntilTokenOrEndOfLine(tok::l_brace, tok::r_brace) ||
!Tok.is(tok::l_brace))
return nullptr;
}
SourceLoc LBLoc = consumeToken(tok::l_brace);
SmallVector<ASTNode, 16> Entries;
SourceLoc RBLoc;
ParserStatus Status = parseBraceItems(Entries, BraceItemListKind::Brace,
BraceItemListKind::Brace);
if (!parseMatchingToken(tok::r_brace, RBLoc,
diag::expected_rbrace_in_brace_stmt, LBLoc)) {
// We recovered do don't propagate any error status (but still preserve
// HasCodeCompletion).
Status.clearIsError();
}
return makeParserResult(Status,
BraceStmt::create(Context, LBLoc, Entries, RBLoc));
}
static ParserStatus parseOptionalControlTransferTarget(Parser &P,
Identifier &Target,
SourceLoc &TargetLoc,
StmtKind Kind) {
// If we have an identifier after 'break' or 'continue', which is not the
// start of another stmt or decl, we assume it is the label to break to,
// unless there is a line break. There is ambiguity with expressions (e.g.
// "break x+y") but since the expression after the them is dead, we don't feel
// bad eagerly parsing this.
if (!P.Tok.isAtStartOfLine()) {
if (P.Tok.is(tok::identifier) && !P.isStartOfStmt(/*preferExpr*/ true) &&
!P.isStartOfSwiftDecl()) {
TargetLoc = P.consumeIdentifier(Target, /*diagnoseDollarPrefix=*/false);
return makeParserSuccess();
} else if (P.Tok.is(tok::code_complete)) {
if (P.CodeCompletionCallbacks)
P.CodeCompletionCallbacks->completeStmtLabel(Kind);
TargetLoc = P.consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
}
}
return makeParserSuccess();
}
/// parseStmtBreak
///
/// stmt-break:
/// 'break' identifier?
///
ParserResult<Stmt> Parser::parseStmtBreak() {
SourceLoc Loc = consumeToken(tok::kw_break);
SourceLoc TargetLoc;
Identifier Target;
ParserStatus Status;
Status |= parseOptionalControlTransferTarget(*this, Target, TargetLoc,
StmtKind::Break);
auto *BS = new (Context) BreakStmt(Loc, Target, TargetLoc, CurDeclContext);
return makeParserResult(Status, BS);
}
/// parseStmtContinue
///
/// stmt-continue:
/// 'continue' identifier?
///
ParserResult<Stmt> Parser::parseStmtContinue() {
SourceLoc Loc = consumeToken(tok::kw_continue);
SourceLoc TargetLoc;
Identifier Target;
ParserStatus Status;
Status |= parseOptionalControlTransferTarget(*this, Target, TargetLoc,
StmtKind::Continue);
auto *CS = new (Context) ContinueStmt(Loc, Target, TargetLoc, CurDeclContext);
return makeParserResult(Status, CS);
}
/// parseStmtReturn
///
/// stmt-return:
/// 'return' expr?
///
ParserResult<Stmt> Parser::parseStmtReturn(SourceLoc tryLoc) {
SourceLoc ReturnLoc = consumeToken(tok::kw_return);
if (Tok.is(tok::code_complete)) {
auto CCE = new (Context) CodeCompletionExpr(Tok.getLoc());
auto Result =
makeParserResult(ReturnStmt::createParsed(Context, ReturnLoc, CCE));
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeReturnStmt(CCE);
}
Result.setHasCodeCompletionAndIsError();
consumeToken();
return Result;
}
auto isStartOfReturnExpr = [&]() {
if (Tok.isAny(tok::r_brace, tok::semi, tok::eof, tok::pound_if,
tok::pound_error, tok::pound_warning, tok::pound_endif,
tok::pound_else, tok::pound_elseif)) {
return false;
}
// Allowed for if/switch/do expressions.
if (Tok.isAny(tok::kw_if, tok::kw_switch) ||
(Tok.is(tok::kw_do) &&
Context.LangOpts.hasFeature(Feature::DoExpressions))) {
return true;
}
if (isStartOfStmt(/*preferExpr*/ true) || isStartOfSwiftDecl())
return false;
return true;
};
// Handle the ambiguity between consuming the expression and allowing the
// enclosing stmt-brace to get it by eagerly eating it unless the return is
// followed by a '}', ';', statement or decl start keyword sequence.
if (isStartOfReturnExpr()) {
SourceLoc ExprLoc = Tok.getLoc();
// Issue a warning when the returned expression is on a different line than
// the return keyword, but both have the same indentation.
if (SourceMgr.getLineAndColumnInBuffer(ReturnLoc).second ==
SourceMgr.getLineAndColumnInBuffer(ExprLoc).second) {
diagnose(ExprLoc, diag::unindented_code_after_return);
diagnose(ExprLoc, diag::indent_expression_to_silence);
}
ParserResult<Expr> Result = parseExpr(diag::expected_expr_return);
if (Result.isNull()) {
// Create an ErrorExpr to tell the type checker that this return
// statement had an expression argument in the source. This suppresses
// the error about missing return value in a non-void function.
Result = makeParserErrorResult(new (Context) ErrorExpr(ExprLoc));
}
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*return=*/0)
.fixItInsert(ExprLoc, "try ")
.fixItRemoveChars(tryLoc, ReturnLoc);
// Note: We can't use tryLoc here because that's outside the ReturnStmt's
// source range.
if (Result.isNonNull() && !isa<ErrorExpr>(Result.get()))
Result = makeParserResult(new (Context) TryExpr(ExprLoc, Result.get()));
}
return makeParserResult(
Result,
ReturnStmt::createParsed(Context, ReturnLoc, Result.getPtrOrNull()));
}
if (tryLoc.isValid())
diagnose(tryLoc, diag::try_on_stmt, "return");
return makeParserResult(
ReturnStmt::createParsed(Context, ReturnLoc, nullptr));
}
/// parseStmtYield
///
/// stmt-yield:
/// 'yield' expr
/// 'yield' '(' expr-list ')'
///
/// Note that a parenthesis always starts the second (list) grammar.
ParserResult<Stmt> Parser::parseStmtYield(SourceLoc tryLoc) {
SourceLoc yieldLoc = consumeToken(tok::kw_yield);
if (Tok.is(tok::code_complete)) {
auto cce = new (Context) CodeCompletionExpr(Tok.getLoc());
auto result = makeParserResult(
YieldStmt::create(Context, yieldLoc, SourceLoc(), cce, SourceLoc()));
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeYieldStmt(cce, /*index=*/std::nullopt);
}
result.setHasCodeCompletionAndIsError();
consumeToken();
return result;
}
ParserStatus status;
SourceLoc lpLoc, rpLoc;
SmallVector<Expr*, 4> yields;
if (Tok.is(tok::l_paren)) {
// If there was a 'try' on the yield, and there are multiple
// yielded values, suggest just removing the try instead of
// suggesting adding it to every yielded value.
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*yield=*/2)
.fixItRemoveChars(tryLoc, yieldLoc);
}
SmallVector<ExprListElt, 4> yieldElts;
status = parseExprList(tok::l_paren, tok::r_paren, /*isArgumentList*/ false,
lpLoc, yieldElts, rpLoc);
for (auto &elt : yieldElts) {
// We don't accept labels in a list of yields.
if (elt.LabelLoc.isValid()) {
diagnose(elt.LabelLoc, diag::unexpected_label_yield)
.fixItRemoveChars(elt.LabelLoc, elt.E->getStartLoc());
}
yields.push_back(elt.E);
}
} else {
SourceLoc beginLoc = Tok.getLoc();
// There's a single yielded value, so suggest moving 'try' before it.
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*yield=*/2)
.fixItInsert(beginLoc, "try ")
.fixItRemoveChars(tryLoc, yieldLoc);
}
auto expr = parseExpr(diag::expected_expr_yield);
if (expr.hasCodeCompletion() && expr.isNonNull()) {
status |= expr;
yields.push_back(expr.get());
} else if (expr.isParseErrorOrHasCompletion()) {
auto endLoc = (Tok.getLoc() == beginLoc ? beginLoc : PreviousLoc);
yields.push_back(
new (Context) ErrorExpr(SourceRange(beginLoc, endLoc)));
} else {
yields.push_back(expr.get());
}
}
return makeParserResult(
status, YieldStmt::create(Context, yieldLoc, lpLoc, yields, rpLoc));
}
bool Parser::isContextualThenKeyword(bool preferExpr) {
if (!Context.LangOpts.hasFeature(Feature::ThenStatements))
return false;
if (!Tok.isContextualKeyword("then"))
return false;
// If we want to prefer an expr, and aren't at the start of a newline, then
// don't parse a ThenStmt.
if (preferExpr && !Tok.isAtStartOfLine())
return false;
// 'then' immediately followed by '('/'[' is a function/subscript call. If
// immediately followed by '.', it's a member access.
if (peekToken().isAny(tok::l_paren, tok::l_square, tok::period)) {
auto tokEndLoc = Lexer::getLocForEndOfToken(SourceMgr, Tok.getLoc());
return peekToken().getLoc() != tokEndLoc;
}
// 'then' followed by '{' is a trailing closure on a function call.
if (peekToken().is(tok::l_brace))
return false;
// If we have 'then' followed by an infix or postfix operator, we know this
// must be an expression.
if (peekToken().isBinaryOperatorLike() || peekToken().isPostfixOperatorLike())
return false;
// These act like binary operators.
if (peekToken().isAny(tok::kw_is, tok::kw_as))
return false;
return true;
}
/// parseStmtThen
///
/// stmt-then:
/// 'then' expr
///
ParserResult<Stmt> Parser::parseStmtThen(SourceLoc tryLoc) {
SourceLoc thenLoc = consumeToken(tok::kw_then);
if (Tok.is(tok::code_complete)) {
auto ccLoc = consumeToken();
auto *CCE = new (Context) CodeCompletionExpr(ccLoc);
if (CodeCompletionCallbacks)
CodeCompletionCallbacks->completeThenStmt(CCE);
return makeParserCodeCompletionResult(
ThenStmt::createParsed(Context, thenLoc, CCE));
}
auto exprLoc = Tok.getLoc();
// Issue a warning when the expression is on a different line than
// the 'then' keyword, but both have the same indentation.
if (SourceMgr.getLineAndColumnInBuffer(thenLoc).second ==
SourceMgr.getLineAndColumnInBuffer(exprLoc).second) {
diagnose(exprLoc, diag::unindented_code_after_then);
diagnose(exprLoc, diag::indent_expression_to_silence);
}
ParserResult<Expr> result = parseExpr(diag::expected_expr_after_then);
bool hasCodeCompletion = result.hasCodeCompletion();
// If we couldn't parse an expr, fill it the gap with an ErrorExpr, as
// ThenStmt expects an expression node.
if (result.isNull())
result = makeParserErrorResult(new (Context) ErrorExpr(exprLoc));
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*then=*/3)
.fixItInsert(exprLoc, "try ")
.fixItRemoveChars(tryLoc, thenLoc);
// Note: We can't use tryLoc here because that's outside the ThenStmt's
// source range.
if (!isa<ErrorExpr>(result.get()))
result = makeParserResult(new (Context) TryExpr(exprLoc, result.get()));
}
if (hasCodeCompletion)
result.setHasCodeCompletionAndIsError();
return makeParserResult(
result, ThenStmt::createParsed(Context, thenLoc, result.get()));
}
/// parseStmtThrow
///