blob: 727ab75adae8bb9aaa027ad5d09ea25459b3dc9f [file] [log] [blame]
Chris Lattner7ad0fbe2006-11-05 07:46:30 +00001//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
Chris Lattner0ccd51e2006-08-09 05:47:47 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner0ccd51e2006-08-09 05:47:47 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Statement and Block portions of the Parser
10// interface.
11//
12//===----------------------------------------------------------------------===//
13
Jordan Rose1e879d82018-03-23 00:07:18 +000014#include "clang/AST/PrettyDeclStackTrace.h"
Aaron Ballmanb06b15a2014-06-06 12:40:24 +000015#include "clang/Basic/Attributes.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/Basic/PrettyStackTrace.h"
Richard Trieu0614cff2018-11-28 04:36:31 +000017#include "clang/Parse/LoopHint.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000018#include "clang/Parse/Parser.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000019#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/Scope.h"
Richard Smith4f605af2012-08-18 00:55:03 +000022#include "clang/Sema/TypoCorrection.h"
Chris Lattner0ccd51e2006-08-09 05:47:47 +000023using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// C99 6.8: Statements and Blocks.
27//===----------------------------------------------------------------------===//
28
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000029/// Parse a standalone statement (for instance, as the body of an 'if',
Richard Smith426a47b2013-10-28 22:04:30 +000030/// 'while', or 'for').
Alexey Bataevc4fad652016-01-13 11:18:54 +000031StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
Richard Smitha6e8d5e2019-02-15 00:27:53 +000032 ParsedStmtContext StmtCtx) {
Richard Smith426a47b2013-10-28 22:04:30 +000033 StmtResult Res;
34
35 // We may get back a null statement if we found a #pragma. Keep going until
36 // we get an actual statement.
37 do {
38 StmtVector Stmts;
Richard Smitha6e8d5e2019-02-15 00:27:53 +000039 Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);
Richard Smith426a47b2013-10-28 22:04:30 +000040 } while (!Res.isInvalid() && !Res.get());
41
42 return Res;
43}
44
Chris Lattner0ccd51e2006-08-09 05:47:47 +000045/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
46/// StatementOrDeclaration:
47/// statement
48/// declaration
49///
50/// statement:
51/// labeled-statement
52/// compound-statement
53/// expression-statement
54/// selection-statement
55/// iteration-statement
56/// jump-statement
Argyrios Kyrtzidisdee82912008-09-07 18:58:01 +000057/// [C++] declaration-statement
Sebastian Redlb219c902008-12-21 16:41:36 +000058/// [C++] try-block
John Wiegley1c0675e2011-04-28 01:08:34 +000059/// [MS] seh-try-block
Fariborz Jahanian90814572007-10-04 20:19:06 +000060/// [OBC] objc-throw-statement
61/// [OBC] objc-try-catch-statement
Fariborz Jahanianf89ca382008-01-29 18:21:32 +000062/// [OBC] objc-synchronized-statement
Chris Lattner0116c472006-08-15 06:03:28 +000063/// [GNU] asm-statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +000064/// [OMP] openmp-construct [TODO]
65///
66/// labeled-statement:
67/// identifier ':' statement
68/// 'case' constant-expression ':' statement
69/// 'default' ':' statement
70///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000071/// selection-statement:
72/// if-statement
73/// switch-statement
74///
75/// iteration-statement:
76/// while-statement
77/// do-statement
78/// for-statement
79///
Chris Lattner9075bd72006-08-10 04:59:57 +000080/// expression-statement:
81/// expression[opt] ';'
82///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000083/// jump-statement:
84/// 'goto' identifier ';'
85/// 'continue' ';'
86/// 'break' ';'
87/// 'return' expression[opt] ';'
Chris Lattner503fadc2006-08-10 05:45:44 +000088/// [GNU] 'goto' '*' expression ';'
Chris Lattner0ccd51e2006-08-09 05:47:47 +000089///
Fariborz Jahanian90814572007-10-04 20:19:06 +000090/// [OBC] objc-throw-statement:
91/// [OBC] '@' 'throw' expression ';'
Mike Stump11289f42009-09-09 15:08:12 +000092/// [OBC] '@' 'throw' ';'
93///
John McCalldadc5752010-08-24 06:29:42 +000094StmtResult
Alexey Bataevc4fad652016-01-13 11:18:54 +000095Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
Richard Smitha6e8d5e2019-02-15 00:27:53 +000096 ParsedStmtContext StmtCtx,
Nico Weber3cef1082011-12-22 23:26:17 +000097 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000098
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +000099 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000100
Richard Smithc202b282012-04-14 00:33:13 +0000101 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +0000102 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +0000103 if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
104 return StmtError();
Richard Smithc202b282012-04-14 00:33:13 +0000105
Alexey Bataevc4fad652016-01-13 11:18:54 +0000106 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000107 Stmts, StmtCtx, TrailingElseLoc, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000108
109 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
110 "attributes on empty statement");
111
112 if (Attrs.empty() || Res.isInvalid())
113 return Res;
114
Erich Keanec480f302018-07-12 21:09:05 +0000115 return Actions.ProcessStmtAttributes(Res.get(), Attrs, Attrs.Range);
Richard Smithc202b282012-04-14 00:33:13 +0000116}
117
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000118namespace {
Bruno Ricci70ad3962019-03-25 17:08:51 +0000119class StatementFilterCCC final : public CorrectionCandidateCallback {
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000120public:
121 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000122 WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
123 tok::identifier, tok::star, tok::amp);
124 WantExpressionKeywords =
125 nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
126 WantRemainingKeywords =
127 nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000128 WantCXXNamedCasts = false;
129 }
130
Craig Topper2b07f022014-03-12 05:09:18 +0000131 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000132 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
Kaelyn Uhrain07e62722013-10-01 22:00:28 +0000133 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain46b6cdc2013-09-27 19:40:16 +0000134 if (NextToken.is(tok::equal))
135 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain30943ce2013-09-27 23:54:23 +0000136 if (NextToken.is(tok::period) &&
137 candidate.getCorrectionDeclAs<NamespaceDecl>())
138 return false;
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000139 return CorrectionCandidateCallback::ValidateCandidate(candidate);
140 }
141
Bruno Ricci70ad3962019-03-25 17:08:51 +0000142 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000143 return std::make_unique<StatementFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +0000144 }
145
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000146private:
147 Token NextToken;
148};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000149}
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000150
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000151StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
152 StmtVector &Stmts, ParsedStmtContext StmtCtx,
153 SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs) {
Craig Topper161e4db2014-05-21 06:02:52 +0000154 const char *SemiError = nullptr;
Richard Smithc202b282012-04-14 00:33:13 +0000155 StmtResult Res;
Nathan Huckleberry1e0affb2019-08-20 17:16:49 +0000156 SourceLocation GNUAttributeLoc;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000157
Chris Lattner503fadc2006-08-10 05:45:44 +0000158 // Cases in this switch statement should fall through if the parser expects
159 // the token to end in a semicolon (in which case SemiError should be set),
160 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000161Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000162 tok::TokenKind Kind = Tok.getKind();
163 SourceLocation AtLoc;
164 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000165 case tok::at: // May be a @try or @throw statement
166 {
Richard Smithc202b282012-04-14 00:33:13 +0000167 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000168 AtLoc = ConsumeToken(); // consume @
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000169 return ParseObjCAtStatement(AtLoc, StmtCtx);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000170 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000171
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000172 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000173 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000174 cutOffParsing();
175 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000176
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000177 case tok::identifier: {
178 Token Next = NextToken();
179 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000180 // identifier ':' statement
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000181 return ParseLabeledStatement(Attrs, StmtCtx);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000182 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000183
Richard Smith4f605af2012-08-18 00:55:03 +0000184 // Look up the identifier, and typo-correct it to a keyword if it's not
185 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000186 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000187 // Try to limit which sets of keywords should be included in typo
188 // correction based on what the next token is.
Bruno Ricci70ad3962019-03-25 17:08:51 +0000189 StatementFilterCCC CCC(Next);
Richard Smith7e8fe672019-10-14 21:53:03 +0000190 if (TryAnnotateName(&CCC) == ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000191 // Handle errors here by skipping up to the next semicolon or '}', and
192 // eat the semicolon if that's what stopped us.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000193 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000194 if (Tok.is(tok::semi))
195 ConsumeToken();
196 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000197 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000198
Richard Smith4f605af2012-08-18 00:55:03 +0000199 // If the identifier was typo-corrected, try again.
200 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000201 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000202 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000203
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000204 // Fall through
Galina Kistanova387ab8b2017-06-01 21:28:26 +0000205 LLVM_FALLTHROUGH;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000206 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000207
Chris Lattner803802d2009-03-24 17:04:48 +0000208 default: {
David Majnemer6ac7dd12016-08-01 16:39:29 +0000209 if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000210 (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
211 ParsedStmtContext()) &&
Nathan Huckleberry1e0affb2019-08-20 17:16:49 +0000212 (GNUAttributeLoc.isValid() || isDeclarationStatement())) {
Chris Lattner49836b42009-04-02 04:16:50 +0000213 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Nathan Huckleberry1e0affb2019-08-20 17:16:49 +0000214 DeclGroupPtrTy Decl;
215 if (GNUAttributeLoc.isValid()) {
216 DeclStart = GNUAttributeLoc;
217 Decl = ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, Attrs,
218 &GNUAttributeLoc);
219 } else {
220 Decl =
221 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, Attrs);
222 }
Stephan Bergmanndc3957e2019-10-17 11:20:21 +0000223 if (Attrs.Range.getBegin().isValid())
224 DeclStart = Attrs.Range.getBegin();
Chris Lattner49836b42009-04-02 04:16:50 +0000225 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000226 }
227
228 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000229 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000230 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000231 }
Mike Stump11289f42009-09-09 15:08:12 +0000232
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000233 return ParseExprStatement(StmtCtx);
Chris Lattner803802d2009-03-24 17:04:48 +0000234 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000235
Nathan Huckleberry1e0affb2019-08-20 17:16:49 +0000236 case tok::kw___attribute: {
237 GNUAttributeLoc = Tok.getLocation();
238 ParseGNUAttributes(Attrs);
239 goto Retry;
240 }
241
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000242 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000243 return ParseCaseStatement(StmtCtx);
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000244 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000245 return ParseDefaultStatement(StmtCtx);
Sebastian Redl042ad952008-12-11 19:30:53 +0000246
Chris Lattner9075bd72006-08-10 04:59:57 +0000247 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000248 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000249 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000250 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
251 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000252 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000253
Chris Lattner9075bd72006-08-10 04:59:57 +0000254 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000255 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000256 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000257 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000258
Chris Lattner9075bd72006-08-10 04:59:57 +0000259 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000260 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000261 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000262 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000263 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000264 break;
265 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000266 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000267
268 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000269 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000270 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000271 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000272 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000273 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000274 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000275 break;
276 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000277 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000278 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000279 break;
280 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000281 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000282 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000283 break;
Richard Smith0e304ea2015-10-22 04:46:14 +0000284 case tok::kw_co_return: // C++ Coroutines: co_return statement
285 Res = ParseReturnStatement();
286 SemiError = "co_return";
287 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000288
Sebastian Redlb219c902008-12-21 16:41:36 +0000289 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000290 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000291 bool msAsm = false;
292 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000293 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000294 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000295 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000296 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000297 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000298
Reid Kleckner6d8d22a2014-06-25 00:28:35 +0000299 case tok::kw___if_exists:
300 case tok::kw___if_not_exists:
301 ProhibitAttributes(Attrs);
302 ParseMicrosoftIfExistsStatement(Stmts);
303 // An __if_exists block is like a compound statement, but it doesn't create
304 // a new scope.
305 return StmtEmpty();
306
Sebastian Redlb219c902008-12-21 16:41:36 +0000307 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000308 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000309
310 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000311 ProhibitAttributes(Attrs); // TODO: is it correct?
312 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000313
Nico Weberc7d05962014-07-06 22:32:59 +0000314 case tok::kw___leave:
315 Res = ParseSEHLeaveStatement();
316 SemiError = "__leave";
317 break;
318
Eli Friedmanec52f922012-02-23 23:47:16 +0000319 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000320 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000321 HandlePragmaVisibility();
322 return StmtEmpty();
323
324 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000325 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000326 HandlePragmaPack();
327 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000328
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000329 case tok::annot_pragma_msstruct:
330 ProhibitAttributes(Attrs);
331 HandlePragmaMSStruct();
332 return StmtEmpty();
333
Eli Friedmanae8ee252012-10-08 23:52:38 +0000334 case tok::annot_pragma_align:
335 ProhibitAttributes(Attrs);
336 HandlePragmaAlign();
337 return StmtEmpty();
338
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000339 case tok::annot_pragma_weak:
340 ProhibitAttributes(Attrs);
341 HandlePragmaWeak();
342 return StmtEmpty();
343
344 case tok::annot_pragma_weakalias:
345 ProhibitAttributes(Attrs);
346 HandlePragmaWeakAlias();
347 return StmtEmpty();
348
349 case tok::annot_pragma_redefine_extname:
350 ProhibitAttributes(Attrs);
351 HandlePragmaRedefineExtname();
352 return StmtEmpty();
353
Eli Friedman68be1642012-10-04 02:36:51 +0000354 case tok::annot_pragma_fp_contract:
Richard Smithca9b0b62013-11-15 21:10:54 +0000355 ProhibitAttributes(Attrs);
Lang Hamesa930e712012-10-21 01:10:01 +0000356 Diag(Tok, diag::err_pragma_fp_contract_scope);
Richard Smithaf3b3252017-05-18 19:21:48 +0000357 ConsumeAnnotationToken();
Lang Hamesa930e712012-10-21 01:10:01 +0000358 return StmtError();
359
Adam Nemet60d32642017-04-04 21:18:36 +0000360 case tok::annot_pragma_fp:
361 ProhibitAttributes(Attrs);
362 Diag(Tok, diag::err_pragma_fp_scope);
Richard Smithaf3b3252017-05-18 19:21:48 +0000363 ConsumeAnnotationToken();
Adam Nemet60d32642017-04-04 21:18:36 +0000364 return StmtError();
365
Kevin P. Neal2c0bc8b2018-08-14 17:06:56 +0000366 case tok::annot_pragma_fenv_access:
367 ProhibitAttributes(Attrs);
368 HandlePragmaFEnvAccess();
369 return StmtEmpty();
370
Eli Friedman68be1642012-10-04 02:36:51 +0000371 case tok::annot_pragma_opencl_extension:
372 ProhibitAttributes(Attrs);
373 HandlePragmaOpenCLExtension();
374 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000375
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000376 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000377 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000378 return HandlePragmaCaptured();
379
Alexey Bataeva769e072013-03-22 06:34:35 +0000380 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000381 ProhibitAttributes(Attrs);
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000382 return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000383
David Majnemer4bb09802014-02-10 19:50:15 +0000384 case tok::annot_pragma_ms_pointers_to_members:
385 ProhibitAttributes(Attrs);
386 HandlePragmaMSPointersToMembers();
387 return StmtEmpty();
388
Warren Huntc3b18962014-04-08 22:30:47 +0000389 case tok::annot_pragma_ms_pragma:
390 ProhibitAttributes(Attrs);
391 HandlePragmaMSPragma();
392 return StmtEmpty();
Aaron Ballmanb06b15a2014-06-06 12:40:24 +0000393
Alexey Bataev3d42f342015-11-20 07:02:57 +0000394 case tok::annot_pragma_ms_vtordisp:
395 ProhibitAttributes(Attrs);
396 HandlePragmaMSVtorDisp();
397 return StmtEmpty();
398
Aaron Ballmanb06b15a2014-06-06 12:40:24 +0000399 case tok::annot_pragma_loop_hint:
400 ProhibitAttributes(Attrs);
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000401 return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, Attrs);
Richard Smithba3a4f92016-01-12 21:59:26 +0000402
403 case tok::annot_pragma_dump:
404 HandlePragmaDump();
405 return StmtEmpty();
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000406
407 case tok::annot_pragma_attribute:
408 HandlePragmaAttribute();
409 return StmtEmpty();
Sebastian Redlb219c902008-12-21 16:41:36 +0000410 }
411
Chris Lattner503fadc2006-08-10 05:45:44 +0000412 // If we reached this code, the statement must end in a semicolon.
Alp Toker97650562014-01-10 11:19:30 +0000413 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000414 // If the result was valid, then we do want to diagnose this. Use
415 // ExpectAndConsume to emit the diagnostic, even though we know it won't
416 // succeed.
417 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000418 // Skip until we see a } or ;, but don't eat it.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000419 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner503fadc2006-08-10 05:45:44 +0000420 }
Mike Stump11289f42009-09-09 15:08:12 +0000421
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000422 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000423}
424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000425/// Parse an expression statement.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000426StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000427 // If a case keyword is missing, this is where it should be inserted.
428 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000429
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +0000430 ExprStatementTokLoc = Tok.getLocation();
431
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000432 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000433 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000434 if (Expr.isInvalid()) {
435 // If the expression is invalid, skip ahead to the next semicolon or '}'.
436 // Not doing this opens us up to the possibility of infinite loops if
437 // ParseExpression does not consume any tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000438 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000439 if (Tok.is(tok::semi))
440 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000441 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000442 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000443
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000444 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
445 Actions.CheckCaseExpression(Expr.get())) {
446 // If a constant expression is followed by a colon inside a switch block,
447 // suggest a missing case keyword.
448 Diag(OldToken, diag::err_expected_case_before_expression)
449 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000450
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000451 // Recover parsing as a case statement.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000452 return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000453 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000454
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000455 // Otherwise, eat the semicolon.
456 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000457 return handleExprStmt(Expr, StmtCtx);
John Wiegley1c0675e2011-04-28 01:08:34 +0000458}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000459
John Wiegley1c0675e2011-04-28 01:08:34 +0000460/// ParseSEHTryBlockCommon
461///
462/// seh-try-block:
463/// '__try' compound-statement seh-handler
464///
465/// seh-handler:
466/// seh-except-block
467/// seh-finally-block
468///
Nico Weberdd256742015-02-25 01:43:27 +0000469StmtResult Parser::ParseSEHTryBlock() {
470 assert(Tok.is(tok::kw___try) && "Expected '__try'");
471 SourceLocation TryLoc = ConsumeToken();
472
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000473 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000474 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley1c0675e2011-04-28 01:08:34 +0000475
Momchil Velikov57c681f2017-08-10 15:43:06 +0000476 StmtResult TryBlock(ParseCompoundStatement(
477 /*isStmtExpr=*/false,
478 Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
479 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000480 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000481
482 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000483 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000484 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000485 SourceLocation Loc = ConsumeToken();
486 Handler = ParseSEHExceptBlock(Loc);
487 } else if (Tok.is(tok::kw___finally)) {
488 SourceLocation Loc = ConsumeToken();
489 Handler = ParseSEHFinallyBlock(Loc);
490 } else {
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000491 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
John Wiegley1c0675e2011-04-28 01:08:34 +0000492 }
493
494 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000495 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000496
497 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
498 TryLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000499 TryBlock.get(),
Warren Huntf6be4cb2014-07-25 20:52:51 +0000500 Handler.get());
John Wiegley1c0675e2011-04-28 01:08:34 +0000501}
502
503/// ParseSEHExceptBlock - Handle __except
504///
505/// seh-except-block:
506/// '__except' '(' seh-filter-expression ')' compound-statement
507///
508StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
509 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
510 raii2(Ident___exception_code, false),
511 raii3(Ident_GetExceptionCode, false);
512
Alp Toker383d2c42014-01-01 03:08:43 +0000513 if (ExpectAndConsume(tok::l_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000514 return StmtError();
515
Reid Kleckner1d59f992015-01-22 01:36:17 +0000516 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
517 Scope::SEHExceptScope);
John Wiegley1c0675e2011-04-28 01:08:34 +0000518
David Blaikiebbafb8a2012-03-11 07:00:24 +0000519 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000520 Ident__exception_info->setIsPoisoned(false);
521 Ident___exception_info->setIsPoisoned(false);
522 Ident_GetExceptionInfo->setIsPoisoned(false);
523 }
Reid Kleckner1d59f992015-01-22 01:36:17 +0000524
525 ExprResult FilterExpr;
526 {
527 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
528 Scope::SEHFilterScope);
Reid Kleckner85368fb2015-04-02 22:09:32 +0000529 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Reid Kleckner1d59f992015-01-22 01:36:17 +0000530 }
Francois Pichetbfaf4772011-04-28 03:14:31 +0000531
David Blaikiebbafb8a2012-03-11 07:00:24 +0000532 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000533 Ident__exception_info->setIsPoisoned(true);
534 Ident___exception_info->setIsPoisoned(true);
535 Ident_GetExceptionInfo->setIsPoisoned(true);
536 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000537
538 if(FilterExpr.isInvalid())
539 return StmtError();
540
Alp Toker383d2c42014-01-01 03:08:43 +0000541 if (ExpectAndConsume(tok::r_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000542 return StmtError();
543
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000544 if (Tok.isNot(tok::l_brace))
545 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
546
Richard Smithc202b282012-04-14 00:33:13 +0000547 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000548
549 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000550 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000551
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000552 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
John Wiegley1c0675e2011-04-28 01:08:34 +0000553}
554
555/// ParseSEHFinallyBlock - Handle __finally
556///
557/// seh-finally-block:
558/// '__finally' compound-statement
559///
Nico Weberd64657f2015-03-09 02:47:59 +0000560StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000561 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
562 raii2(Ident___abnormal_termination, false),
563 raii3(Ident_AbnormalTermination, false);
564
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000565 if (Tok.isNot(tok::l_brace))
566 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
567
Nico Weberd64657f2015-03-09 02:47:59 +0000568 ParseScope FinallyScope(this, 0);
569 Actions.ActOnStartSEHFinallyBlock();
570
Richard Smithc202b282012-04-14 00:33:13 +0000571 StmtResult Block(ParseCompoundStatement());
Nico Weberce903292015-03-09 03:17:15 +0000572 if(Block.isInvalid()) {
573 Actions.ActOnAbortSEHFinallyBlock();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000574 return Block;
Nico Weberce903292015-03-09 03:17:15 +0000575 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000576
Nico Weberd64657f2015-03-09 02:47:59 +0000577 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000578}
579
Nico Weberc7d05962014-07-06 22:32:59 +0000580/// Handle __leave
581///
582/// seh-leave-statement:
583/// '__leave' ';'
584///
585StmtResult Parser::ParseSEHLeaveStatement() {
586 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
587 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
588}
589
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000590/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000591///
592/// labeled-statement:
593/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000594/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000595///
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000596StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs,
597 ParsedStmtContext StmtCtx) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000598 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
599 "Not an identifier!");
600
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000601 // The substatement is always a 'statement', not a 'declaration', but is
602 // otherwise in the same context as the labeled-statement.
603 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
604
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000605 Token IdentTok = Tok; // Save the whole token.
606 ConsumeToken(); // eat the identifier.
607
608 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000609
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000610 // identifier ':' statement
611 SourceLocation ColonLoc = ConsumeToken();
612
Richard Smitha3e01cf2013-11-15 22:45:29 +0000613 // Read label attributes, if present.
614 StmtResult SubStmt;
615 if (Tok.is(tok::kw___attribute)) {
616 ParsedAttributesWithRange TempAttrs(AttrFactory);
617 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000618
Richard Smitha3e01cf2013-11-15 22:45:29 +0000619 // In C++, GNU attributes only apply to the label if they are followed by a
620 // semicolon, to disambiguate label attributes from attributes on a labeled
621 // declaration.
622 //
623 // This doesn't quite match what GCC does; if the attribute list is empty
624 // and followed by a semicolon, GCC will reject (it appears to parse the
625 // attributes as part of a statement in that case). That looks like a bug.
626 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
627 attrs.takeAllFrom(TempAttrs);
628 else if (isDeclarationStatement()) {
629 StmtVector Stmts;
630 // FIXME: We should do this whether or not we have a declaration
631 // statement, but that doesn't work correctly (because ProhibitAttributes
632 // can't handle GNU attributes), so only call it in the one case where
633 // GNU attributes are allowed.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000634 SubStmt = ParseStatementOrDeclarationAfterAttributes(Stmts, StmtCtx,
635 nullptr, TempAttrs);
Richard Smitha3e01cf2013-11-15 22:45:29 +0000636 if (!TempAttrs.empty() && !SubStmt.isInvalid())
Erich Keanec480f302018-07-12 21:09:05 +0000637 SubStmt = Actions.ProcessStmtAttributes(SubStmt.get(), TempAttrs,
638 TempAttrs.Range);
Richard Smitha3e01cf2013-11-15 22:45:29 +0000639 } else {
Alp Toker383d2c42014-01-01 03:08:43 +0000640 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smitha3e01cf2013-11-15 22:45:29 +0000641 }
642 }
643
644 // If we've not parsed a statement yet, parse one now.
645 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000646 SubStmt = ParseStatement(nullptr, StmtCtx);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000647
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000648 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000649 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000650 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000651
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000652 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
653 IdentTok.getLocation());
Erich Keanec480f302018-07-12 21:09:05 +0000654 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, attrs);
655 attrs.clear();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000656
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000657 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
658 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000659}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000660
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000661/// ParseCaseStatement
662/// labeled-statement:
663/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000664/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000665///
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000666StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
667 bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000668 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000669
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000670 // The substatement is always a 'statement', not a 'declaration', but is
671 // otherwise in the same context as the labeled-statement.
672 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
673
Chris Lattner34a22092009-03-04 04:23:07 +0000674 // It is very very common for code to contain many case statements recursively
675 // nested, as in (but usually without indentation):
676 // case 1:
677 // case 2:
678 // case 3:
679 // case 4:
680 // case 5: etc.
681 //
682 // Parsing this naively works, but is both inefficient and can cause us to run
683 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000684 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000685 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smitha3e01cf2013-11-15 22:45:29 +0000686 // weirdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000687
Chris Lattner34a22092009-03-04 04:23:07 +0000688 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
689 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000690 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner34a22092009-03-04 04:23:07 +0000692 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
693 // gets updated each time a new case is parsed, and whose body is unset so
694 // far. When parsing 'case 4', this is the 'case 3' node.
Craig Topper161e4db2014-05-21 06:02:52 +0000695 Stmt *DeepestParsedCaseStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattner34a22092009-03-04 04:23:07 +0000697 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000698 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000699 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000700 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
701 ConsumeToken(); // eat the 'case'.
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000702 ColonLoc = SourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000703
Douglas Gregord328d572009-09-21 18:10:23 +0000704 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000705 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000706 cutOffParsing();
707 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000708 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000709
Chris Lattner125c0ee2009-12-10 00:38:54 +0000710 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
711 /// Disable this form of error recovery while we're parsing the case
712 /// expression.
713 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000714
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000715 ExprResult LHS;
716 if (!MissingCase) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000717 LHS = ParseCaseExpression(CaseLoc);
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000718 if (LHS.isInvalid()) {
719 // If constant-expression is parsed unsuccessfully, recover by skipping
720 // current case statement (moving to the colon that ends it).
Richard Smithef6c43d2018-07-26 18:41:30 +0000721 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
722 return StmtError();
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000723 }
724 } else {
725 LHS = Expr;
726 MissingCase = false;
Chris Lattner476c3ad2006-08-13 22:09:58 +0000727 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000728
Chris Lattner34a22092009-03-04 04:23:07 +0000729 // GNU case range extension.
730 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000731 ExprResult RHS;
Alp Tokerec543272013-12-24 09:48:30 +0000732 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
733 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Richard Smithef6c43d2018-07-26 18:41:30 +0000734 RHS = ParseCaseExpression(CaseLoc);
Chris Lattner34a22092009-03-04 04:23:07 +0000735 if (RHS.isInvalid()) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000736 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
737 return StmtError();
Chris Lattner34a22092009-03-04 04:23:07 +0000738 }
739 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000740
Chris Lattner125c0ee2009-12-10 00:38:54 +0000741 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000742
Alp Tokerec543272013-12-24 09:48:30 +0000743 if (TryConsumeToken(tok::colon, ColonLoc)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000744 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
745 TryConsumeToken(tok::coloncolon, ColonLoc)) {
746 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Alp Tokerec543272013-12-24 09:48:30 +0000747 Diag(ColonLoc, diag::err_expected_after)
748 << "'case'" << tok::colon
749 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000750 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000751 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000752 Diag(ExpectedLoc, diag::err_expected_after)
753 << "'case'" << tok::colon
754 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000755 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000756 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000757
John McCalldadc5752010-08-24 06:29:42 +0000758 StmtResult Case =
Richard Smithef6c43d2018-07-26 18:41:30 +0000759 Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000760
Chris Lattner34a22092009-03-04 04:23:07 +0000761 // If we had a sema error parsing this case, then just ignore it and
762 // continue parsing the sub-stmt.
763 if (Case.isInvalid()) {
764 if (TopLevelCase.isInvalid()) // No parsed case stmts.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000765 return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
Chris Lattner34a22092009-03-04 04:23:07 +0000766 // Otherwise, just don't add it as a nested case.
767 } else {
768 // If this is the first case statement we parsed, it becomes TopLevelCase.
769 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000770 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000771 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000772 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000773 else
John McCallb268a282010-08-23 23:25:46 +0000774 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000775 DeepestParsedCaseStmt = NextDeepest;
776 }
Mike Stump11289f42009-09-09 15:08:12 +0000777
Chris Lattner34a22092009-03-04 04:23:07 +0000778 // Handle all case statements.
779 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000780
Chris Lattner34a22092009-03-04 04:23:07 +0000781 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000782 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattner34a22092009-03-04 04:23:07 +0000784 if (Tok.isNot(tok::r_brace)) {
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000785 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
Chris Lattner34a22092009-03-04 04:23:07 +0000786 } else {
787 // Nicely diagnose the common error "switch (X) { case 4: }", which is
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000788 // not valid. If ColonLoc doesn't point to a valid text location, there was
789 // another parsing error, so avoid producing extra diagnostics.
790 if (ColonLoc.isValid()) {
791 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
792 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
793 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
794 }
795 SubStmt = StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +0000796 }
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattner34a22092009-03-04 04:23:07 +0000798 // Install the body into the most deeply-nested case.
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000799 if (DeepestParsedCaseStmt) {
800 // Broken sub-stmt shouldn't prevent forming the case statement properly.
801 if (SubStmt.isInvalid())
802 SubStmt = Actions.ActOnNullStmt(SourceLocation());
803 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
804 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000805
Chris Lattner34a22092009-03-04 04:23:07 +0000806 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000807 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000808}
809
810/// ParseDefaultStatement
811/// labeled-statement:
812/// 'default' ':' statement
813/// Note that this does not parse the 'statement' at the end.
814///
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000815StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000816 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000817
818 // The substatement is always a 'statement', not a 'declaration', but is
819 // otherwise in the same context as the labeled-statement.
820 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
821
Chris Lattneraf635312006-10-16 06:06:51 +0000822 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000823
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000824 SourceLocation ColonLoc;
Alp Tokerec543272013-12-24 09:48:30 +0000825 if (TryConsumeToken(tok::colon, ColonLoc)) {
Alp Tokerec543272013-12-24 09:48:30 +0000826 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
Alp Toker97650562014-01-10 11:19:30 +0000827 // Treat "default;" as a typo for "default:".
Alp Tokerec543272013-12-24 09:48:30 +0000828 Diag(ColonLoc, diag::err_expected_after)
829 << "'default'" << tok::colon
830 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000831 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000832 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000833 Diag(ExpectedLoc, diag::err_expected_after)
834 << "'default'" << tok::colon
835 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000836 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000837 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000838
Richard Smith1002d102012-02-17 01:35:32 +0000839 StmtResult SubStmt;
840
841 if (Tok.isNot(tok::r_brace)) {
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000842 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
Richard Smith1002d102012-02-17 01:35:32 +0000843 } else {
844 // Diagnose the common error "switch (X) {... default: }", which is
845 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000846 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000847 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
848 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
849 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000850 }
851
Richard Smith1002d102012-02-17 01:35:32 +0000852 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000853 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000854 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000855
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000856 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000857 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000858}
859
Richard Smithc202b282012-04-14 00:33:13 +0000860StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
Momchil Velikov57c681f2017-08-10 15:43:06 +0000861 return ParseCompoundStatement(isStmtExpr,
862 Scope::DeclScope | Scope::CompoundStmtScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000863}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000864
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000865/// ParseCompoundStatement - Parse a "{}" block.
866///
867/// compound-statement: [C99 6.8.2]
868/// { block-item-list[opt] }
869/// [GNU] { label-declarations block-item-list } [TODO]
870///
871/// block-item-list:
872/// block-item
873/// block-item-list block-item
874///
875/// block-item:
876/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000877/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000878/// statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000879///
880/// [GNU] label-declarations:
881/// [GNU] label-declaration
882/// [GNU] label-declarations label-declaration
883///
884/// [GNU] label-declaration:
885/// [GNU] '__label__' identifier-list ';'
886///
Richard Smithc202b282012-04-14 00:33:13 +0000887StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000888 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000889 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000890
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000891 // Enter a scope to hold everything within the compound stmt. Compound
892 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000893 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000894
895 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000896 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000897}
898
Lang Hames2954cea2012-11-03 22:29:05 +0000899/// Parse any pragmas at the start of the compound expression. We handle these
900/// separately since some pragmas (FP_CONTRACT) must appear before any C
901/// statement in the compound, but may be intermingled with other pragmas.
902void Parser::ParseCompoundStatementLeadingPragmas() {
903 bool checkForPragmas = true;
904 while (checkForPragmas) {
905 switch (Tok.getKind()) {
906 case tok::annot_pragma_vis:
907 HandlePragmaVisibility();
908 break;
909 case tok::annot_pragma_pack:
910 HandlePragmaPack();
911 break;
912 case tok::annot_pragma_msstruct:
913 HandlePragmaMSStruct();
914 break;
915 case tok::annot_pragma_align:
916 HandlePragmaAlign();
917 break;
918 case tok::annot_pragma_weak:
919 HandlePragmaWeak();
920 break;
921 case tok::annot_pragma_weakalias:
922 HandlePragmaWeakAlias();
923 break;
924 case tok::annot_pragma_redefine_extname:
925 HandlePragmaRedefineExtname();
926 break;
927 case tok::annot_pragma_opencl_extension:
928 HandlePragmaOpenCLExtension();
929 break;
930 case tok::annot_pragma_fp_contract:
931 HandlePragmaFPContract();
932 break;
Adam Nemet60d32642017-04-04 21:18:36 +0000933 case tok::annot_pragma_fp:
934 HandlePragmaFP();
935 break;
Kevin P. Neal2c0bc8b2018-08-14 17:06:56 +0000936 case tok::annot_pragma_fenv_access:
937 HandlePragmaFEnvAccess();
938 break;
David Majnemer4bb09802014-02-10 19:50:15 +0000939 case tok::annot_pragma_ms_pointers_to_members:
940 HandlePragmaMSPointersToMembers();
941 break;
Warren Huntc3b18962014-04-08 22:30:47 +0000942 case tok::annot_pragma_ms_pragma:
943 HandlePragmaMSPragma();
944 break;
Alexey Bataev3d42f342015-11-20 07:02:57 +0000945 case tok::annot_pragma_ms_vtordisp:
946 HandlePragmaMSVtorDisp();
947 break;
Richard Smithba3a4f92016-01-12 21:59:26 +0000948 case tok::annot_pragma_dump:
949 HandlePragmaDump();
950 break;
Lang Hames2954cea2012-11-03 22:29:05 +0000951 default:
952 checkForPragmas = false;
953 break;
954 }
955 }
956
957}
958
Roman Lebedev377748f2018-11-20 18:59:05 +0000959/// Consume any extra semi-colons resulting in null statements,
960/// returning true if any tok::semi were consumed.
961bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
962 if (!Tok.is(tok::semi))
963 return false;
964
965 SourceLocation StartLoc = Tok.getLocation();
966 SourceLocation EndLoc;
967
968 while (Tok.is(tok::semi) && !Tok.hasLeadingEmptyMacro() &&
969 Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
970 EndLoc = Tok.getLocation();
971
972 // Don't just ConsumeToken() this tok::semi, do store it in AST.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000973 StmtResult R =
974 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
Roman Lebedev377748f2018-11-20 18:59:05 +0000975 if (R.isUsable())
976 Stmts.push_back(R.get());
977 }
978
979 // Did not consume any extra semi.
980 if (EndLoc.isInvalid())
981 return false;
982
983 Diag(StartLoc, diag::warn_null_statement)
984 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
985 return true;
986}
987
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000988StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
989 bool IsStmtExprResult = false;
990 if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
Aaron Ballmanb1e511b2019-07-09 15:02:07 +0000991 // For GCC compatibility we skip past NullStmts.
992 unsigned LookAhead = 0;
993 while (GetLookAheadToken(LookAhead).is(tok::semi)) {
994 ++LookAhead;
995 }
996 // Then look to see if the next two tokens close the statement expression;
997 // if so, this expression statement is the last statement in a statment
998 // expression.
999 IsStmtExprResult = GetLookAheadToken(LookAhead).is(tok::r_brace) &&
1000 GetLookAheadToken(LookAhead + 1).is(tok::r_paren);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001001 }
Richard Smitha6e8d5e2019-02-15 00:27:53 +00001002
1003 if (IsStmtExprResult)
1004 E = Actions.ActOnStmtExprResult(E);
1005 return Actions.ActOnExprStmt(E, /*DiscardedValue=*/!IsStmtExprResult);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001006}
1007
Chris Lattnerf2978802007-01-21 06:52:16 +00001008/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +00001009/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +00001010/// consume the '}' at the end of the block. It does not manipulate the scope
1011/// stack.
John McCalldadc5752010-08-24 06:29:42 +00001012StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +00001013 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +00001014 Tok.getLocation(),
1015 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +00001016
1017 // Record the state of the FP_CONTRACT pragma, restore on leaving the
1018 // compound statement.
1019 Sema::FPContractStateRAII SaveFPContractState(Actions);
1020
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001021 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001022 BalancedDelimiterTracker T(*this, tok::l_brace);
1023 if (T.consumeOpen())
1024 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +00001025
Richard Smith6eb9b9e2018-02-03 00:44:57 +00001026 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001027
Lang Hames2954cea2012-11-03 22:29:05 +00001028 // Parse any pragmas at the beginning of the compound statement.
1029 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +00001030
Lang Hames2954cea2012-11-03 22:29:05 +00001031 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +00001032
Chris Lattner43e7f312011-02-18 02:08:43 +00001033 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1034 // only allowed at the start of a compound stmt regardless of the language.
1035 while (Tok.is(tok::kw___label__)) {
1036 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001037
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001038 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +00001039 while (1) {
1040 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001041 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner43e7f312011-02-18 02:08:43 +00001042 break;
1043 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001044
Chris Lattner43e7f312011-02-18 02:08:43 +00001045 IdentifierInfo *II = Tok.getIdentifierInfo();
1046 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +00001047 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001048
Alp Tokerec543272013-12-24 09:48:30 +00001049 if (!TryConsumeToken(tok::comma))
Chris Lattner43e7f312011-02-18 02:08:43 +00001050 break;
Chris Lattner43e7f312011-02-18 02:08:43 +00001051 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001052
John McCall084e83d2011-03-24 11:26:52 +00001053 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +00001054 DeclGroupPtrTy Res =
1055 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +00001056 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001057
Chris Lattner02f1b612012-04-28 16:12:17 +00001058 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +00001059 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001060 Stmts.push_back(R.get());
Chris Lattner43e7f312011-02-18 02:08:43 +00001061 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001062
Richard Smitha6e8d5e2019-02-15 00:27:53 +00001063 ParsedStmtContext SubStmtCtx =
1064 ParsedStmtContext::Compound |
1065 (isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());
1066
Richard Smith752ada82015-11-17 23:32:01 +00001067 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
1068 Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +00001069 if (Tok.is(tok::annot_pragma_unused)) {
1070 HandlePragmaUnused();
1071 continue;
1072 }
1073
Roman Lebedev377748f2018-11-20 18:59:05 +00001074 if (ConsumeNullStmt(Stmts))
1075 continue;
1076
John McCalldadc5752010-08-24 06:29:42 +00001077 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001078 if (Tok.isNot(tok::kw___extension__)) {
Richard Smitha6e8d5e2019-02-15 00:27:53 +00001079 R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001080 } else {
1081 // __extension__ can start declarations and it can also be a unary
1082 // operator for expressions. Consume multiple __extension__ markers here
1083 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +00001084 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001085 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001086 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001087 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +00001088
John McCall084e83d2011-03-24 11:26:52 +00001089 ParsedAttributesWithRange attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00001090 MaybeParseCXX11Attributes(attrs, nullptr,
1091 /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +00001092
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001093 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +00001094 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +00001095 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +00001096 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +00001097 ExtensionRAIIObject O(Diags);
1098
Chris Lattner49836b42009-04-02 04:16:50 +00001099 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +00001100 DeclGroupPtrTy Res =
1101 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001102 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001103 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +00001104 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +00001105 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +00001106
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001107 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001108 SkipUntil(tok::semi);
1109 continue;
1110 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +00001111
Chris Lattner1ff6e732008-10-20 06:51:33 +00001112 // Eat the semicolon at the end of stmt and convert the expr into a
1113 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +00001114 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smitha6e8d5e2019-02-15 00:27:53 +00001115 R = handleExprStmt(Res, SubStmtCtx);
1116 if (R.isUsable())
1117 R = Actions.ProcessStmtAttributes(R.get(), attrs, attrs.Range);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001118 }
1119 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001120
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001121 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001122 Stmts.push_back(R.get());
Chris Lattner30f910e2006-10-16 05:52:41 +00001123 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001124
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001125 SourceLocation CloseLoc = Tok.getLocation();
1126
Chris Lattner0ccd51e2006-08-09 05:47:47 +00001127 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +00001128 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001129 // Recover by creating a compound statement with what we parsed so far,
1130 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +00001131 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001132
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001133 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001134 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +00001135}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001136
Chris Lattnerc0081db2008-12-12 06:31:07 +00001137/// ParseParenExprOrCondition:
1138/// [C ] '(' expression ')'
Richard Smithc7a05a92016-06-29 21:17:59 +00001139/// [C++] '(' condition ')'
1140/// [C++1z] '(' init-statement[opt] condition ')'
Chris Lattnerc0081db2008-12-12 06:31:07 +00001141///
1142/// This function parses and performs error recovery on the specified condition
1143/// or expression (depending on whether we're in C++ or C mode). This function
1144/// goes out of its way to recover well. It returns true if there was a parser
1145/// error (the right paren couldn't be found), which indicates that the caller
1146/// should try to recover harder. It returns false if the condition is
1147/// successfully parsed. Note that a successful parse can still have semantic
1148/// errors in the condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001149bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1150 Sema::ConditionResult &Cond,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001151 SourceLocation Loc,
Richard Smith03a4aa32016-06-23 19:02:52 +00001152 Sema::ConditionKind CK) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001153 BalancedDelimiterTracker T(*this, tok::l_paren);
1154 T.consumeOpen();
1155
David Blaikiebbafb8a2012-03-11 07:00:24 +00001156 if (getLangOpts().CPlusPlus)
Richard Smithc7a05a92016-06-29 21:17:59 +00001157 Cond = ParseCXXCondition(InitStmt, Loc, CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001158 else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001159 ExprResult CondExpr = ParseExpression();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001160
Douglas Gregore60e41a2010-05-06 17:25:47 +00001161 // If required, convert to a boolean value.
Richard Smith03a4aa32016-06-23 19:02:52 +00001162 if (CondExpr.isInvalid())
1163 Cond = Sema::ConditionError();
1164 else
1165 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001166 }
Mike Stump11289f42009-09-09 15:08:12 +00001167
Chris Lattnerc0081db2008-12-12 06:31:07 +00001168 // If the parser was confused by the condition and we don't have a ')', try to
1169 // recover by skipping ahead to a semi and bailing out. If condexp is
1170 // semantically invalid but we have well formed code, keep going.
Richard Smith03a4aa32016-06-23 19:02:52 +00001171 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +00001172 SkipUntil(tok::semi);
1173 // Skipping may have stopped if it found the containing ')'. If so, we can
1174 // continue parsing the if statement.
1175 if (Tok.isNot(tok::r_paren))
1176 return true;
1177 }
Mike Stump11289f42009-09-09 15:08:12 +00001178
Chris Lattnerc0081db2008-12-12 06:31:07 +00001179 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001180 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +00001181
Chris Lattner70d44982012-04-28 16:24:20 +00001182 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1183 // that all callers are looking for a statement after the condition, so ")"
1184 // isn't valid.
1185 while (Tok.is(tok::r_paren)) {
1186 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1187 << FixItHint::CreateRemoval(Tok.getLocation());
1188 ConsumeParen();
1189 }
Chad Rosier67055f52012-07-10 21:35:27 +00001190
Chris Lattnerc0081db2008-12-12 06:31:07 +00001191 return false;
1192}
1193
1194
Chris Lattnerc951dae2006-08-10 04:23:57 +00001195/// ParseIfStatement
1196/// if-statement: [C99 6.8.4.1]
1197/// 'if' '(' expression ')' statement
1198/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001199/// [C++] 'if' '(' condition ')' statement
1200/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +00001201///
Richard Smithc202b282012-04-14 00:33:13 +00001202StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001203 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001204 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +00001205
Richard Smithb130fe72016-06-23 19:16:49 +00001206 bool IsConstexpr = false;
1207 if (Tok.is(tok::kw_constexpr)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001208 Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
Richard Smithb130fe72016-06-23 19:16:49 +00001209 : diag::ext_constexpr_if);
1210 IsConstexpr = true;
1211 ConsumeToken();
1212 }
1213
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001214 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001215 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +00001216 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +00001217 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +00001218 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001219
David Blaikiebbafb8a2012-03-11 07:00:24 +00001220 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001221
Chris Lattner2dd1b722007-08-26 23:08:06 +00001222 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1223 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001224 //
1225 // C++ 6.4p3:
1226 // A name introduced by a declaration in a condition is in scope from its
1227 // point of declaration until the end of the substatements controlled by the
1228 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001229 // C++ 3.3.2p4:
1230 // Names declared in the for-init-statement, and in the condition of if,
1231 // while, for, and switch statements are local to the if, while, for, or
1232 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001233 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001234 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001235
Chris Lattnerc951dae2006-08-10 04:23:57 +00001236 // Parse the condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001237 StmtResult InitStmt;
Richard Smith03a4aa32016-06-23 19:02:52 +00001238 Sema::ConditionResult Cond;
Richard Smithc7a05a92016-06-29 21:17:59 +00001239 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
Richard Smithb130fe72016-06-23 19:16:49 +00001240 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1241 : Sema::ConditionKind::Boolean))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001242 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001243
Richard Smithb130fe72016-06-23 19:16:49 +00001244 llvm::Optional<bool> ConstexprCondition;
1245 if (IsConstexpr)
1246 ConstexprCondition = Cond.getKnownValue();
1247
Chris Lattner8fb26252007-08-22 05:28:50 +00001248 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001249 // there is no compound stmt. C90 does not have this clause. We only do this
1250 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001251 //
1252 // C++ 6.4p1:
1253 // The substatement in a selection-statement (each substatement, in the else
1254 // form of the if statement) implicitly defines a local scope.
1255 //
1256 // For C++ we create a scope for the condition and a new scope for
1257 // substatements because:
1258 // -When the 'then' scope exits, we want the condition declaration to still be
1259 // active for the 'else' scope too.
1260 // -Sema will detect name clashes by considering declarations of a
1261 // 'ControlScope' as part of its direct subscope.
1262 // -If we wanted the condition and substatement to be in the same scope, we
1263 // would have to notify ParseStatement not to create a new scope. It's
1264 // simpler to let it create a new scope.
1265 //
David Majnemer2206bf52014-03-05 08:57:59 +00001266 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001267
Chris Lattner5c5808a2007-10-29 05:08:52 +00001268 // Read the 'then' stmt.
1269 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001270
1271 SourceLocation InnerStatementTrailingElseLoc;
Richard Smithb130fe72016-06-23 19:16:49 +00001272 StmtResult ThenStmt;
1273 {
1274 EnterExpressionEvaluationContext PotentiallyDiscarded(
Faisal Valid143a0c2017-04-01 21:30:49 +00001275 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00001276 Sema::ExpressionEvaluationContextRecord::EK_Other,
Richard Smithb130fe72016-06-23 19:16:49 +00001277 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1278 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1279 }
Chris Lattnerac4471c2007-05-28 05:38:24 +00001280
Chris Lattner37e54f42007-08-22 05:16:28 +00001281 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001282 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001283
Chris Lattnerc951dae2006-08-10 04:23:57 +00001284 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001285 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001286 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001287 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001288
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001289 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001290 if (TrailingElseLoc)
1291 *TrailingElseLoc = Tok.getLocation();
1292
Chris Lattneraf635312006-10-16 06:06:51 +00001293 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001294 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001295
Chris Lattner8fb26252007-08-22 05:28:50 +00001296 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001297 // there is no compound stmt. C90 does not have this clause. We only do
1298 // this if the body isn't a compound statement to avoid push/pop in common
1299 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001300 //
1301 // C++ 6.4p1:
1302 // The substatement in a selection-statement (each substatement, in the else
1303 // form of the if statement) implicitly defines a local scope.
1304 //
Richard Smithb130fe72016-06-23 19:16:49 +00001305 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1306 Tok.is(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001307
Richard Smithb130fe72016-06-23 19:16:49 +00001308 EnterExpressionEvaluationContext PotentiallyDiscarded(
Faisal Valid143a0c2017-04-01 21:30:49 +00001309 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00001310 Sema::ExpressionEvaluationContextRecord::EK_Other,
Richard Smithb130fe72016-06-23 19:16:49 +00001311 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
Chris Lattner30f910e2006-10-16 05:52:41 +00001312 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001313
Chris Lattner37e54f42007-08-22 05:16:28 +00001314 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001315 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001316 } else if (Tok.is(tok::code_completion)) {
1317 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001318 cutOffParsing();
1319 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001320 } else if (InnerStatementTrailingElseLoc.isValid()) {
1321 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001322 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001323
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001324 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattner5c5808a2007-10-29 05:08:52 +00001326 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001327 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001328 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001329 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
Craig Topper161e4db2014-05-21 06:02:52 +00001330 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1331 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001332 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001333 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001334 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001335
Chris Lattner5c5808a2007-10-29 05:08:52 +00001336 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001337 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001338 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001339 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001340 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001341
Richard Smithc7a05a92016-06-29 21:17:59 +00001342 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1343 ThenStmt.get(), ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001344}
1345
Chris Lattner9075bd72006-08-10 04:59:57 +00001346/// ParseSwitchStatement
1347/// switch-statement:
1348/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001349/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001350StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001351 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001352 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001353
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001354 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001355 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001356 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001357 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001358 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001359
David Blaikiebbafb8a2012-03-11 07:00:24 +00001360 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001361
Chris Lattner2dd1b722007-08-26 23:08:06 +00001362 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1363 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001364 //
1365 // C++ 6.4p3:
1366 // A name introduced by a declaration in a condition is in scope from its
1367 // point of declaration until the end of the substatements controlled by the
1368 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001369 // C++ 3.3.2p4:
1370 // Names declared in the for-init-statement, and in the condition of if,
1371 // while, for, and switch statements are local to the if, while, for, or
1372 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001373 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001374 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001375 if (C99orCXX)
1376 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001377 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001378
Chris Lattner9075bd72006-08-10 04:59:57 +00001379 // Parse the condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001380 StmtResult InitStmt;
Richard Smith03a4aa32016-06-23 19:02:52 +00001381 Sema::ConditionResult Cond;
Richard Smithc7a05a92016-06-29 21:17:59 +00001382 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1383 Sema::ConditionKind::Switch))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001384 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001385
Richard Smithc7a05a92016-06-29 21:17:59 +00001386 StmtResult Switch =
1387 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001388
Douglas Gregore60e41a2010-05-06 17:25:47 +00001389 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001390 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001391 // FIXME: This is not optimal recovery, but parsing the body is more
1392 // dangerous due to the presence of case and default statements, which
1393 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001394 if (Tok.is(tok::l_brace)) {
1395 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001396 SkipUntil(tok::r_brace);
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001397 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001398 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001399 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001400 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001401
Chris Lattner8fb26252007-08-22 05:28:50 +00001402 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001403 // there is no compound stmt. C90 does not have this clause. We only do this
1404 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001405 //
1406 // C++ 6.4p1:
1407 // The substatement in a selection-statement (each substatement, in the else
1408 // form of the if statement) implicitly defines a local scope.
1409 //
1410 // See comments in ParseIfStatement for why we create a scope for the
1411 // condition and a new scope for substatement in C++.
1412 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001413 getCurScope()->AddFlags(Scope::BreakScope);
David Majnemer2206bf52014-03-05 08:57:59 +00001414 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001415
Hans Wennborg852c3462014-06-17 00:09:05 +00001416 // We have incremented the mangling number for the SwitchScope and the
1417 // InnerScope, which is one too many.
1418 if (C99orCXX)
David Majnemera7f8c462015-03-19 21:54:30 +00001419 getCurScope()->decrementMSManglingNumber();
Hans Wennborg852c3462014-06-17 00:09:05 +00001420
Chris Lattner9075bd72006-08-10 04:59:57 +00001421 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001422 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001423
Chris Lattner8fd2d012010-01-24 01:50:29 +00001424 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001425 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001426 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001427
John McCallb268a282010-08-23 23:25:46 +00001428 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001429}
1430
1431/// ParseWhileStatement
1432/// while-statement: [C99 6.8.5.1]
1433/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001434/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001435StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001436 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001437 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001438 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001439
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001440 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001441 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001442 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001443 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001444 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001445
David Blaikiebbafb8a2012-03-11 07:00:24 +00001446 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001447
Chris Lattner2dd1b722007-08-26 23:08:06 +00001448 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1449 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001450 //
1451 // C++ 6.4p3:
1452 // A name introduced by a declaration in a condition is in scope from its
1453 // point of declaration until the end of the substatements controlled by the
1454 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001455 // C++ 3.3.2p4:
1456 // Names declared in the for-init-statement, and in the condition of if,
1457 // while, for, and switch statements are local to the if, while, for, or
1458 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001459 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001460 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001461 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001462 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1463 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001464 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001465 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1466 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001467
Chris Lattner9075bd72006-08-10 04:59:57 +00001468 // Parse the condition.
Richard Smith03a4aa32016-06-23 19:02:52 +00001469 Sema::ConditionResult Cond;
Richard Smithc7a05a92016-06-29 21:17:59 +00001470 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1471 Sema::ConditionKind::Boolean))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001472 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001473
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001474 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001475 // there is no compound stmt. C90 does not have this clause. We only do this
1476 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001477 //
1478 // C++ 6.5p2:
1479 // The substatement in an iteration-statement implicitly defines a local scope
1480 // which is entered and exited each time through the loop.
1481 //
1482 // See comments in ParseIfStatement for why we create a scope for the
1483 // condition and a new scope for substatement in C++.
1484 //
David Majnemer2206bf52014-03-05 08:57:59 +00001485 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001486
Chris Lattner9075bd72006-08-10 04:59:57 +00001487 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001488 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001489
Chris Lattner8fb26252007-08-22 05:28:50 +00001490 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001491 InnerScope.Exit();
1492 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001493
Richard Smith03a4aa32016-06-23 19:02:52 +00001494 if (Cond.isInvalid() || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001495 return StmtError();
1496
Richard Smith03a4aa32016-06-23 19:02:52 +00001497 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001498}
1499
1500/// ParseDoStatement
1501/// do-statement: [C99 6.8.5.2]
1502/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001503/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001504StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001505 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001506 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001507
Chris Lattner2dd1b722007-08-26 23:08:06 +00001508 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1509 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001510 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001511 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001512 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001513 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001514 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001515
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001516 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001517
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001518 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001519 // there is no compound stmt. C90 does not have this clause. We only do this
1520 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001521 //
1522 // C++ 6.5p2:
1523 // The substatement in an iteration-statement implicitly defines a local scope
1524 // which is entered and exited each time through the loop.
1525 //
David Majnemer2206bf52014-03-05 08:57:59 +00001526 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1527 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001528
Chris Lattner9075bd72006-08-10 04:59:57 +00001529 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001530 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001531
Chris Lattner8fb26252007-08-22 05:28:50 +00001532 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001533 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001534
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001535 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001536 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001537 Diag(Tok, diag::err_expected_while);
Alp Tokerec543272013-12-24 09:48:30 +00001538 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001539 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner0046de12008-11-13 18:52:53 +00001540 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001541 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001542 }
Chris Lattneraf635312006-10-16 06:06:51 +00001543 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001544
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001545 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001546 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001547 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001548 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001549 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001550
Richard Smithc2c8bb82013-10-15 01:34:54 +00001551 // Parse the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001552 BalancedDelimiterTracker T(*this, tok::l_paren);
1553 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001554
Richard Smithc2c8bb82013-10-15 01:34:54 +00001555 // A do-while expression is not a condition, so can't have attributes.
1556 DiagnoseAndSkipCXX11Attributes();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001557
John McCalldadc5752010-08-24 06:29:42 +00001558 ExprResult Cond = ParseExpression();
Alex Lorenzc38ba662017-10-30 22:55:11 +00001559 // Correct the typos in condition before closing the scope.
1560 if (Cond.isUsable())
1561 Cond = Actions.CorrectDelayedTyposInExpr(Cond);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001562 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001563 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001564
Sebastian Redlb62406f2008-12-11 19:48:14 +00001565 if (Cond.isInvalid() || Body.isInvalid())
1566 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001567
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001568 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1569 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001570}
1571
Richard Smith955bf012014-06-19 11:42:00 +00001572bool Parser::isForRangeIdentifier() {
1573 assert(Tok.is(tok::identifier));
1574
1575 const Token &Next = NextToken();
1576 if (Next.is(tok::colon))
1577 return true;
1578
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001579 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
Richard Smith955bf012014-06-19 11:42:00 +00001580 TentativeParsingAction PA(*this);
1581 ConsumeToken();
1582 SkipCXX11Attributes();
1583 bool Result = Tok.is(tok::colon);
1584 PA.Revert();
1585 return Result;
1586 }
1587
1588 return false;
1589}
1590
Chris Lattner9075bd72006-08-10 04:59:57 +00001591/// ParseForStatement
1592/// for-statement: [C99 6.8.5.3]
1593/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1594/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001595/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1596/// [C++] statement
Richard Smith0e304ea2015-10-22 04:46:14 +00001597/// [C++0x] 'for'
1598/// 'co_await'[opt] [Coroutines]
1599/// '(' for-range-declaration ':' for-range-initializer ')'
1600/// statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001601/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1602/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001603///
1604/// [C++] for-init-statement:
1605/// [C++] expression-statement
1606/// [C++] simple-declaration
1607///
Richard Smith02e85f32011-04-14 22:09:26 +00001608/// [C++0x] for-range-declaration:
1609/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1610/// [C++0x] for-range-initializer:
1611/// [C++0x] expression
1612/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001613StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001614 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001615 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001616
Richard Smith0e304ea2015-10-22 04:46:14 +00001617 SourceLocation CoawaitLoc;
1618 if (Tok.is(tok::kw_co_await))
1619 CoawaitLoc = ConsumeToken();
1620
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001621 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001622 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001623 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001624 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001625 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001626
Chad Rosier67055f52012-07-10 21:35:27 +00001627 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
Erik Pilkingtonfa983902018-10-30 20:31:30 +00001628 getLangOpts().ObjC;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001629
Chris Lattner2dd1b722007-08-26 23:08:06 +00001630 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1631 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001632 //
1633 // C++ 6.4p3:
1634 // A name introduced by a declaration in a condition is in scope from its
1635 // point of declaration until the end of the substatements controlled by the
1636 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001637 // C++ 3.3.2p4:
1638 // Names declared in the for-init-statement, and in the condition of if,
1639 // while, for, and switch statements are local to the if, while, for, or
1640 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001641 // C++ 6.5.3p1:
1642 // Names declared in the for-init-statement are in the same declarative-region
1643 // as those declared in the condition.
1644 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001645 unsigned ScopeFlags = 0;
Chris Lattner934074c2009-04-22 00:54:41 +00001646 if (C99orCXXorObjC)
Serge Pavlov09f99242014-01-23 15:05:00 +00001647 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001648
1649 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001650
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001651 BalancedDelimiterTracker T(*this, tok::l_paren);
1652 T.consumeOpen();
1653
John McCalldadc5752010-08-24 06:29:42 +00001654 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001655
Richard Smith8baa5002018-09-28 18:44:09 +00001656 bool ForEach = false;
John McCalldadc5752010-08-24 06:29:42 +00001657 StmtResult FirstPart;
Richard Smith03a4aa32016-06-23 19:02:52 +00001658 Sema::ConditionResult SecondPart;
John McCalldadc5752010-08-24 06:29:42 +00001659 ExprResult Collection;
Richard Smith8baa5002018-09-28 18:44:09 +00001660 ForRangeInfo ForRangeInfo;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001661 FullExprArg ThirdPart(Actions);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001662
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001663 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001664 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001665 C99orCXXorObjC? Sema::PCC_ForInit
1666 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001667 cutOffParsing();
1668 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001669 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001670
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001671 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001672 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001673
Roman Lebedev377748f2018-11-20 18:59:05 +00001674 SourceLocation EmptyInitStmtSemiLoc;
1675
Chris Lattner9075bd72006-08-10 04:59:57 +00001676 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001677 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001678 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001679 // no first part, eat the ';'.
Roman Lebedev377748f2018-11-20 18:59:05 +00001680 SourceLocation SemiLoc = Tok.getLocation();
1681 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
1682 EmptyInitStmtSemiLoc = SemiLoc;
Chris Lattner53361ac2006-08-10 05:19:57 +00001683 ConsumeToken();
Richard Smith955bf012014-06-19 11:42:00 +00001684 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1685 isForRangeIdentifier()) {
1686 ProhibitAttributes(attrs);
1687 IdentifierInfo *Name = Tok.getIdentifierInfo();
1688 SourceLocation Loc = ConsumeToken();
1689 MaybeParseCXX11Attributes(attrs);
1690
Richard Smith8baa5002018-09-28 18:44:09 +00001691 ForRangeInfo.ColonLoc = ConsumeToken();
Richard Smith955bf012014-06-19 11:42:00 +00001692 if (Tok.is(tok::l_brace))
Richard Smith8baa5002018-09-28 18:44:09 +00001693 ForRangeInfo.RangeExpr = ParseBraceInitializer();
Richard Smith955bf012014-06-19 11:42:00 +00001694 else
Richard Smith8baa5002018-09-28 18:44:09 +00001695 ForRangeInfo.RangeExpr = ParseExpression();
Richard Smith955bf012014-06-19 11:42:00 +00001696
Richard Smith83d3f152014-11-27 01:54:27 +00001697 Diag(Loc, diag::err_for_range_identifier)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001698 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
Richard Smith955bf012014-06-19 11:42:00 +00001699 ? FixItHint::CreateInsertion(Loc, "auto &&")
1700 : FixItHint());
1701
Richard Smith8baa5002018-09-28 18:44:09 +00001702 ForRangeInfo.LoopVar = Actions.ActOnCXXForRangeIdentifier(
1703 getCurScope(), Loc, Name, attrs, attrs.Range.getEnd());
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001704 } else if (isForInitDeclaration()) { // for (int X = 4;
Richard Smithbf5bcf22018-06-26 23:20:26 +00001705 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1706
Chris Lattner53361ac2006-08-10 05:19:57 +00001707 // Parse declaration, which eats the ';'.
George Burgess IV4d456452018-06-28 21:36:00 +00001708 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001709 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
George Burgess IV4d456452018-06-28 21:36:00 +00001710 Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
1711 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001712
Richard Smith02e85f32011-04-14 22:09:26 +00001713 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001714 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001715 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1716
Chris Lattner49836b42009-04-02 04:16:50 +00001717 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00001718 DeclGroupPtrTy DG = ParseSimpleDeclaration(
Faisal Vali421b2d12017-12-29 05:41:00 +00001719 DeclaratorContext::ForContext, DeclEnd, attrs, false,
Richard Smith8baa5002018-09-28 18:44:09 +00001720 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001721 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Richard Smith8baa5002018-09-28 18:44:09 +00001722 if (ForRangeInfo.ParsedForRangeDecl()) {
1723 Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001724 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8baa5002018-09-28 18:44:09 +00001725 ForRangeInfo.LoopVar = FirstPart;
1726 FirstPart = StmtResult();
Richard Smith02e85f32011-04-14 22:09:26 +00001727 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001728 ConsumeToken();
1729 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001730 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001731 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001732 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001733
Douglas Gregor68762e72010-08-23 21:17:50 +00001734 if (Tok.is(tok::code_completion)) {
1735 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001736 cutOffParsing();
1737 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001738 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001739 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001740 } else {
1741 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001742 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001743 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001744 ProhibitAttributes(attrs);
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001745 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Chris Lattner71e23ce2006-11-04 20:18:38 +00001746
John McCall34376a62010-12-04 03:47:34 +00001747 ForEach = isTokIdentifier_in();
1748
Chris Lattnercd68f642007-06-27 01:06:29 +00001749 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001750 if (!Value.isInvalid()) {
1751 if (ForEach)
1752 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001753 else {
1754 // We already know this is not an init-statement within a for loop, so
1755 // if we are parsing a C++11 range-based for loop, we should treat this
1756 // expression statement as being a discarded value expression because
1757 // we will err below. This way we do not warn on an unused expression
1758 // that was an error in the first place, like with: for (expr : expr);
1759 bool IsRangeBasedFor =
1760 getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon);
1761 FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
1762 }
John McCall34376a62010-12-04 03:47:34 +00001763 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001764
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001765 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001766 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001767 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001768 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001769
Douglas Gregor68762e72010-08-23 21:17:50 +00001770 if (Tok.is(tok::code_completion)) {
David Blaikie0403cb12016-01-15 23:43:25 +00001771 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001772 cutOffParsing();
1773 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001774 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001775 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001776 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001777 // User tried to write the reasonable, but ill-formed, for-range-statement
1778 // for (expr : expr) { ... }
1779 Diag(Tok, diag::err_for_range_expected_decl)
1780 << FirstPart.get()->getSourceRange();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001781 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smith03a4aa32016-06-23 19:02:52 +00001782 SecondPart = Sema::ConditionError();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001783 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001784 if (!Value.isInvalid()) {
1785 Diag(Tok, diag::err_expected_semi_for);
1786 } else {
1787 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001788 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001789 if (Tok.is(tok::semi))
1790 ConsumeToken();
1791 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001792 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001793 }
Serge Pavlov09f99242014-01-23 15:05:00 +00001794
1795 // Parse the second part of the for specifier.
1796 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smith8baa5002018-09-28 18:44:09 +00001797 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
1798 !SecondPart.isInvalid()) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001799 // Parse the second part of the for specifier.
1800 if (Tok.is(tok::semi)) { // for (...;;
1801 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001802 } else if (Tok.is(tok::r_paren)) {
1803 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001804 } else {
Richard Smith8baa5002018-09-28 18:44:09 +00001805 if (getLangOpts().CPlusPlus) {
1806 // C++2a: We've parsed an init-statement; we might have a
1807 // for-range-declaration next.
1808 bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
1809 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
Richard Smithc7a05a92016-06-29 21:17:59 +00001810 SecondPart =
Richard Smith8baa5002018-09-28 18:44:09 +00001811 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean,
1812 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
1813
1814 if (ForRangeInfo.ParsedForRangeDecl()) {
1815 Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
1816 : ForRangeInfo.ColonLoc,
1817 getLangOpts().CPlusPlus2a
1818 ? diag::warn_cxx17_compat_for_range_init_stmt
1819 : diag::ext_for_range_init_stmt)
1820 << (FirstPart.get() ? FirstPart.get()->getSourceRange()
1821 : SourceRange());
Roman Lebedev377748f2018-11-20 18:59:05 +00001822 if (EmptyInitStmtSemiLoc.isValid()) {
1823 Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
1824 << /*for-loop*/ 2
1825 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
1826 }
Richard Smith8baa5002018-09-28 18:44:09 +00001827 }
1828 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001829 ExprResult SecondExpr = ParseExpression();
1830 if (SecondExpr.isInvalid())
1831 SecondPart = Sema::ConditionError();
1832 else
1833 SecondPart =
1834 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1835 Sema::ConditionKind::Boolean);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001836 }
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001837 }
Richard Smith8baa5002018-09-28 18:44:09 +00001838 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001839
Richard Smith8baa5002018-09-28 18:44:09 +00001840 // Parse the third part of the for statement.
1841 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001842 if (Tok.isNot(tok::semi)) {
Richard Smith03a4aa32016-06-23 19:02:52 +00001843 if (!SecondPart.isInvalid())
Douglas Gregor230a7e62011-02-17 03:38:46 +00001844 Diag(Tok, diag::err_expected_semi_for);
1845 else
1846 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001847 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001848 }
1849
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001850 if (Tok.is(tok::semi)) {
1851 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001852 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001853
Douglas Gregore60e41a2010-05-06 17:25:47 +00001854 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001855 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001856 // FIXME: The C++11 standard doesn't actually say that this is a
1857 // discarded-value expression, but it clearly should be.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001858 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001859 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001860 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001861 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001862 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001863
Richard Smith0e304ea2015-10-22 04:46:14 +00001864 // C++ Coroutines [stmt.iter]:
1865 // 'co_await' can only be used for a range-based for statement.
Richard Smith8baa5002018-09-28 18:44:09 +00001866 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
Richard Smith0e304ea2015-10-22 04:46:14 +00001867 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1868 CoawaitLoc = SourceLocation();
1869 }
1870
Richard Smith02e85f32011-04-14 22:09:26 +00001871 // We need to perform most of the semantic analysis for a C++0x for-range
1872 // statememt before parsing the body, in order to be able to deduce the type
1873 // of an auto-typed loop variable.
1874 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001875 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001876
Richard Smith8baa5002018-09-28 18:44:09 +00001877 if (ForRangeInfo.ParsedForRangeDecl()) {
Denis Zobnin7d6b9242016-02-02 17:33:09 +00001878 ExprResult CorrectedRange =
Richard Smith8baa5002018-09-28 18:44:09 +00001879 Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());
Richard Smith9f690bd2015-10-27 06:02:45 +00001880 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1881 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
Richard Smith8baa5002018-09-28 18:44:09 +00001882 ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00001883 T.getCloseLocation(), Sema::BFRK_Build);
John McCall53848232011-07-27 01:07:15 +00001884
1885 // Similarly, we need to do the semantic analysis for a for-range
1886 // statement immediately in order to close over temporaries correctly.
1887 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001888 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001889 FirstPart.get(),
1890 Collection.get(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001891 T.getCloseLocation());
Alexey Bataev9c821032015-04-30 04:23:23 +00001892 } else {
1893 // In OpenMP loop region loop control variable must be captured and be
1894 // private. Perform analysis of first part (if any).
1895 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1896 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1897 }
John McCall53848232011-07-27 01:07:15 +00001898 }
1899
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001900 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001901 // there is no compound stmt. C90 does not have this clause. We only do this
1902 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001903 //
1904 // C++ 6.5p2:
1905 // The substatement in an iteration-statement implicitly defines a local scope
1906 // which is entered and exited each time through the loop.
1907 //
1908 // See comments in ParseIfStatement for why we create a scope for
1909 // for-init-statement/condition and a new scope for substatement in C++.
1910 //
David Majnemer2206bf52014-03-05 08:57:59 +00001911 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1912 Tok.is(tok::l_brace));
1913
1914 // The body of the for loop has the same local mangling number as the
1915 // for-init-statement.
1916 // It will only be incremented if the body contains other things that would
1917 // normally increment the mangling number (like a compound statement).
1918 if (C99orCXXorObjC)
David Majnemera7f8c462015-03-19 21:54:30 +00001919 getCurScope()->decrementMSManglingNumber();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001920
Chris Lattner9075bd72006-08-10 04:59:57 +00001921 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001922 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001923
Chris Lattner8fb26252007-08-22 05:28:50 +00001924 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001925 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001926
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001927 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001928 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001929
1930 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001931 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001932
Richard Smith02e85f32011-04-14 22:09:26 +00001933 if (ForEach)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001934 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1935 Body.get());
Mike Stump11289f42009-09-09 15:08:12 +00001936
Richard Smith8baa5002018-09-28 18:44:09 +00001937 if (ForRangeInfo.ParsedForRangeDecl())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001938 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001939
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001940 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
Richard Smith03a4aa32016-06-23 19:02:52 +00001941 SecondPart, ThirdPart, T.getCloseLocation(),
1942 Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001943}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001944
Chris Lattner503fadc2006-08-10 05:45:44 +00001945/// ParseGotoStatement
1946/// jump-statement:
1947/// 'goto' identifier ';'
1948/// [GNU] 'goto' '*' expression ';'
1949///
1950/// Note: this lets the caller parse the end ';'.
1951///
Richard Smithc202b282012-04-14 00:33:13 +00001952StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001953 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001954 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001955
John McCalldadc5752010-08-24 06:29:42 +00001956 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001957 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001958 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1959 Tok.getLocation());
1960 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001961 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001962 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001963 // GNU indirect goto extension.
1964 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001965 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001966 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001967 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001968 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001969 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001970 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001971 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001972 } else {
Alp Tokerec543272013-12-24 09:48:30 +00001973 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001974 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001975 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001976
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001977 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001978}
1979
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001980/// ParseContinueStatement
1981/// jump-statement:
1982/// 'continue' ';'
1983///
1984/// Note: this lets the caller parse the end ';'.
1985///
Richard Smithc202b282012-04-14 00:33:13 +00001986StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001987 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001988 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001989}
1990
1991/// ParseBreakStatement
1992/// jump-statement:
1993/// 'break' ';'
1994///
1995/// Note: this lets the caller parse the end ';'.
1996///
Richard Smithc202b282012-04-14 00:33:13 +00001997StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001998 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001999 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00002000}
2001
Chris Lattner503fadc2006-08-10 05:45:44 +00002002/// ParseReturnStatement
2003/// jump-statement:
2004/// 'return' expression[opt] ';'
Richard Smith0e304ea2015-10-22 04:46:14 +00002005/// 'return' braced-init-list ';'
2006/// 'co_return' expression[opt] ';'
2007/// 'co_return' braced-init-list ';'
Richard Smithc202b282012-04-14 00:33:13 +00002008StmtResult Parser::ParseReturnStatement() {
Richard Smith0e304ea2015-10-22 04:46:14 +00002009 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
2010 "Not a return stmt!");
2011 bool IsCoreturn = Tok.is(tok::kw_co_return);
Chris Lattneraf635312006-10-16 06:06:51 +00002012 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00002013
John McCalldadc5752010-08-24 06:29:42 +00002014 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002015 if (Tok.isNot(tok::semi)) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00002016 if (!IsCoreturn)
2017 PreferredType.enterReturn(Actions, Tok.getLocation());
Richard Smith0e304ea2015-10-22 04:46:14 +00002018 // FIXME: Code completion for co_return.
2019 if (Tok.is(tok::code_completion) && !IsCoreturn) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00002020 Actions.CodeCompleteExpression(getCurScope(),
2021 PreferredType.get(Tok.getLocation()));
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002022 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002023 return StmtError();
2024 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002025
David Blaikiebbafb8a2012-03-11 07:00:24 +00002026 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00002027 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00002028 if (R.isUsable())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002029 Diag(R.get()->getBeginLoc(),
2030 getLangOpts().CPlusPlus11
2031 ? diag::warn_cxx98_compat_generalized_initializer_lists
2032 : diag::ext_generalized_initializer_lists)
2033 << R.get()->getSourceRange();
Douglas Gregore9e27d92011-03-11 23:10:44 +00002034 } else
Nico Weber3ce01c32015-01-04 08:07:54 +00002035 R = ParseExpression();
Serge Pavlovf79bd5c2013-12-04 03:51:59 +00002036 if (R.isInvalid()) {
2037 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002038 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00002039 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00002040 }
Richard Smithcfd53b42015-10-22 06:13:50 +00002041 if (IsCoreturn)
Eric Fiselier20f25cb2017-03-06 23:38:15 +00002042 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002043 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
Chris Lattner503fadc2006-08-10 05:45:44 +00002044}
Chris Lattner0116c472006-08-15 06:03:28 +00002045
Alexey Bataevc4fad652016-01-13 11:18:54 +00002046StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
Richard Smitha6e8d5e2019-02-15 00:27:53 +00002047 ParsedStmtContext StmtCtx,
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002048 SourceLocation *TrailingElseLoc,
2049 ParsedAttributesWithRange &Attrs) {
2050 // Create temporary attribute list.
2051 ParsedAttributesWithRange TempAttrs(AttrFactory);
2052
Mark Heffernanbd26f5e2014-07-21 18:08:34 +00002053 // Get loop hints and consume annotated token.
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002054 while (Tok.is(tok::annot_pragma_loop_hint)) {
Tyler Nowicki0c9b34b2014-07-31 20:15:14 +00002055 LoopHint Hint;
2056 if (!HandlePragmaLoopHint(Hint))
2057 continue;
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002058
Tyler Nowicki0c9b34b2014-07-31 20:15:14 +00002059 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002060 ArgsUnion(Hint.ValueExpr)};
Mark Heffernanbd26f5e2014-07-21 18:08:34 +00002061 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
2062 Hint.PragmaNameLoc->Loc, ArgHints, 4,
Erich Keanee891aa92018-07-13 15:07:47 +00002063 ParsedAttr::AS_Pragma);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002064 }
2065
2066 // Get the next statement.
2067 MaybeParseCXX11Attributes(Attrs);
2068
2069 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
Richard Smitha6e8d5e2019-02-15 00:27:53 +00002070 Stmts, StmtCtx, TrailingElseLoc, Attrs);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002071
2072 Attrs.takeAllFrom(TempAttrs);
2073 return S;
2074}
2075
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002076Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002077 assert(Tok.is(tok::l_brace));
2078 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002079
Jordan Rose1e879d82018-03-23 00:07:18 +00002080 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00002081 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002082
Alexey Bataev3d42f342015-11-20 07:02:57 +00002083 // Save and reset current vtordisp stack if we have entered a C++ method body.
2084 bool IsCXXMethod =
2085 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
Denis Zobnin2290dac2016-04-29 11:27:00 +00002086 Sema::PragmaStackSentinelRAII
2087 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
Alexey Bataev3d42f342015-11-20 07:02:57 +00002088
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002089 // Do not enter a scope for the brace, as the arguments are in the same scope
2090 // (the function body) as the body itself. Instead, just read the statement
2091 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002092 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002093
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002094 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002095 if (FnBody.isInvalid()) {
2096 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002097 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002098 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002099
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002100 BodyScope.Exit();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002101 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002102}
Sebastian Redlb219c902008-12-21 16:41:36 +00002103
Sebastian Redla7b98a72009-04-26 20:35:05 +00002104/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2105///
2106/// function-try-block:
2107/// 'try' ctor-initializer[opt] compound-statement handler-seq
2108///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002109Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002110 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2111 SourceLocation TryLoc = ConsumeToken();
2112
Jordan Rose1e879d82018-03-23 00:07:18 +00002113 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00002114 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002115
2116 // Constructor initializer list?
2117 if (Tok.is(tok::colon))
2118 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002119 else
2120 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002121
Alexey Bataev3d42f342015-11-20 07:02:57 +00002122 // Save and reset current vtordisp stack if we have entered a C++ method body.
2123 bool IsCXXMethod =
2124 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
Denis Zobnin2290dac2016-04-29 11:27:00 +00002125 Sema::PragmaStackSentinelRAII
2126 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
Alexey Bataev3d42f342015-11-20 07:02:57 +00002127
Sebastian Redld98ecd62009-04-26 21:08:36 +00002128 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002129 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00002130 // If we failed to parse the try-catch, we just give the function an empty
2131 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002132 if (FnBody.isInvalid()) {
2133 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002134 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002135 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002136
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002137 BodyScope.Exit();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002138 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002139}
2140
Erik Verbruggen6e922512012-04-12 10:11:59 +00002141bool Parser::trySkippingFunctionBody() {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002142 assert(SkipFunctionBodies &&
2143 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002144 if (!PP.isCodeCompletionEnabled()) {
Olivier Goffartf9e890c2016-06-16 21:40:06 +00002145 SkipFunctionBody();
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002146 return true;
2147 }
2148
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002149 // We're in code-completion mode. Skip parsing for all function bodies unless
2150 // the body contains the code-completion point.
2151 TentativeParsingAction PA(*this);
Olivier Goffartf9e890c2016-06-16 21:40:06 +00002152 bool IsTryCatch = Tok.is(tok::kw_try);
2153 CachedTokens Toks;
2154 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2155 if (llvm::any_of(Toks, [](const Token &Tok) {
2156 return Tok.is(tok::code_completion);
2157 })) {
2158 PA.Revert();
2159 return false;
2160 }
2161 if (ErrorInPrologue) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002162 PA.Commit();
Olivier Goffartf9e890c2016-06-16 21:40:06 +00002163 SkipMalformedDecl();
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002164 return true;
2165 }
Olivier Goffartf9e890c2016-06-16 21:40:06 +00002166 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2167 PA.Revert();
2168 return false;
2169 }
2170 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2171 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2172 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2173 PA.Revert();
2174 return false;
2175 }
2176 }
2177 PA.Commit();
2178 return true;
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002179}
2180
Sebastian Redlb219c902008-12-21 16:41:36 +00002181/// ParseCXXTryBlock - Parse a C++ try-block.
2182///
2183/// try-block:
2184/// 'try' compound-statement handler-seq
2185///
Richard Smithc202b282012-04-14 00:33:13 +00002186StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002187 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2188
2189 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002190 return ParseCXXTryBlockCommon(TryLoc);
2191}
2192
2193/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2194/// function-try-block.
2195///
2196/// try-block:
2197/// 'try' compound-statement handler-seq
2198///
2199/// function-try-block:
2200/// 'try' ctor-initializer[opt] compound-statement handler-seq
2201///
2202/// handler-seq:
2203/// handler handler-seq[opt]
2204///
John Wiegley1c0675e2011-04-28 01:08:34 +00002205/// [Borland] try-block:
2206/// 'try' compound-statement seh-except-block
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002207/// 'try' compound-statement seh-finally-block
John Wiegley1c0675e2011-04-28 01:08:34 +00002208///
David Blaikie1c9c9042012-11-10 01:04:23 +00002209StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002210 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002211 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Richard Smithc202b282012-04-14 00:33:13 +00002212
Momchil Velikov57c681f2017-08-10 15:43:06 +00002213 StmtResult TryBlock(ParseCompoundStatement(
2214 /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2215 Scope::CompoundStmtScope |
2216 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002217 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002218 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002219
John Wiegley1c0675e2011-04-28 01:08:34 +00002220 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002221
Richard Smithc202b282012-04-14 00:33:13 +00002222 if ((Tok.is(tok::identifier) &&
2223 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2224 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002225 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2226 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002227 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002228 SourceLocation Loc = ConsumeToken();
2229 Handler = ParseSEHExceptBlock(Loc);
2230 }
2231 else {
2232 SourceLocation Loc = ConsumeToken();
2233 Handler = ParseSEHFinallyBlock(Loc);
2234 }
2235 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002236 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002237
John Wiegley1c0675e2011-04-28 01:08:34 +00002238 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2239 TryLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002240 TryBlock.get(),
Warren Huntf6be4cb2014-07-25 20:52:51 +00002241 Handler.get());
Sebastian Redlb219c902008-12-21 16:41:36 +00002242 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002243 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002244 StmtVector Handlers;
Richard Smithc2c8bb82013-10-15 01:34:54 +00002245
2246 // C++11 attributes can't appear here, despite this context seeming
2247 // statement-like.
2248 DiagnoseAndSkipCXX11Attributes();
Sebastian Redlb219c902008-12-21 16:41:36 +00002249
John Wiegley1c0675e2011-04-28 01:08:34 +00002250 if (Tok.isNot(tok::kw_catch))
2251 return StmtError(Diag(Tok, diag::err_expected_catch));
2252 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002253 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002254 if (!Handler.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002255 Handlers.push_back(Handler.get());
John Wiegley1c0675e2011-04-28 01:08:34 +00002256 }
2257 // Don't bother creating the full statement if we don't have any usable
2258 // handlers.
2259 if (Handlers.empty())
2260 return StmtError();
2261
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002262 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002263 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002264}
2265
2266/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2267///
Richard Smith1dba27c2013-01-29 09:02:09 +00002268/// handler:
2269/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002270///
Richard Smith1dba27c2013-01-29 09:02:09 +00002271/// exception-declaration:
2272/// attribute-specifier-seq[opt] type-specifier-seq declarator
2273/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2274/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002275///
David Blaikie1c9c9042012-11-10 01:04:23 +00002276StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002277 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2278
2279 SourceLocation CatchLoc = ConsumeToken();
2280
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002281 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002282 if (T.expectAndConsume())
Sebastian Redlb219c902008-12-21 16:41:36 +00002283 return StmtError();
2284
2285 // C++ 3.3.2p3:
2286 // The name in a catch exception-declaration is local to the handler and
2287 // shall not be redeclared in the outermost block of the handler.
Brian Gesiake8b3d632019-03-22 16:08:29 +00002288 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
Brian Gesiakb15c35a2019-03-25 00:53:10 +00002289 Scope::CatchScope |
2290 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002291
2292 // exception-declaration is equivalent to '...' or a parameter-declaration
2293 // without default arguments.
Craig Topper161e4db2014-05-21 06:02:52 +00002294 Decl *ExceptionDecl = nullptr;
Sebastian Redlb219c902008-12-21 16:41:36 +00002295 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002296 ParsedAttributesWithRange Attributes(AttrFactory);
2297 MaybeParseCXX11Attributes(Attributes);
2298
John McCall084e83d2011-03-24 11:26:52 +00002299 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002300 DS.takeAttributesFrom(Attributes);
2301
Sebastian Redl54c04d42008-12-22 19:15:10 +00002302 if (ParseCXXTypeSpecifierSeq(DS))
2303 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002304
Faisal Vali421b2d12017-12-29 05:41:00 +00002305 Declarator ExDecl(DS, DeclaratorContext::CXXCatchContext);
Sebastian Redlb219c902008-12-21 16:41:36 +00002306 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002307 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002308 } else
2309 ConsumeToken();
2310
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002311 T.consumeClose();
2312 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002313 return StmtError();
2314
2315 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002316 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redlb219c902008-12-21 16:41:36 +00002317
Alexis Hunt96d5c762009-11-21 08:43:09 +00002318 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Brian Gesiake8b3d632019-03-22 16:08:29 +00002319 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002320 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002321 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002322
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002323 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
Sebastian Redlb219c902008-12-21 16:41:36 +00002324}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002325
2326void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002327 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002328 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002329 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002330
Douglas Gregor43edb322011-10-24 22:31:10 +00002331 // Handle dependent statements by parsing the braces as a compound statement.
2332 // This is not the same behavior as Visual C++, which don't treat this as a
2333 // compound statement, but for Clang's type checking we can't have anything
2334 // inside these braces escaping to the surrounding code.
2335 if (Result.Behavior == IEB_Dependent) {
2336 if (!Tok.is(tok::l_brace)) {
Alp Tokerec543272013-12-24 09:48:30 +00002337 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smithc202b282012-04-14 00:33:13 +00002338 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002339 }
Richard Smithc202b282012-04-14 00:33:13 +00002340
2341 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002342 if (Compound.isInvalid())
2343 return;
Richard Smithc202b282012-04-14 00:33:13 +00002344
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002345 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2346 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002347 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002348 Result.Name,
2349 Compound.get());
2350 if (DepResult.isUsable())
2351 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002352 return;
2353 }
Richard Smithc202b282012-04-14 00:33:13 +00002354
Douglas Gregor43edb322011-10-24 22:31:10 +00002355 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2356 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00002357 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002358 return;
2359 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002360
Douglas Gregor43edb322011-10-24 22:31:10 +00002361 switch (Result.Behavior) {
2362 case IEB_Parse:
2363 // Parse the statements below.
2364 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002365
Douglas Gregor43edb322011-10-24 22:31:10 +00002366 case IEB_Dependent:
2367 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002368
Douglas Gregor43edb322011-10-24 22:31:10 +00002369 case IEB_Skip:
2370 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002371 return;
2372 }
2373
2374 // Condition is true, parse the statements.
2375 while (Tok.isNot(tok::r_brace)) {
Richard Smitha6e8d5e2019-02-15 00:27:53 +00002376 StmtResult R =
2377 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002378 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002379 Stmts.push_back(R.get());
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002380 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002381 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002382}
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00002383
2384bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2385 MaybeParseGNUAttributes(Attrs);
2386
2387 if (Attrs.empty())
2388 return true;
2389
Erich Keanee891aa92018-07-13 15:07:47 +00002390 if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00002391 return true;
2392
2393 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2394 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);
2395 return false;
2396 }
2397 return true;
2398}