-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
ParseStmt.cpp
2155 lines (1889 loc) · 76.4 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/Parse/Parser.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Version.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/CodeCompletionCallbacks.h"
#include "swift/Subsystems.h"
#include "swift/Syntax/TokenSyntax.h"
#include "swift/Syntax/SyntaxParsingContext.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace swift::syntax;
/// isStartOfStmt - Return true if the current token starts a statement.
///
bool Parser::isStartOfStmt() {
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_repeat:
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::pound_if:
case tok::pound_sourceLocation:
return true;
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.
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::kw_try);
return isStartOfStmt();
}
case tok::identifier: {
// "identifier ':' for/while/do/switch" is a label on a loop/switch.
if (!peekToken().is(tok::colon)) 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);
// For better recovery, we just accept a label on any statement. We reject
// putting a label on something inappropriate in parseStmt().
return isStartOfStmt();
}
}
}
ParserStatus Parser::parseExprOrStmt(ASTNode &Result) {
if (Tok.is(tok::semi)) {
diagnose(Tok, diag::illegal_semi_stmt)
.fixItRemove(SourceRange(Tok.getLoc()));
consumeToken();
return makeParserError();
}
if (isStartOfStmt()) {
ParserResult<Stmt> Res = parseStmt();
if (Res.isNonNull())
Result = Res.get();
return Res;
}
// Note that we're parsing a statement.
StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(),
StructureMarkerKind::Statement);
if (CodeCompletion)
CodeCompletion->setExprBeginning(getParserPosition());
if (Tok.is(tok::code_complete)) {
if (CodeCompletion)
CodeCompletion->completeStmtOrExpr();
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));
}
}
if (ResultExpr.hasCodeCompletion() && CodeCompletion) {
CodeCompletion->completeExpr();
}
return ResultExpr;
}
bool Parser::isTerminatorForBraceItemListKind(BraceItemListKind Kind,
ArrayRef<ASTNode> ParsedDecls) {
switch (Kind) {
case BraceItemListKind::Brace:
return false;
case BraceItemListKind::Case:
if (Tok.is(tok::pound_if)) {
// '#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.
Parser::BacktrackingScope Backtrack(*this);
do {
consumeToken();
while (!Tok.isAtStartOfLine() && Tok.isNot(tok::eof))
skipSingle();
} while (Tok.isAny(tok::pound_if, tok::pound_elseif, tok::pound_else));
return Tok.isAny(tok::kw_case, tok::kw_default);
}
return Tok.isAny(tok::kw_case, tok::kw_default);
case BraceItemListKind::TopLevelCode:
// When parsing the top level executable code for a module, if we parsed
// some executable code, then we're done. We want to process (name bind,
// type check, etc) decls one at a time to make sure that there are not
// forward type references, etc. There is an outer loop around the parser
// that will reinvoke the parser at the top level on each statement until
// EOF. In contrast, it is ok to have forward references between classes,
// functions, etc.
for (auto I : ParsedDecls) {
if (isa<TopLevelCodeDecl>(I.get<Decl*>()))
// Only bail out if the next token is at the start of a line. If we
// don't, then we may accidentally allow things like "a = 1 b = 4".
// FIXME: This is really dubious. This will reject some things, but
// allow other things we don't want.
if (Tok.isAtStartOfLine())
return true;
}
return false;
case BraceItemListKind::TopLevelLibrary:
return false;
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) {
backtrackToPosition(BeginParserPosition);
SourceLoc BeginLoc = Tok.getLoc();
// Consume tokens up to code completion token.
while (Tok.isNot(tok::code_complete, tok::eof)) {
consumeToken();
}
// Consume the code completion token, if there is one.
consumeIf(tok::code_complete);
// Also perform the same recovery as the main parser to capture tokens from
// this decl that are past the code completion token.
skipUntilDeclStmtRBrace(tok::l_brace);
SourceLoc EndLoc = Tok.getLoc();
State->delayTopLevel(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.
skipUntil(tok::eof);
}
/// 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) {
SyntaxParsingContext StmtListContext(SyntaxContext, SyntaxKind::StmtList);
bool IsTopLevel = (Kind == BraceItemListKind::TopLevelCode) ||
(Kind == BraceItemListKind::TopLevelLibrary);
bool isActiveConditionalBlock =
ConditionalBlockKind == BraceItemListKind::ActiveConditionalBlock;
bool isConditionalBlock = isActiveConditionalBlock ||
ConditionalBlockKind == BraceItemListKind::InactiveConditionalBlock;
// If we're not parsing an active #if block, form a new lexical scope.
Optional<Scope> initScope;
if (!isActiveConditionalBlock) {
auto scopeKind = IsTopLevel ? ScopeKind::TopLevel : ScopeKind::Brace;
initScope.emplace(this, scopeKind,
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) &&
Tok.isNot(tok::kw_sil) &&
Tok.isNot(tok::kw_sil_scope) &&
Tok.isNot(tok::kw_sil_stage) &&
Tok.isNot(tok::kw_sil_vtable) &&
Tok.isNot(tok::kw_sil_global) &&
Tok.isNot(tok::kw_sil_witness_table) &&
Tok.isNot(tok::kw_sil_default_witness_table) &&
(isConditionalBlock ||
!isTerminatorForBraceItemListKind(Kind, Entries))) {
SyntaxParsingContext StmtContext(SyntaxContext, SyntaxContextKind::Stmt);
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 (consumeIf(tok::unknown))
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.
if (!PreviousHadSemi && !Tok.isAtStartOfLine()) {
SourceLoc EndOfPreviousLoc = getEndOfPreviousLoc();
diagnose(EndOfPreviousLoc, diag::statement_same_line_without_semi)
.fixItInsert(EndOfPreviousLoc, ";");
// FIXME: Add semicolon to the AST?
}
ParserPosition BeginParserPosition;
if (isCodeCompletionFirstPass())
BeginParserPosition = getParserPosition();
// Parse the decl, stmt, or expression.
PreviousHadSemi = false;
if (Tok.is(tok::pound_if)) {
auto IfConfigResult = parseIfConfig(
[&](SmallVectorImpl<ASTNode> &Elements, bool IsActive) {
parseBraceItems(Elements, Kind, IsActive
? BraceItemListKind::ActiveConditionalBlock
: BraceItemListKind::InactiveConditionalBlock);
});
if (auto ICD = IfConfigResult.getPtrOrNull()) {
Result = ICD;
// Add the #if block itself
Entries.push_back(ICD);
for (auto &Entry : ICD->getActiveClauseElements()) {
if (Entry.is<Decl *>() && isa<IfConfigDecl>(Entry.get<Decl *>()))
// Don't hoist nested '#if'.
continue;
Entries.push_back(Entry);
if (Entry.is<Decl *>())
Entry.get<Decl *>()->setEscapedFromIfConfig(true);
}
} else {
NeedParseErrorRecovery = true;
continue;
}
} else if (Tok.is(tok::pound_line)) {
ParserStatus Status = parseLineDirective(true);
BraceItemsStatus |= Status;
NeedParseErrorRecovery = Status.isError();
} else if (Tok.is(tok::pound_sourceLocation)) {
ParserStatus Status = parseLineDirective(false);
BraceItemsStatus |= Status;
NeedParseErrorRecovery = Status.isError();
} else if (isStartOfDecl()) {
SmallVector<Decl*, 8> TmpDecls;
ParserResult<Decl> DeclResult =
parseDecl(IsTopLevel ? PD_AllowTopLevel : PD_Default,
[&](Decl *D) {TmpDecls.push_back(D);});
if (DeclResult.isParseError()) {
NeedParseErrorRecovery = true;
if (DeclResult.hasCodeCompletion() && IsTopLevel &&
isCodeCompletionFirstPass()) {
consumeDecl(BeginParserPosition, None, IsTopLevel);
return DeclResult;
}
}
Result = DeclResult.getPtrOrNull();
Entries.append(TmpDecls.begin(), TmpDecls.end());
} 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, &State->getTopLevelContext());
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);
if (Status.hasCodeCompletion() && isCodeCompletionFirstPass()) {
consumeTopLevelDecl(BeginParserPosition, TLCD);
auto Brace = BraceStmt::create(Context, StartLoc, {}, Tok.getLoc());
TLCD->setBody(Brace);
Entries.push_back(TLCD);
return Status;
}
if (Status.isError())
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
auto Brace = BraceStmt::create(Context, Result.getStartLoc(),
Result, Result.getEndLoc());
TLCD->setBody(Brace);
Entries.push_back(TLCD);
}
} else if (Tok.is(tok::kw_init) && isa<ConstructorDecl>(CurDeclContext)) {
SourceLoc StartLoc = Tok.getLoc();
auto CD = cast<ConstructorDecl>(CurDeclContext);
// Hint at missing 'self.' or 'super.' then skip this statement.
bool isSelf = !CD->isDesignatedInit() || !isa<ClassDecl>(CD->getParent());
diagnose(StartLoc, diag::invalid_nested_init, isSelf)
.fixItInsert(StartLoc, isSelf ? "self." : "super.");
NeedParseErrorRecovery = 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, decl or
// '{'.
//
// 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(tok::l_brace);
// If we have to recover, pretend that we had a semicolon; it's less
// noisy that way.
PreviousHadSemi = true;
}
}
return BraceItemsStatus;
}
void Parser::parseTopLevelCodeDeclDelayed() {
auto DelayedState = State->takeDelayedDeclState();
assert(DelayedState.get() && "should have delayed state");
auto BeginParserPosition = getParserPosition(DelayedState->BodyPos);
auto EndLexerState = L->getStateForEndOfTokenLoc(DelayedState->BodyEnd);
// ParserPositionRAII needs a primed parser to restore to.
if (Tok.is(tok::NUM_TOKENS))
consumeTokenWithoutFeedingReceiver();
// Ensure that we restore the parser state at exit.
ParserPositionRAII PPR(*this);
// Create a lexer that cannot go past the end state.
Lexer LocalLex(*L, BeginParserPosition.LS, EndLexerState);
// Temporarily swap out the parser's current lexer with our new one.
llvm::SaveAndRestore<Lexer *> T(L, &LocalLex);
// Rewind to the beginning of the top-level code.
restoreParserPosition(BeginParserPosition);
// Re-enter the lexical scope.
Scope S(this, DelayedState->takeScope());
// Re-enter the top-level decl context.
// FIXME: this can issue discriminators out-of-order?
auto *TLCD = cast<TopLevelCodeDecl>(DelayedState->ParentContext);
ContextChange CC(*this, TLCD, &State->getTopLevelContext());
SourceLoc StartLoc = Tok.getLoc();
ASTNode Result;
// 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);
}
parseExprOrStmt(Result);
if (!Result.isNull()) {
auto Brace = BraceStmt::create(Context, StartLoc, Result, Tok.getLoc());
TLCD->setBody(Brace);
}
}
/// Recover from a 'case' or 'default' outside of a 'switch' by consuming up to
/// the next ':'.
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);
// FIXME: Return an ErrorStmt?
return nullptr;
}
ParserResult<Stmt> Parser::parseStmt() {
SyntaxParsingContext LocalContext(SyntaxContext, SyntaxContextKind::Stmt);
// Note that we're parsing a statement.
StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(),
StructureMarkerKind::Statement);
LabeledStmtInfo LabelInfo;
// If this is a label on a loop/switch statement, consume it and pass it into
// parsing logic below.
if (Tok.is(tok::identifier) && peekToken().is(tok::colon)) {
LabelInfo.Loc = consumeIdentifier(&LabelInfo.Name);
consumeToken(tok::colon);
}
SourceLoc tryLoc;
(void)consumeIf(tok::kw_try, tryLoc);
switch (Tok.getKind()) {
case tok::pound_line:
case tok::pound_sourceLocation:
case tok::pound_if:
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);
return nullptr;
case tok::kw_return:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtReturn(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_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());
SyntaxContext->setCreateSyntax(SyntaxKind::FallthroughStmt);
return makeParserResult(
new (Context) FallthroughStmt(consumeToken(tok::kw_fallthrough)));
}
}
}
/// 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
while (Tok.isNot(tok::eof, tok::l_brace) && !Tok.isAtStartOfLine())
skipSingle();
if (Tok.isNot(tok::l_brace))
return nullptr;
}
SyntaxParsingContext LocalContext(SyntaxContext, SyntaxKind::CodeBlock);
SourceLoc LBLoc = consumeToken(tok::l_brace);
SmallVector<ASTNode, 16> Entries;
SourceLoc RBLoc;
ParserStatus Status = parseBraceItems(Entries, BraceItemListKind::Brace,
BraceItemListKind::Brace);
parseMatchingToken(tok::r_brace, RBLoc,
diag::expected_rbrace_in_brace_stmt, LBLoc);
return makeParserResult(Status,
BraceStmt::create(Context, LBLoc, Entries, RBLoc));
}
/// parseStmtBreak
///
/// stmt-break:
/// 'break' identifier?
///
ParserResult<Stmt> Parser::parseStmtBreak() {
SyntaxContext->setCreateSyntax(SyntaxKind::BreakStmt);
SourceLoc Loc = consumeToken(tok::kw_break);
SourceLoc TargetLoc;
Identifier Target;
// If we have an identifier after this, 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 break is dead, we don't feel bad eagerly
// parsing this.
if (Tok.is(tok::identifier) && !Tok.isAtStartOfLine() &&
!isStartOfStmt() && !isStartOfDecl())
TargetLoc = consumeIdentifier(&Target);
return makeParserResult(new (Context) BreakStmt(Loc, Target, TargetLoc));
}
/// parseStmtContinue
///
/// stmt-continue:
/// 'continue' identifier?
///
ParserResult<Stmt> Parser::parseStmtContinue() {
SyntaxContext->setCreateSyntax(SyntaxKind::ContinueStmt);
SourceLoc Loc = consumeToken(tok::kw_continue);
SourceLoc TargetLoc;
Identifier Target;
// If we have an identifier after this, which is not the start of another
// stmt or decl, we assume it is the label to continue to, unless there is a
// line break. There is ambiguity with expressions (e.g. "continue x+y") but
// since the expression after the continue is dead, we don't feel bad eagerly
// parsing this.
if (Tok.is(tok::identifier) && !Tok.isAtStartOfLine() &&
!isStartOfStmt() && !isStartOfDecl())
TargetLoc = consumeIdentifier(&Target);
return makeParserResult(new (Context) ContinueStmt(Loc, Target, TargetLoc));
}
/// parseStmtReturn
///
/// stmt-return:
/// 'return' expr?
///
ParserResult<Stmt> Parser::parseStmtReturn(SourceLoc tryLoc) {
SyntaxContext->setCreateSyntax(SyntaxKind::ReturnStmt);
SourceLoc ReturnLoc = consumeToken(tok::kw_return);
if (Tok.is(tok::code_complete)) {
auto CCE = new (Context) CodeCompletionExpr(SourceRange(Tok.getLoc()));
auto Result = makeParserResult(new (Context) ReturnStmt(ReturnLoc, CCE));
if (CodeCompletion) {
CodeCompletion->completeReturnStmt(CCE);
}
Result.setHasCodeCompletion();
consumeToken();
return Result;
}
// 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 (Tok.isNot(tok::r_brace, tok::semi, tok::eof, tok::pound_if,
tok::pound_endif, tok::pound_else, tok::pound_elseif) &&
!isStartOfStmt() && !isStartOfDecl()) {
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.getLineAndColumn(ReturnLoc).second ==
SourceMgr.getLineAndColumn(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_on_return_throw, /*isThrow=*/false)
.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, new (Context) ReturnStmt(ReturnLoc, Result.getPtrOrNull()));
}
if (tryLoc.isValid())
diagnose(tryLoc, diag::try_on_stmt, "return");
return makeParserResult(new (Context) ReturnStmt(ReturnLoc, nullptr));
}
/// parseStmtThrow
///
/// stmt-throw
/// 'throw' expr
///
ParserResult<Stmt> Parser::parseStmtThrow(SourceLoc tryLoc) {
SyntaxContext->setCreateSyntax(SyntaxKind::ThrowStmt);
SourceLoc throwLoc = consumeToken(tok::kw_throw);
SourceLoc exprLoc;
if (Tok.isNot(tok::eof))
exprLoc = Tok.getLoc();
ParserResult<Expr> Result = parseExpr(diag::expected_expr_throw);
if (Result.hasCodeCompletion())
return makeParserCodeCompletionResult<Stmt>();
if (Result.isNull())
Result = makeParserErrorResult(new (Context) ErrorExpr(throwLoc));
if (tryLoc.isValid() && exprLoc.isValid()) {
diagnose(tryLoc, diag::try_on_return_throw, /*isThrow=*/true)
.fixItInsert(exprLoc, "try ")
.fixItRemoveChars(tryLoc, throwLoc);
// Note: We can't use tryLoc here because that's outside the ThrowStmt's
// source range.
if (Result.isNonNull() && !isa<ErrorExpr>(Result.get()))
Result = makeParserResult(new (Context) TryExpr(exprLoc, Result.get()));
}
return makeParserResult(Result,
new (Context) ThrowStmt(throwLoc, Result.get()));
}
/// parseStmtDefer
///
/// stmt-defer:
/// 'defer' brace-stmt
///
ParserResult<Stmt> Parser::parseStmtDefer() {
SyntaxContext->setCreateSyntax(SyntaxKind::DeferStmt);
SourceLoc DeferLoc = consumeToken(tok::kw_defer);
// Macro expand out the defer into a closure and call, which we can typecheck
// and emit where needed.
//
// The AST representation for a defer statement is a bit weird. We retain the
// brace statement that the user wrote, but actually model this as if they
// wrote:
//
// func tmpClosure() { body }
// tmpClosure() // This is emitted on each path that needs to run this.
//
// As such, the body of the 'defer' is actually type checked within the
// closure's DeclContext.
auto params = ParameterList::createEmpty(Context);
DeclName name(Context, Context.getIdentifier("$defer"), params);
auto tempDecl
= FuncDecl::create(Context,
/*StaticLoc=*/ SourceLoc(),
StaticSpellingKind::None,
/*FuncLoc=*/ SourceLoc(),
name,
/*NameLoc=*/ SourceLoc(),
/*Throws=*/ false, /*ThrowsLoc=*/ SourceLoc(),
/*generic params*/ nullptr,
params,
TypeLoc(),
CurDeclContext);
tempDecl->setImplicit();
setLocalDiscriminator(tempDecl);
ParserStatus Status;
{
// Change the DeclContext for any variables declared in the defer to be within
// the defer closure.
ParseFunctionBody cc(*this, tempDecl);
ParserResult<BraceStmt> Body =
parseBraceItemList(diag::expected_lbrace_after_defer);
if (Body.isNull())
return nullptr;
Status |= Body;
tempDecl->setBody(Body.get());
}
SourceLoc loc = tempDecl->getBody()->getStartLoc();
// Form the call, which will be emitted on any path that needs to run the
// code.
auto DRE = new (Context) DeclRefExpr(tempDecl, DeclNameLoc(loc),
/*Implicit*/true,
AccessSemantics::DirectToStorage);
auto call = CallExpr::createImplicit(Context, DRE, { }, { });
auto DS = new (Context) DeferStmt(DeferLoc, tempDecl, call);
return makeParserResult(Status, DS);
}
namespace {
struct GuardedPattern {
Pattern *ThePattern = nullptr;
SourceLoc WhereLoc;
Expr *Guard = nullptr;
};
/// Contexts in which a guarded pattern can appear.
enum class GuardedPatternContext {
Case,
Catch,
};
} // unnamed namespace
/// Parse a pattern-matching clause for a case or catch statement,
/// including the guard expression:
///
/// pattern 'where' expr
static void parseGuardedPattern(Parser &P, GuardedPattern &result,
ParserStatus &status,
SmallVectorImpl<VarDecl *> &boundDecls,
GuardedPatternContext parsingContext,
bool isFirstPattern) {
ParserResult<Pattern> patternResult;
auto setErrorResult = [&] () {
patternResult = makeParserErrorResult(new (P.Context)
AnyPattern(SourceLoc()));
};
bool isExprBasic = [&]() -> bool {
switch (parsingContext) {
// 'case' is terminated with a colon and so allows a trailing closure.
case GuardedPatternContext::Case:
return false;
// 'catch' is terminated with a brace and so cannot.
case GuardedPatternContext::Catch:
return true;
}
llvm_unreachable("bad pattern context");
}();
// Do some special-case code completion for the start of the pattern.
if (P.Tok.is(tok::code_complete)) {
setErrorResult();
if (P.CodeCompletion) {
switch (parsingContext) {
case GuardedPatternContext::Case:
P.CodeCompletion->completeCaseStmtBeginning();
break;
case GuardedPatternContext::Catch:
P.CodeCompletion->completePostfixExprBeginning(nullptr);
break;
}
P.consumeToken();
} else {
result.ThePattern = patternResult.get();
status.setHasCodeCompletion();
return;
}
}
if (parsingContext == GuardedPatternContext::Case &&
P.Tok.isAny(tok::period_prefix, tok::period) &&
P.peekToken().is(tok::code_complete)) {
setErrorResult();
if (P.CodeCompletion) {
P.consumeToken();
P.CodeCompletion->completeCaseStmtDotPrefix();
P.consumeToken();
} else {
result.ThePattern = patternResult.get();
status.setHasCodeCompletion();
return;
}
}
// If this is a 'catch' clause and we have "catch {" or "catch where...",
// then we get an implicit "let error" pattern.
if (parsingContext == GuardedPatternContext::Catch &&
P.Tok.isAny(tok::l_brace, tok::kw_where)) {
auto loc = P.Tok.getLoc();
auto errorName = P.Context.Id_error;
auto var = new (P.Context) VarDecl(/*IsStatic*/false,
VarDecl::Specifier::Let,
/*IsCaptureList*/false, loc, errorName,
Type(), P.CurDeclContext);
var->setImplicit();
auto namePattern = new (P.Context) NamedPattern(var);
auto varPattern = new (P.Context) VarPattern(loc, /*isLet*/true,
namePattern, /*implicit*/true);
patternResult = makeParserResult(varPattern);
}
// Okay, if the special code-completion didn't kick in, parse a
// matching pattern.
if (patternResult.isNull()) {
llvm::SaveAndRestore<decltype(P.InVarOrLetPattern)>
T(P.InVarOrLetPattern, Parser::IVOLP_InMatchingPattern);
patternResult = P.parseMatchingPattern(isExprBasic);
}
// If that didn't work, use a bogus pattern so that we can fill out
// the AST.
if (patternResult.isNull())
patternResult =
makeParserErrorResult(new (P.Context) AnyPattern(P.PreviousLoc));
// Fill in the pattern.
status |= patternResult;
result.ThePattern = patternResult.get();
if (isFirstPattern) {
// Add variable bindings from the pattern to the case scope. We have
// to do this with a full AST walk, because the freshly parsed pattern
// represents tuples and var patterns as tupleexprs and
// unresolved_pattern_expr nodes, instead of as proper pattern nodes.
patternResult.get()->forEachVariable([&](VarDecl *VD) {
if (VD->hasName()) P.addToScope(VD);
boundDecls.push_back(VD);
});
} else {
// If boundDecls already contains variables, then we must match the
// same number and same names in this pattern as were declared in a
// previous pattern (and later we will make sure they have the same
// types).
SmallVector<VarDecl*, 4> repeatedDecls;
patternResult.get()->forEachVariable([&](VarDecl *VD) {
if (!VD->hasName())
return;
for (auto repeat : repeatedDecls)
if (repeat->getName() == VD->getName())
P.addToScope(VD); // will diagnose a duplicate declaration
bool found = false;
for (auto previous : boundDecls) {
if (previous->hasName() && previous->getName() == VD->getName()) {
found = true;
break;
}
}
if (!found) {
// Diagnose a declaration that doesn't match a previous pattern.
P.diagnose(VD->getLoc(), diag::extra_var_in_multiple_pattern_list, VD->getName());
status.setIsParseError();
}
repeatedDecls.push_back(VD);
});
for (auto previous : boundDecls) {
bool found = false;
for (auto repeat : repeatedDecls) {
if (previous->hasName() && previous->getName() == repeat->getName()) {
found = true;
break;
}
}
if (!found) {
// Diagnose a previous declaration that is missing in this pattern.
P.diagnose(previous->getLoc(), diag::extra_var_in_multiple_pattern_list, previous->getName());
status.setIsParseError();
}
}
for (auto VD : repeatedDecls) {
VD->setHasNonPatternBindingInit();
VD->setImplicit();
}
}
// Now that we have them, mark them as being initialized without a PBD.
for (auto VD : boundDecls)
VD->setHasNonPatternBindingInit();
// Parse the optional 'where' guard.
if (P.Tok.is(tok::kw_where)) {
SyntaxParsingContext WhereClauseCtxt(P.SyntaxContext,
SyntaxKind::WhereClause);
result.WhereLoc = P.consumeToken(tok::kw_where);
SourceLoc startOfGuard = P.Tok.getLoc();
auto diagKind = [=]() -> Diag<> {
switch (parsingContext) {
case GuardedPatternContext::Case:
return diag::expected_case_where_expr;
case GuardedPatternContext::Catch:
return diag::expected_catch_where_expr;