blob: 267003b518936cbecb4b581044113e991bb44901 [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 {
119class StatementFilterCCC : public CorrectionCandidateCallback {
120public:
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
142private:
143 Token NextToken;
144};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000145}
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000146
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000147StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
148 StmtVector &Stmts, ParsedStmtContext StmtCtx,
149 SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs) {
Craig Topper161e4db2014-05-21 06:02:52 +0000150 const char *SemiError = nullptr;
Richard Smithc202b282012-04-14 00:33:13 +0000151 StmtResult Res;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000152
Chris Lattner503fadc2006-08-10 05:45:44 +0000153 // Cases in this switch statement should fall through if the parser expects
154 // the token to end in a semicolon (in which case SemiError should be set),
155 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000156Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000157 tok::TokenKind Kind = Tok.getKind();
158 SourceLocation AtLoc;
159 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000160 case tok::at: // May be a @try or @throw statement
161 {
Richard Smithc202b282012-04-14 00:33:13 +0000162 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000163 AtLoc = ConsumeToken(); // consume @
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000164 return ParseObjCAtStatement(AtLoc, StmtCtx);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000165 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000166
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000167 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000168 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000169 cutOffParsing();
170 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000171
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000172 case tok::identifier: {
173 Token Next = NextToken();
174 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000175 // identifier ':' statement
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000176 return ParseLabeledStatement(Attrs, StmtCtx);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000177 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000178
Richard Smith4f605af2012-08-18 00:55:03 +0000179 // Look up the identifier, and typo-correct it to a keyword if it's not
180 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000181 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000182 // Try to limit which sets of keywords should be included in typo
183 // correction based on what the next token is.
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000184 if (TryAnnotateName(/*IsAddressOfOperand*/ false,
185 llvm::make_unique<StatementFilterCCC>(Next)) ==
186 ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000187 // Handle errors here by skipping up to the next semicolon or '}', and
188 // eat the semicolon if that's what stopped us.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000189 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000190 if (Tok.is(tok::semi))
191 ConsumeToken();
192 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000193 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000194
Richard Smith4f605af2012-08-18 00:55:03 +0000195 // If the identifier was typo-corrected, try again.
196 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000197 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000198 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000199
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000200 // Fall through
Galina Kistanova387ab8b2017-06-01 21:28:26 +0000201 LLVM_FALLTHROUGH;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000202 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000203
Chris Lattner803802d2009-03-24 17:04:48 +0000204 default: {
David Majnemer6ac7dd12016-08-01 16:39:29 +0000205 if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000206 (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
207 ParsedStmtContext()) &&
Alexey Bataevc4fad652016-01-13 11:18:54 +0000208 isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000209 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +0000210 DeclGroupPtrTy Decl = ParseDeclaration(DeclaratorContext::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000211 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000212 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000213 }
214
215 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000216 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000217 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000218 }
Mike Stump11289f42009-09-09 15:08:12 +0000219
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000220 return ParseExprStatement(StmtCtx);
Chris Lattner803802d2009-03-24 17:04:48 +0000221 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000222
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000223 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000224 return ParseCaseStatement(StmtCtx);
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000225 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000226 return ParseDefaultStatement(StmtCtx);
Sebastian Redl042ad952008-12-11 19:30:53 +0000227
Chris Lattner9075bd72006-08-10 04:59:57 +0000228 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000229 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000230 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000231 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
232 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000233 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000234
Chris Lattner9075bd72006-08-10 04:59:57 +0000235 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000236 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000237 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000238 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000239
Chris Lattner9075bd72006-08-10 04:59:57 +0000240 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000241 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000242 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000243 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000244 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000245 break;
246 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000247 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000248
249 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000250 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000251 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000252 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000253 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000254 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000255 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000256 break;
257 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000258 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000259 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000260 break;
261 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000262 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000263 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000264 break;
Richard Smith0e304ea2015-10-22 04:46:14 +0000265 case tok::kw_co_return: // C++ Coroutines: co_return statement
266 Res = ParseReturnStatement();
267 SemiError = "co_return";
268 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000269
Sebastian Redlb219c902008-12-21 16:41:36 +0000270 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000271 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000272 bool msAsm = false;
273 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000274 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000275 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000276 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000277 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000278 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000279
Reid Kleckner6d8d22a2014-06-25 00:28:35 +0000280 case tok::kw___if_exists:
281 case tok::kw___if_not_exists:
282 ProhibitAttributes(Attrs);
283 ParseMicrosoftIfExistsStatement(Stmts);
284 // An __if_exists block is like a compound statement, but it doesn't create
285 // a new scope.
286 return StmtEmpty();
287
Sebastian Redlb219c902008-12-21 16:41:36 +0000288 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000289 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000290
291 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000292 ProhibitAttributes(Attrs); // TODO: is it correct?
293 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000294
Nico Weberc7d05962014-07-06 22:32:59 +0000295 case tok::kw___leave:
296 Res = ParseSEHLeaveStatement();
297 SemiError = "__leave";
298 break;
299
Eli Friedmanec52f922012-02-23 23:47:16 +0000300 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000301 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000302 HandlePragmaVisibility();
303 return StmtEmpty();
304
305 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000306 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000307 HandlePragmaPack();
308 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000309
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000310 case tok::annot_pragma_msstruct:
311 ProhibitAttributes(Attrs);
312 HandlePragmaMSStruct();
313 return StmtEmpty();
314
Eli Friedmanae8ee252012-10-08 23:52:38 +0000315 case tok::annot_pragma_align:
316 ProhibitAttributes(Attrs);
317 HandlePragmaAlign();
318 return StmtEmpty();
319
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000320 case tok::annot_pragma_weak:
321 ProhibitAttributes(Attrs);
322 HandlePragmaWeak();
323 return StmtEmpty();
324
325 case tok::annot_pragma_weakalias:
326 ProhibitAttributes(Attrs);
327 HandlePragmaWeakAlias();
328 return StmtEmpty();
329
330 case tok::annot_pragma_redefine_extname:
331 ProhibitAttributes(Attrs);
332 HandlePragmaRedefineExtname();
333 return StmtEmpty();
334
Eli Friedman68be1642012-10-04 02:36:51 +0000335 case tok::annot_pragma_fp_contract:
Richard Smithca9b0b62013-11-15 21:10:54 +0000336 ProhibitAttributes(Attrs);
Lang Hamesa930e712012-10-21 01:10:01 +0000337 Diag(Tok, diag::err_pragma_fp_contract_scope);
Richard Smithaf3b3252017-05-18 19:21:48 +0000338 ConsumeAnnotationToken();
Lang Hamesa930e712012-10-21 01:10:01 +0000339 return StmtError();
340
Adam Nemet60d32642017-04-04 21:18:36 +0000341 case tok::annot_pragma_fp:
342 ProhibitAttributes(Attrs);
343 Diag(Tok, diag::err_pragma_fp_scope);
Richard Smithaf3b3252017-05-18 19:21:48 +0000344 ConsumeAnnotationToken();
Adam Nemet60d32642017-04-04 21:18:36 +0000345 return StmtError();
346
Kevin P. Neal2c0bc8b2018-08-14 17:06:56 +0000347 case tok::annot_pragma_fenv_access:
348 ProhibitAttributes(Attrs);
349 HandlePragmaFEnvAccess();
350 return StmtEmpty();
351
Eli Friedman68be1642012-10-04 02:36:51 +0000352 case tok::annot_pragma_opencl_extension:
353 ProhibitAttributes(Attrs);
354 HandlePragmaOpenCLExtension();
355 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000356
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000357 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000358 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000359 return HandlePragmaCaptured();
360
Alexey Bataeva769e072013-03-22 06:34:35 +0000361 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000362 ProhibitAttributes(Attrs);
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000363 return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000364
David Majnemer4bb09802014-02-10 19:50:15 +0000365 case tok::annot_pragma_ms_pointers_to_members:
366 ProhibitAttributes(Attrs);
367 HandlePragmaMSPointersToMembers();
368 return StmtEmpty();
369
Warren Huntc3b18962014-04-08 22:30:47 +0000370 case tok::annot_pragma_ms_pragma:
371 ProhibitAttributes(Attrs);
372 HandlePragmaMSPragma();
373 return StmtEmpty();
Aaron Ballmanb06b15a2014-06-06 12:40:24 +0000374
Alexey Bataev3d42f342015-11-20 07:02:57 +0000375 case tok::annot_pragma_ms_vtordisp:
376 ProhibitAttributes(Attrs);
377 HandlePragmaMSVtorDisp();
378 return StmtEmpty();
379
Aaron Ballmanb06b15a2014-06-06 12:40:24 +0000380 case tok::annot_pragma_loop_hint:
381 ProhibitAttributes(Attrs);
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000382 return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, Attrs);
Richard Smithba3a4f92016-01-12 21:59:26 +0000383
384 case tok::annot_pragma_dump:
385 HandlePragmaDump();
386 return StmtEmpty();
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000387
388 case tok::annot_pragma_attribute:
389 HandlePragmaAttribute();
390 return StmtEmpty();
Sebastian Redlb219c902008-12-21 16:41:36 +0000391 }
392
Chris Lattner503fadc2006-08-10 05:45:44 +0000393 // If we reached this code, the statement must end in a semicolon.
Alp Toker97650562014-01-10 11:19:30 +0000394 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000395 // If the result was valid, then we do want to diagnose this. Use
396 // ExpectAndConsume to emit the diagnostic, even though we know it won't
397 // succeed.
398 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000399 // Skip until we see a } or ;, but don't eat it.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000400 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner503fadc2006-08-10 05:45:44 +0000401 }
Mike Stump11289f42009-09-09 15:08:12 +0000402
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000403 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000404}
405
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000406/// Parse an expression statement.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000407StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000408 // If a case keyword is missing, this is where it should be inserted.
409 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000410
Alex Lorenzf0b4e5d2016-10-18 10:55:01 +0000411 ExprStatementTokLoc = Tok.getLocation();
412
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000413 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000414 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000415 if (Expr.isInvalid()) {
416 // If the expression is invalid, skip ahead to the next semicolon or '}'.
417 // Not doing this opens us up to the possibility of infinite loops if
418 // ParseExpression does not consume any tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000419 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000420 if (Tok.is(tok::semi))
421 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000422 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000423 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000424
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000425 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
426 Actions.CheckCaseExpression(Expr.get())) {
427 // If a constant expression is followed by a colon inside a switch block,
428 // suggest a missing case keyword.
429 Diag(OldToken, diag::err_expected_case_before_expression)
430 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000431
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000432 // Recover parsing as a case statement.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000433 return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000434 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000435
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000436 // Otherwise, eat the semicolon.
437 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000438 return handleExprStmt(Expr, StmtCtx);
John Wiegley1c0675e2011-04-28 01:08:34 +0000439}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000440
John Wiegley1c0675e2011-04-28 01:08:34 +0000441/// ParseSEHTryBlockCommon
442///
443/// seh-try-block:
444/// '__try' compound-statement seh-handler
445///
446/// seh-handler:
447/// seh-except-block
448/// seh-finally-block
449///
Nico Weberdd256742015-02-25 01:43:27 +0000450StmtResult Parser::ParseSEHTryBlock() {
451 assert(Tok.is(tok::kw___try) && "Expected '__try'");
452 SourceLocation TryLoc = ConsumeToken();
453
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000454 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000455 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley1c0675e2011-04-28 01:08:34 +0000456
Momchil Velikov57c681f2017-08-10 15:43:06 +0000457 StmtResult TryBlock(ParseCompoundStatement(
458 /*isStmtExpr=*/false,
459 Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
460 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000461 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000462
463 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000464 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000465 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000466 SourceLocation Loc = ConsumeToken();
467 Handler = ParseSEHExceptBlock(Loc);
468 } else if (Tok.is(tok::kw___finally)) {
469 SourceLocation Loc = ConsumeToken();
470 Handler = ParseSEHFinallyBlock(Loc);
471 } else {
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000472 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
John Wiegley1c0675e2011-04-28 01:08:34 +0000473 }
474
475 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000476 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000477
478 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
479 TryLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000480 TryBlock.get(),
Warren Huntf6be4cb2014-07-25 20:52:51 +0000481 Handler.get());
John Wiegley1c0675e2011-04-28 01:08:34 +0000482}
483
484/// ParseSEHExceptBlock - Handle __except
485///
486/// seh-except-block:
487/// '__except' '(' seh-filter-expression ')' compound-statement
488///
489StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
490 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
491 raii2(Ident___exception_code, false),
492 raii3(Ident_GetExceptionCode, false);
493
Alp Toker383d2c42014-01-01 03:08:43 +0000494 if (ExpectAndConsume(tok::l_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000495 return StmtError();
496
Reid Kleckner1d59f992015-01-22 01:36:17 +0000497 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
498 Scope::SEHExceptScope);
John Wiegley1c0675e2011-04-28 01:08:34 +0000499
David Blaikiebbafb8a2012-03-11 07:00:24 +0000500 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000501 Ident__exception_info->setIsPoisoned(false);
502 Ident___exception_info->setIsPoisoned(false);
503 Ident_GetExceptionInfo->setIsPoisoned(false);
504 }
Reid Kleckner1d59f992015-01-22 01:36:17 +0000505
506 ExprResult FilterExpr;
507 {
508 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
509 Scope::SEHFilterScope);
Reid Kleckner85368fb2015-04-02 22:09:32 +0000510 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Reid Kleckner1d59f992015-01-22 01:36:17 +0000511 }
Francois Pichetbfaf4772011-04-28 03:14:31 +0000512
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000514 Ident__exception_info->setIsPoisoned(true);
515 Ident___exception_info->setIsPoisoned(true);
516 Ident_GetExceptionInfo->setIsPoisoned(true);
517 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000518
519 if(FilterExpr.isInvalid())
520 return StmtError();
521
Alp Toker383d2c42014-01-01 03:08:43 +0000522 if (ExpectAndConsume(tok::r_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000523 return StmtError();
524
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000525 if (Tok.isNot(tok::l_brace))
526 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
527
Richard Smithc202b282012-04-14 00:33:13 +0000528 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000529
530 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000531 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000532
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000533 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
John Wiegley1c0675e2011-04-28 01:08:34 +0000534}
535
536/// ParseSEHFinallyBlock - Handle __finally
537///
538/// seh-finally-block:
539/// '__finally' compound-statement
540///
Nico Weberd64657f2015-03-09 02:47:59 +0000541StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000542 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
543 raii2(Ident___abnormal_termination, false),
544 raii3(Ident_AbnormalTermination, false);
545
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000546 if (Tok.isNot(tok::l_brace))
547 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
548
Nico Weberd64657f2015-03-09 02:47:59 +0000549 ParseScope FinallyScope(this, 0);
550 Actions.ActOnStartSEHFinallyBlock();
551
Richard Smithc202b282012-04-14 00:33:13 +0000552 StmtResult Block(ParseCompoundStatement());
Nico Weberce903292015-03-09 03:17:15 +0000553 if(Block.isInvalid()) {
554 Actions.ActOnAbortSEHFinallyBlock();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000555 return Block;
Nico Weberce903292015-03-09 03:17:15 +0000556 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000557
Nico Weberd64657f2015-03-09 02:47:59 +0000558 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000559}
560
Nico Weberc7d05962014-07-06 22:32:59 +0000561/// Handle __leave
562///
563/// seh-leave-statement:
564/// '__leave' ';'
565///
566StmtResult Parser::ParseSEHLeaveStatement() {
567 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
568 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
569}
570
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000571/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000572///
573/// labeled-statement:
574/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000575/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000576///
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000577StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs,
578 ParsedStmtContext StmtCtx) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000579 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
580 "Not an identifier!");
581
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000582 // The substatement is always a 'statement', not a 'declaration', but is
583 // otherwise in the same context as the labeled-statement.
584 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
585
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000586 Token IdentTok = Tok; // Save the whole token.
587 ConsumeToken(); // eat the identifier.
588
589 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000590
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000591 // identifier ':' statement
592 SourceLocation ColonLoc = ConsumeToken();
593
Richard Smitha3e01cf2013-11-15 22:45:29 +0000594 // Read label attributes, if present.
595 StmtResult SubStmt;
596 if (Tok.is(tok::kw___attribute)) {
597 ParsedAttributesWithRange TempAttrs(AttrFactory);
598 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000599
Richard Smitha3e01cf2013-11-15 22:45:29 +0000600 // In C++, GNU attributes only apply to the label if they are followed by a
601 // semicolon, to disambiguate label attributes from attributes on a labeled
602 // declaration.
603 //
604 // This doesn't quite match what GCC does; if the attribute list is empty
605 // and followed by a semicolon, GCC will reject (it appears to parse the
606 // attributes as part of a statement in that case). That looks like a bug.
607 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
608 attrs.takeAllFrom(TempAttrs);
609 else if (isDeclarationStatement()) {
610 StmtVector Stmts;
611 // FIXME: We should do this whether or not we have a declaration
612 // statement, but that doesn't work correctly (because ProhibitAttributes
613 // can't handle GNU attributes), so only call it in the one case where
614 // GNU attributes are allowed.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000615 SubStmt = ParseStatementOrDeclarationAfterAttributes(Stmts, StmtCtx,
616 nullptr, TempAttrs);
Richard Smitha3e01cf2013-11-15 22:45:29 +0000617 if (!TempAttrs.empty() && !SubStmt.isInvalid())
Erich Keanec480f302018-07-12 21:09:05 +0000618 SubStmt = Actions.ProcessStmtAttributes(SubStmt.get(), TempAttrs,
619 TempAttrs.Range);
Richard Smitha3e01cf2013-11-15 22:45:29 +0000620 } else {
Alp Toker383d2c42014-01-01 03:08:43 +0000621 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smitha3e01cf2013-11-15 22:45:29 +0000622 }
623 }
624
625 // If we've not parsed a statement yet, parse one now.
626 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000627 SubStmt = ParseStatement(nullptr, StmtCtx);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000628
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000629 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000630 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000631 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000632
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000633 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
634 IdentTok.getLocation());
Erich Keanec480f302018-07-12 21:09:05 +0000635 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, attrs);
636 attrs.clear();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000637
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000638 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
639 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000640}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000641
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000642/// ParseCaseStatement
643/// labeled-statement:
644/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000645/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000646///
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000647StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
648 bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000649 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000650
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000651 // The substatement is always a 'statement', not a 'declaration', but is
652 // otherwise in the same context as the labeled-statement.
653 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
654
Chris Lattner34a22092009-03-04 04:23:07 +0000655 // It is very very common for code to contain many case statements recursively
656 // nested, as in (but usually without indentation):
657 // case 1:
658 // case 2:
659 // case 3:
660 // case 4:
661 // case 5: etc.
662 //
663 // Parsing this naively works, but is both inefficient and can cause us to run
664 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000665 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000666 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smitha3e01cf2013-11-15 22:45:29 +0000667 // weirdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000668
Chris Lattner34a22092009-03-04 04:23:07 +0000669 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
670 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000671 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000672
Chris Lattner34a22092009-03-04 04:23:07 +0000673 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
674 // gets updated each time a new case is parsed, and whose body is unset so
675 // far. When parsing 'case 4', this is the 'case 3' node.
Craig Topper161e4db2014-05-21 06:02:52 +0000676 Stmt *DeepestParsedCaseStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000677
Chris Lattner34a22092009-03-04 04:23:07 +0000678 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000679 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000680 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000681 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
682 ConsumeToken(); // eat the 'case'.
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000683 ColonLoc = SourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000684
Douglas Gregord328d572009-09-21 18:10:23 +0000685 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000686 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000687 cutOffParsing();
688 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000689 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000690
Chris Lattner125c0ee2009-12-10 00:38:54 +0000691 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
692 /// Disable this form of error recovery while we're parsing the case
693 /// expression.
694 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000695
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000696 ExprResult LHS;
697 if (!MissingCase) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000698 LHS = ParseCaseExpression(CaseLoc);
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000699 if (LHS.isInvalid()) {
700 // If constant-expression is parsed unsuccessfully, recover by skipping
701 // current case statement (moving to the colon that ends it).
Richard Smithef6c43d2018-07-26 18:41:30 +0000702 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
703 return StmtError();
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000704 }
705 } else {
706 LHS = Expr;
707 MissingCase = false;
Chris Lattner476c3ad2006-08-13 22:09:58 +0000708 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000709
Chris Lattner34a22092009-03-04 04:23:07 +0000710 // GNU case range extension.
711 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000712 ExprResult RHS;
Alp Tokerec543272013-12-24 09:48:30 +0000713 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
714 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Richard Smithef6c43d2018-07-26 18:41:30 +0000715 RHS = ParseCaseExpression(CaseLoc);
Chris Lattner34a22092009-03-04 04:23:07 +0000716 if (RHS.isInvalid()) {
Richard Smithef6c43d2018-07-26 18:41:30 +0000717 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
718 return StmtError();
Chris Lattner34a22092009-03-04 04:23:07 +0000719 }
720 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000721
Chris Lattner125c0ee2009-12-10 00:38:54 +0000722 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000723
Alp Tokerec543272013-12-24 09:48:30 +0000724 if (TryConsumeToken(tok::colon, ColonLoc)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000725 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
726 TryConsumeToken(tok::coloncolon, ColonLoc)) {
727 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Alp Tokerec543272013-12-24 09:48:30 +0000728 Diag(ColonLoc, diag::err_expected_after)
729 << "'case'" << tok::colon
730 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000731 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000732 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000733 Diag(ExpectedLoc, diag::err_expected_after)
734 << "'case'" << tok::colon
735 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000736 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000737 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000738
John McCalldadc5752010-08-24 06:29:42 +0000739 StmtResult Case =
Richard Smithef6c43d2018-07-26 18:41:30 +0000740 Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000741
Chris Lattner34a22092009-03-04 04:23:07 +0000742 // If we had a sema error parsing this case, then just ignore it and
743 // continue parsing the sub-stmt.
744 if (Case.isInvalid()) {
745 if (TopLevelCase.isInvalid()) // No parsed case stmts.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000746 return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
Chris Lattner34a22092009-03-04 04:23:07 +0000747 // Otherwise, just don't add it as a nested case.
748 } else {
749 // If this is the first case statement we parsed, it becomes TopLevelCase.
750 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000751 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000752 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000753 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000754 else
John McCallb268a282010-08-23 23:25:46 +0000755 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000756 DeepestParsedCaseStmt = NextDeepest;
757 }
Mike Stump11289f42009-09-09 15:08:12 +0000758
Chris Lattner34a22092009-03-04 04:23:07 +0000759 // Handle all case statements.
760 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattner34a22092009-03-04 04:23:07 +0000762 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000763 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000764
Chris Lattner34a22092009-03-04 04:23:07 +0000765 if (Tok.isNot(tok::r_brace)) {
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000766 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
Chris Lattner34a22092009-03-04 04:23:07 +0000767 } else {
768 // Nicely diagnose the common error "switch (X) { case 4: }", which is
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000769 // not valid. If ColonLoc doesn't point to a valid text location, there was
770 // another parsing error, so avoid producing extra diagnostics.
771 if (ColonLoc.isValid()) {
772 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
773 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
774 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
775 }
776 SubStmt = StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +0000777 }
Mike Stump11289f42009-09-09 15:08:12 +0000778
Chris Lattner34a22092009-03-04 04:23:07 +0000779 // Install the body into the most deeply-nested case.
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000780 if (DeepestParsedCaseStmt) {
781 // Broken sub-stmt shouldn't prevent forming the case statement properly.
782 if (SubStmt.isInvalid())
783 SubStmt = Actions.ActOnNullStmt(SourceLocation());
784 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
785 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000786
Chris Lattner34a22092009-03-04 04:23:07 +0000787 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000788 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000789}
790
791/// ParseDefaultStatement
792/// labeled-statement:
793/// 'default' ':' statement
794/// Note that this does not parse the 'statement' at the end.
795///
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000796StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000797 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000798
799 // The substatement is always a 'statement', not a 'declaration', but is
800 // otherwise in the same context as the labeled-statement.
801 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
802
Chris Lattneraf635312006-10-16 06:06:51 +0000803 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000804
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000805 SourceLocation ColonLoc;
Alp Tokerec543272013-12-24 09:48:30 +0000806 if (TryConsumeToken(tok::colon, ColonLoc)) {
Alp Tokerec543272013-12-24 09:48:30 +0000807 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
Alp Toker97650562014-01-10 11:19:30 +0000808 // Treat "default;" as a typo for "default:".
Alp Tokerec543272013-12-24 09:48:30 +0000809 Diag(ColonLoc, diag::err_expected_after)
810 << "'default'" << tok::colon
811 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000812 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000813 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000814 Diag(ExpectedLoc, diag::err_expected_after)
815 << "'default'" << tok::colon
816 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000817 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000818 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000819
Richard Smith1002d102012-02-17 01:35:32 +0000820 StmtResult SubStmt;
821
822 if (Tok.isNot(tok::r_brace)) {
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000823 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
Richard Smith1002d102012-02-17 01:35:32 +0000824 } else {
825 // Diagnose the common error "switch (X) {... default: }", which is
826 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000827 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000828 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
829 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
830 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000831 }
832
Richard Smith1002d102012-02-17 01:35:32 +0000833 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000834 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000835 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000836
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000837 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000838 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000839}
840
Richard Smithc202b282012-04-14 00:33:13 +0000841StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
Momchil Velikov57c681f2017-08-10 15:43:06 +0000842 return ParseCompoundStatement(isStmtExpr,
843 Scope::DeclScope | Scope::CompoundStmtScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000844}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000845
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000846/// ParseCompoundStatement - Parse a "{}" block.
847///
848/// compound-statement: [C99 6.8.2]
849/// { block-item-list[opt] }
850/// [GNU] { label-declarations block-item-list } [TODO]
851///
852/// block-item-list:
853/// block-item
854/// block-item-list block-item
855///
856/// block-item:
857/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000858/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000859/// statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000860///
861/// [GNU] label-declarations:
862/// [GNU] label-declaration
863/// [GNU] label-declarations label-declaration
864///
865/// [GNU] label-declaration:
866/// [GNU] '__label__' identifier-list ';'
867///
Richard Smithc202b282012-04-14 00:33:13 +0000868StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000869 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000870 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000871
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000872 // Enter a scope to hold everything within the compound stmt. Compound
873 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000874 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000875
876 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000877 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000878}
879
Lang Hames2954cea2012-11-03 22:29:05 +0000880/// Parse any pragmas at the start of the compound expression. We handle these
881/// separately since some pragmas (FP_CONTRACT) must appear before any C
882/// statement in the compound, but may be intermingled with other pragmas.
883void Parser::ParseCompoundStatementLeadingPragmas() {
884 bool checkForPragmas = true;
885 while (checkForPragmas) {
886 switch (Tok.getKind()) {
887 case tok::annot_pragma_vis:
888 HandlePragmaVisibility();
889 break;
890 case tok::annot_pragma_pack:
891 HandlePragmaPack();
892 break;
893 case tok::annot_pragma_msstruct:
894 HandlePragmaMSStruct();
895 break;
896 case tok::annot_pragma_align:
897 HandlePragmaAlign();
898 break;
899 case tok::annot_pragma_weak:
900 HandlePragmaWeak();
901 break;
902 case tok::annot_pragma_weakalias:
903 HandlePragmaWeakAlias();
904 break;
905 case tok::annot_pragma_redefine_extname:
906 HandlePragmaRedefineExtname();
907 break;
908 case tok::annot_pragma_opencl_extension:
909 HandlePragmaOpenCLExtension();
910 break;
911 case tok::annot_pragma_fp_contract:
912 HandlePragmaFPContract();
913 break;
Adam Nemet60d32642017-04-04 21:18:36 +0000914 case tok::annot_pragma_fp:
915 HandlePragmaFP();
916 break;
Kevin P. Neal2c0bc8b2018-08-14 17:06:56 +0000917 case tok::annot_pragma_fenv_access:
918 HandlePragmaFEnvAccess();
919 break;
David Majnemer4bb09802014-02-10 19:50:15 +0000920 case tok::annot_pragma_ms_pointers_to_members:
921 HandlePragmaMSPointersToMembers();
922 break;
Warren Huntc3b18962014-04-08 22:30:47 +0000923 case tok::annot_pragma_ms_pragma:
924 HandlePragmaMSPragma();
925 break;
Alexey Bataev3d42f342015-11-20 07:02:57 +0000926 case tok::annot_pragma_ms_vtordisp:
927 HandlePragmaMSVtorDisp();
928 break;
Richard Smithba3a4f92016-01-12 21:59:26 +0000929 case tok::annot_pragma_dump:
930 HandlePragmaDump();
931 break;
Lang Hames2954cea2012-11-03 22:29:05 +0000932 default:
933 checkForPragmas = false;
934 break;
935 }
936 }
937
938}
939
Roman Lebedev377748f2018-11-20 18:59:05 +0000940/// Consume any extra semi-colons resulting in null statements,
941/// returning true if any tok::semi were consumed.
942bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
943 if (!Tok.is(tok::semi))
944 return false;
945
946 SourceLocation StartLoc = Tok.getLocation();
947 SourceLocation EndLoc;
948
949 while (Tok.is(tok::semi) && !Tok.hasLeadingEmptyMacro() &&
950 Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
951 EndLoc = Tok.getLocation();
952
953 // Don't just ConsumeToken() this tok::semi, do store it in AST.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000954 StmtResult R =
955 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
Roman Lebedev377748f2018-11-20 18:59:05 +0000956 if (R.isUsable())
957 Stmts.push_back(R.get());
958 }
959
960 // Did not consume any extra semi.
961 if (EndLoc.isInvalid())
962 return false;
963
964 Diag(StartLoc, diag::warn_null_statement)
965 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
966 return true;
967}
968
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000969StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
970 bool IsStmtExprResult = false;
971 if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
972 // Look ahead to see if the next two tokens close the statement expression;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000973 // if so, this expression statement is the last statement in a
974 // statment expression.
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000975 IsStmtExprResult = Tok.is(tok::r_brace) && NextToken().is(tok::r_paren);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000976 }
Richard Smitha6e8d5e2019-02-15 00:27:53 +0000977
978 if (IsStmtExprResult)
979 E = Actions.ActOnStmtExprResult(E);
980 return Actions.ActOnExprStmt(E, /*DiscardedValue=*/!IsStmtExprResult);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000981}
982
Chris Lattnerf2978802007-01-21 06:52:16 +0000983/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000984/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000985/// consume the '}' at the end of the block. It does not manipulate the scope
986/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000987StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000988 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000989 Tok.getLocation(),
990 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000991
992 // Record the state of the FP_CONTRACT pragma, restore on leaving the
993 // compound statement.
994 Sema::FPContractStateRAII SaveFPContractState(Actions);
995
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000996 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000997 BalancedDelimiterTracker T(*this, tok::l_brace);
998 if (T.consumeOpen())
999 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +00001000
Richard Smith6eb9b9e2018-02-03 00:44:57 +00001001 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001002
Lang Hames2954cea2012-11-03 22:29:05 +00001003 // Parse any pragmas at the beginning of the compound statement.
1004 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +00001005
Lang Hames2954cea2012-11-03 22:29:05 +00001006 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +00001007
Chris Lattner43e7f312011-02-18 02:08:43 +00001008 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1009 // only allowed at the start of a compound stmt regardless of the language.
1010 while (Tok.is(tok::kw___label__)) {
1011 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001012
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001013 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +00001014 while (1) {
1015 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001016 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner43e7f312011-02-18 02:08:43 +00001017 break;
1018 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001019
Chris Lattner43e7f312011-02-18 02:08:43 +00001020 IdentifierInfo *II = Tok.getIdentifierInfo();
1021 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +00001022 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001023
Alp Tokerec543272013-12-24 09:48:30 +00001024 if (!TryConsumeToken(tok::comma))
Chris Lattner43e7f312011-02-18 02:08:43 +00001025 break;
Chris Lattner43e7f312011-02-18 02:08:43 +00001026 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001027
John McCall084e83d2011-03-24 11:26:52 +00001028 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +00001029 DeclGroupPtrTy Res =
1030 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +00001031 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001032
Chris Lattner02f1b612012-04-28 16:12:17 +00001033 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +00001034 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001035 Stmts.push_back(R.get());
Chris Lattner43e7f312011-02-18 02:08:43 +00001036 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001037
Richard Smitha6e8d5e2019-02-15 00:27:53 +00001038 ParsedStmtContext SubStmtCtx =
1039 ParsedStmtContext::Compound |
1040 (isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());
1041
Richard Smith752ada82015-11-17 23:32:01 +00001042 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
1043 Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +00001044 if (Tok.is(tok::annot_pragma_unused)) {
1045 HandlePragmaUnused();
1046 continue;
1047 }
1048
Roman Lebedev377748f2018-11-20 18:59:05 +00001049 if (ConsumeNullStmt(Stmts))
1050 continue;
1051
John McCalldadc5752010-08-24 06:29:42 +00001052 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001053 if (Tok.isNot(tok::kw___extension__)) {
Richard Smitha6e8d5e2019-02-15 00:27:53 +00001054 R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001055 } else {
1056 // __extension__ can start declarations and it can also be a unary
1057 // operator for expressions. Consume multiple __extension__ markers here
1058 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +00001059 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001060 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001061 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001062 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +00001063
John McCall084e83d2011-03-24 11:26:52 +00001064 ParsedAttributesWithRange attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00001065 MaybeParseCXX11Attributes(attrs, nullptr,
1066 /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +00001067
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001068 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +00001069 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +00001070 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +00001071 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +00001072 ExtensionRAIIObject O(Diags);
1073
Chris Lattner49836b42009-04-02 04:16:50 +00001074 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +00001075 DeclGroupPtrTy Res =
1076 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001077 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001078 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +00001079 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +00001080 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +00001081
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001082 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001083 SkipUntil(tok::semi);
1084 continue;
1085 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +00001086
Chris Lattner1ff6e732008-10-20 06:51:33 +00001087 // Eat the semicolon at the end of stmt and convert the expr into a
1088 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +00001089 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smitha6e8d5e2019-02-15 00:27:53 +00001090 R = handleExprStmt(Res, SubStmtCtx);
1091 if (R.isUsable())
1092 R = Actions.ProcessStmtAttributes(R.get(), attrs, attrs.Range);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001093 }
1094 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001095
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001096 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001097 Stmts.push_back(R.get());
Chris Lattner30f910e2006-10-16 05:52:41 +00001098 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001099
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001100 SourceLocation CloseLoc = Tok.getLocation();
1101
Chris Lattner0ccd51e2006-08-09 05:47:47 +00001102 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +00001103 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001104 // Recover by creating a compound statement with what we parsed so far,
1105 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +00001106 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001107
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001108 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001109 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +00001110}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001111
Chris Lattnerc0081db2008-12-12 06:31:07 +00001112/// ParseParenExprOrCondition:
1113/// [C ] '(' expression ')'
Richard Smithc7a05a92016-06-29 21:17:59 +00001114/// [C++] '(' condition ')'
1115/// [C++1z] '(' init-statement[opt] condition ')'
Chris Lattnerc0081db2008-12-12 06:31:07 +00001116///
1117/// This function parses and performs error recovery on the specified condition
1118/// or expression (depending on whether we're in C++ or C mode). This function
1119/// goes out of its way to recover well. It returns true if there was a parser
1120/// error (the right paren couldn't be found), which indicates that the caller
1121/// should try to recover harder. It returns false if the condition is
1122/// successfully parsed. Note that a successful parse can still have semantic
1123/// errors in the condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001124bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1125 Sema::ConditionResult &Cond,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001126 SourceLocation Loc,
Richard Smith03a4aa32016-06-23 19:02:52 +00001127 Sema::ConditionKind CK) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001128 BalancedDelimiterTracker T(*this, tok::l_paren);
1129 T.consumeOpen();
1130
David Blaikiebbafb8a2012-03-11 07:00:24 +00001131 if (getLangOpts().CPlusPlus)
Richard Smithc7a05a92016-06-29 21:17:59 +00001132 Cond = ParseCXXCondition(InitStmt, Loc, CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001133 else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001134 ExprResult CondExpr = ParseExpression();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001135
Douglas Gregore60e41a2010-05-06 17:25:47 +00001136 // If required, convert to a boolean value.
Richard Smith03a4aa32016-06-23 19:02:52 +00001137 if (CondExpr.isInvalid())
1138 Cond = Sema::ConditionError();
1139 else
1140 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001141 }
Mike Stump11289f42009-09-09 15:08:12 +00001142
Chris Lattnerc0081db2008-12-12 06:31:07 +00001143 // If the parser was confused by the condition and we don't have a ')', try to
1144 // recover by skipping ahead to a semi and bailing out. If condexp is
1145 // semantically invalid but we have well formed code, keep going.
Richard Smith03a4aa32016-06-23 19:02:52 +00001146 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +00001147 SkipUntil(tok::semi);
1148 // Skipping may have stopped if it found the containing ')'. If so, we can
1149 // continue parsing the if statement.
1150 if (Tok.isNot(tok::r_paren))
1151 return true;
1152 }
Mike Stump11289f42009-09-09 15:08:12 +00001153
Chris Lattnerc0081db2008-12-12 06:31:07 +00001154 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001155 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +00001156
Chris Lattner70d44982012-04-28 16:24:20 +00001157 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1158 // that all callers are looking for a statement after the condition, so ")"
1159 // isn't valid.
1160 while (Tok.is(tok::r_paren)) {
1161 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1162 << FixItHint::CreateRemoval(Tok.getLocation());
1163 ConsumeParen();
1164 }
Chad Rosier67055f52012-07-10 21:35:27 +00001165
Chris Lattnerc0081db2008-12-12 06:31:07 +00001166 return false;
1167}
1168
1169
Chris Lattnerc951dae2006-08-10 04:23:57 +00001170/// ParseIfStatement
1171/// if-statement: [C99 6.8.4.1]
1172/// 'if' '(' expression ')' statement
1173/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001174/// [C++] 'if' '(' condition ')' statement
1175/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +00001176///
Richard Smithc202b282012-04-14 00:33:13 +00001177StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001178 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001179 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +00001180
Richard Smithb130fe72016-06-23 19:16:49 +00001181 bool IsConstexpr = false;
1182 if (Tok.is(tok::kw_constexpr)) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001183 Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
Richard Smithb130fe72016-06-23 19:16:49 +00001184 : diag::ext_constexpr_if);
1185 IsConstexpr = true;
1186 ConsumeToken();
1187 }
1188
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001189 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001190 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +00001191 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +00001192 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +00001193 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001194
David Blaikiebbafb8a2012-03-11 07:00:24 +00001195 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001196
Chris Lattner2dd1b722007-08-26 23:08:06 +00001197 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1198 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001199 //
1200 // C++ 6.4p3:
1201 // A name introduced by a declaration in a condition is in scope from its
1202 // point of declaration until the end of the substatements controlled by the
1203 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001204 // C++ 3.3.2p4:
1205 // Names declared in the for-init-statement, and in the condition of if,
1206 // while, for, and switch statements are local to the if, while, for, or
1207 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001208 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001209 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001210
Chris Lattnerc951dae2006-08-10 04:23:57 +00001211 // Parse the condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001212 StmtResult InitStmt;
Richard Smith03a4aa32016-06-23 19:02:52 +00001213 Sema::ConditionResult Cond;
Richard Smithc7a05a92016-06-29 21:17:59 +00001214 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
Richard Smithb130fe72016-06-23 19:16:49 +00001215 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1216 : Sema::ConditionKind::Boolean))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001217 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001218
Richard Smithb130fe72016-06-23 19:16:49 +00001219 llvm::Optional<bool> ConstexprCondition;
1220 if (IsConstexpr)
1221 ConstexprCondition = Cond.getKnownValue();
1222
Chris Lattner8fb26252007-08-22 05:28:50 +00001223 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001224 // there is no compound stmt. C90 does not have this clause. We only do this
1225 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001226 //
1227 // C++ 6.4p1:
1228 // The substatement in a selection-statement (each substatement, in the else
1229 // form of the if statement) implicitly defines a local scope.
1230 //
1231 // For C++ we create a scope for the condition and a new scope for
1232 // substatements because:
1233 // -When the 'then' scope exits, we want the condition declaration to still be
1234 // active for the 'else' scope too.
1235 // -Sema will detect name clashes by considering declarations of a
1236 // 'ControlScope' as part of its direct subscope.
1237 // -If we wanted the condition and substatement to be in the same scope, we
1238 // would have to notify ParseStatement not to create a new scope. It's
1239 // simpler to let it create a new scope.
1240 //
David Majnemer2206bf52014-03-05 08:57:59 +00001241 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001242
Chris Lattner5c5808a2007-10-29 05:08:52 +00001243 // Read the 'then' stmt.
1244 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001245
1246 SourceLocation InnerStatementTrailingElseLoc;
Richard Smithb130fe72016-06-23 19:16:49 +00001247 StmtResult ThenStmt;
1248 {
1249 EnterExpressionEvaluationContext PotentiallyDiscarded(
Faisal Valid143a0c2017-04-01 21:30:49 +00001250 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00001251 Sema::ExpressionEvaluationContextRecord::EK_Other,
Richard Smithb130fe72016-06-23 19:16:49 +00001252 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1253 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1254 }
Chris Lattnerac4471c2007-05-28 05:38:24 +00001255
Chris Lattner37e54f42007-08-22 05:16:28 +00001256 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001257 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001258
Chris Lattnerc951dae2006-08-10 04:23:57 +00001259 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001260 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001261 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001262 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001263
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001264 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001265 if (TrailingElseLoc)
1266 *TrailingElseLoc = Tok.getLocation();
1267
Chris Lattneraf635312006-10-16 06:06:51 +00001268 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001269 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001270
Chris Lattner8fb26252007-08-22 05:28:50 +00001271 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001272 // there is no compound stmt. C90 does not have this clause. We only do
1273 // this if the body isn't a compound statement to avoid push/pop in common
1274 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001275 //
1276 // C++ 6.4p1:
1277 // The substatement in a selection-statement (each substatement, in the else
1278 // form of the if statement) implicitly defines a local scope.
1279 //
Richard Smithb130fe72016-06-23 19:16:49 +00001280 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1281 Tok.is(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001282
Richard Smithb130fe72016-06-23 19:16:49 +00001283 EnterExpressionEvaluationContext PotentiallyDiscarded(
Faisal Valid143a0c2017-04-01 21:30:49 +00001284 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00001285 Sema::ExpressionEvaluationContextRecord::EK_Other,
Richard Smithb130fe72016-06-23 19:16:49 +00001286 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
Chris Lattner30f910e2006-10-16 05:52:41 +00001287 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001288
Chris Lattner37e54f42007-08-22 05:16:28 +00001289 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001290 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001291 } else if (Tok.is(tok::code_completion)) {
1292 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001293 cutOffParsing();
1294 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001295 } else if (InnerStatementTrailingElseLoc.isValid()) {
1296 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001297 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001298
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001299 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattner5c5808a2007-10-29 05:08:52 +00001301 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001302 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001303 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001304 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
Craig Topper161e4db2014-05-21 06:02:52 +00001305 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1306 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001307 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001308 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001309 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001310
Chris Lattner5c5808a2007-10-29 05:08:52 +00001311 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001312 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001313 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001314 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001315 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001316
Richard Smithc7a05a92016-06-29 21:17:59 +00001317 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1318 ThenStmt.get(), ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001319}
1320
Chris Lattner9075bd72006-08-10 04:59:57 +00001321/// ParseSwitchStatement
1322/// switch-statement:
1323/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001324/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001325StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001326 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001327 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001328
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001329 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001330 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001331 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001332 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001333 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001334
David Blaikiebbafb8a2012-03-11 07:00:24 +00001335 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001336
Chris Lattner2dd1b722007-08-26 23:08:06 +00001337 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1338 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001339 //
1340 // C++ 6.4p3:
1341 // A name introduced by a declaration in a condition is in scope from its
1342 // point of declaration until the end of the substatements controlled by the
1343 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001344 // C++ 3.3.2p4:
1345 // Names declared in the for-init-statement, and in the condition of if,
1346 // while, for, and switch statements are local to the if, while, for, or
1347 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001348 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001349 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001350 if (C99orCXX)
1351 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001352 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001353
Chris Lattner9075bd72006-08-10 04:59:57 +00001354 // Parse the condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001355 StmtResult InitStmt;
Richard Smith03a4aa32016-06-23 19:02:52 +00001356 Sema::ConditionResult Cond;
Richard Smithc7a05a92016-06-29 21:17:59 +00001357 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1358 Sema::ConditionKind::Switch))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001359 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001360
Richard Smithc7a05a92016-06-29 21:17:59 +00001361 StmtResult Switch =
1362 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001363
Douglas Gregore60e41a2010-05-06 17:25:47 +00001364 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001365 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001366 // FIXME: This is not optimal recovery, but parsing the body is more
1367 // dangerous due to the presence of case and default statements, which
1368 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001369 if (Tok.is(tok::l_brace)) {
1370 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001371 SkipUntil(tok::r_brace);
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001372 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001373 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001374 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001375 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001376
Chris Lattner8fb26252007-08-22 05:28:50 +00001377 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001378 // there is no compound stmt. C90 does not have this clause. We only do this
1379 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001380 //
1381 // C++ 6.4p1:
1382 // The substatement in a selection-statement (each substatement, in the else
1383 // form of the if statement) implicitly defines a local scope.
1384 //
1385 // See comments in ParseIfStatement for why we create a scope for the
1386 // condition and a new scope for substatement in C++.
1387 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001388 getCurScope()->AddFlags(Scope::BreakScope);
David Majnemer2206bf52014-03-05 08:57:59 +00001389 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001390
Hans Wennborg852c3462014-06-17 00:09:05 +00001391 // We have incremented the mangling number for the SwitchScope and the
1392 // InnerScope, which is one too many.
1393 if (C99orCXX)
David Majnemera7f8c462015-03-19 21:54:30 +00001394 getCurScope()->decrementMSManglingNumber();
Hans Wennborg852c3462014-06-17 00:09:05 +00001395
Chris Lattner9075bd72006-08-10 04:59:57 +00001396 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001397 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001398
Chris Lattner8fd2d012010-01-24 01:50:29 +00001399 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001400 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001401 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001402
John McCallb268a282010-08-23 23:25:46 +00001403 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001404}
1405
1406/// ParseWhileStatement
1407/// while-statement: [C99 6.8.5.1]
1408/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001409/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001410StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001411 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001412 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001413 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001414
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001415 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001416 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001417 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001418 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001419 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001420
David Blaikiebbafb8a2012-03-11 07:00:24 +00001421 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001422
Chris Lattner2dd1b722007-08-26 23:08:06 +00001423 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1424 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001425 //
1426 // C++ 6.4p3:
1427 // A name introduced by a declaration in a condition is in scope from its
1428 // point of declaration until the end of the substatements controlled by the
1429 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001430 // C++ 3.3.2p4:
1431 // Names declared in the for-init-statement, and in the condition of if,
1432 // while, for, and switch statements are local to the if, while, for, or
1433 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001434 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001435 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001436 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001437 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1438 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001439 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001440 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1441 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001442
Chris Lattner9075bd72006-08-10 04:59:57 +00001443 // Parse the condition.
Richard Smith03a4aa32016-06-23 19:02:52 +00001444 Sema::ConditionResult Cond;
Richard Smithc7a05a92016-06-29 21:17:59 +00001445 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1446 Sema::ConditionKind::Boolean))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001447 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001448
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001449 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001450 // there is no compound stmt. C90 does not have this clause. We only do this
1451 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001452 //
1453 // C++ 6.5p2:
1454 // The substatement in an iteration-statement implicitly defines a local scope
1455 // which is entered and exited each time through the loop.
1456 //
1457 // See comments in ParseIfStatement for why we create a scope for the
1458 // condition and a new scope for substatement in C++.
1459 //
David Majnemer2206bf52014-03-05 08:57:59 +00001460 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001461
Chris Lattner9075bd72006-08-10 04:59:57 +00001462 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001463 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001464
Chris Lattner8fb26252007-08-22 05:28:50 +00001465 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001466 InnerScope.Exit();
1467 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001468
Richard Smith03a4aa32016-06-23 19:02:52 +00001469 if (Cond.isInvalid() || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001470 return StmtError();
1471
Richard Smith03a4aa32016-06-23 19:02:52 +00001472 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001473}
1474
1475/// ParseDoStatement
1476/// do-statement: [C99 6.8.5.2]
1477/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001478/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001479StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001480 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001481 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001482
Chris Lattner2dd1b722007-08-26 23:08:06 +00001483 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1484 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001485 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001486 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001487 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001488 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001489 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001490
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001491 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001492
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001493 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001494 // there is no compound stmt. C90 does not have this clause. We only do this
1495 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001496 //
1497 // C++ 6.5p2:
1498 // The substatement in an iteration-statement implicitly defines a local scope
1499 // which is entered and exited each time through the loop.
1500 //
David Majnemer2206bf52014-03-05 08:57:59 +00001501 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1502 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001503
Chris Lattner9075bd72006-08-10 04:59:57 +00001504 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001505 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001506
Chris Lattner8fb26252007-08-22 05:28:50 +00001507 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001508 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001509
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001510 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001511 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001512 Diag(Tok, diag::err_expected_while);
Alp Tokerec543272013-12-24 09:48:30 +00001513 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001514 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner0046de12008-11-13 18:52:53 +00001515 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001516 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001517 }
Chris Lattneraf635312006-10-16 06:06:51 +00001518 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001519
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001520 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001521 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001522 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001523 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001524 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001525
Richard Smithc2c8bb82013-10-15 01:34:54 +00001526 // Parse the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001527 BalancedDelimiterTracker T(*this, tok::l_paren);
1528 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001529
Richard Smithc2c8bb82013-10-15 01:34:54 +00001530 // A do-while expression is not a condition, so can't have attributes.
1531 DiagnoseAndSkipCXX11Attributes();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001532
John McCalldadc5752010-08-24 06:29:42 +00001533 ExprResult Cond = ParseExpression();
Alex Lorenzc38ba662017-10-30 22:55:11 +00001534 // Correct the typos in condition before closing the scope.
1535 if (Cond.isUsable())
1536 Cond = Actions.CorrectDelayedTyposInExpr(Cond);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001537 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001538 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001539
Sebastian Redlb62406f2008-12-11 19:48:14 +00001540 if (Cond.isInvalid() || Body.isInvalid())
1541 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001542
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001543 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1544 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001545}
1546
Richard Smith955bf012014-06-19 11:42:00 +00001547bool Parser::isForRangeIdentifier() {
1548 assert(Tok.is(tok::identifier));
1549
1550 const Token &Next = NextToken();
1551 if (Next.is(tok::colon))
1552 return true;
1553
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001554 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
Richard Smith955bf012014-06-19 11:42:00 +00001555 TentativeParsingAction PA(*this);
1556 ConsumeToken();
1557 SkipCXX11Attributes();
1558 bool Result = Tok.is(tok::colon);
1559 PA.Revert();
1560 return Result;
1561 }
1562
1563 return false;
1564}
1565
Chris Lattner9075bd72006-08-10 04:59:57 +00001566/// ParseForStatement
1567/// for-statement: [C99 6.8.5.3]
1568/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1569/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001570/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1571/// [C++] statement
Richard Smith0e304ea2015-10-22 04:46:14 +00001572/// [C++0x] 'for'
1573/// 'co_await'[opt] [Coroutines]
1574/// '(' for-range-declaration ':' for-range-initializer ')'
1575/// statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001576/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1577/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001578///
1579/// [C++] for-init-statement:
1580/// [C++] expression-statement
1581/// [C++] simple-declaration
1582///
Richard Smith02e85f32011-04-14 22:09:26 +00001583/// [C++0x] for-range-declaration:
1584/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1585/// [C++0x] for-range-initializer:
1586/// [C++0x] expression
1587/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001588StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001589 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001590 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001591
Richard Smith0e304ea2015-10-22 04:46:14 +00001592 SourceLocation CoawaitLoc;
1593 if (Tok.is(tok::kw_co_await))
1594 CoawaitLoc = ConsumeToken();
1595
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001596 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001597 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001598 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001599 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001600 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001601
Chad Rosier67055f52012-07-10 21:35:27 +00001602 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
Erik Pilkingtonfa983902018-10-30 20:31:30 +00001603 getLangOpts().ObjC;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001604
Chris Lattner2dd1b722007-08-26 23:08:06 +00001605 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1606 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001607 //
1608 // C++ 6.4p3:
1609 // A name introduced by a declaration in a condition is in scope from its
1610 // point of declaration until the end of the substatements controlled by the
1611 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001612 // C++ 3.3.2p4:
1613 // Names declared in the for-init-statement, and in the condition of if,
1614 // while, for, and switch statements are local to the if, while, for, or
1615 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001616 // C++ 6.5.3p1:
1617 // Names declared in the for-init-statement are in the same declarative-region
1618 // as those declared in the condition.
1619 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001620 unsigned ScopeFlags = 0;
Chris Lattner934074c2009-04-22 00:54:41 +00001621 if (C99orCXXorObjC)
Serge Pavlov09f99242014-01-23 15:05:00 +00001622 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001623
1624 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001625
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001626 BalancedDelimiterTracker T(*this, tok::l_paren);
1627 T.consumeOpen();
1628
John McCalldadc5752010-08-24 06:29:42 +00001629 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001630
Richard Smith8baa5002018-09-28 18:44:09 +00001631 bool ForEach = false;
John McCalldadc5752010-08-24 06:29:42 +00001632 StmtResult FirstPart;
Richard Smith03a4aa32016-06-23 19:02:52 +00001633 Sema::ConditionResult SecondPart;
John McCalldadc5752010-08-24 06:29:42 +00001634 ExprResult Collection;
Richard Smith8baa5002018-09-28 18:44:09 +00001635 ForRangeInfo ForRangeInfo;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001636 FullExprArg ThirdPart(Actions);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001637
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001638 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001639 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001640 C99orCXXorObjC? Sema::PCC_ForInit
1641 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001642 cutOffParsing();
1643 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001644 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001645
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001646 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001647 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001648
Roman Lebedev377748f2018-11-20 18:59:05 +00001649 SourceLocation EmptyInitStmtSemiLoc;
1650
Chris Lattner9075bd72006-08-10 04:59:57 +00001651 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001652 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001653 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001654 // no first part, eat the ';'.
Roman Lebedev377748f2018-11-20 18:59:05 +00001655 SourceLocation SemiLoc = Tok.getLocation();
1656 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
1657 EmptyInitStmtSemiLoc = SemiLoc;
Chris Lattner53361ac2006-08-10 05:19:57 +00001658 ConsumeToken();
Richard Smith955bf012014-06-19 11:42:00 +00001659 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1660 isForRangeIdentifier()) {
1661 ProhibitAttributes(attrs);
1662 IdentifierInfo *Name = Tok.getIdentifierInfo();
1663 SourceLocation Loc = ConsumeToken();
1664 MaybeParseCXX11Attributes(attrs);
1665
Richard Smith8baa5002018-09-28 18:44:09 +00001666 ForRangeInfo.ColonLoc = ConsumeToken();
Richard Smith955bf012014-06-19 11:42:00 +00001667 if (Tok.is(tok::l_brace))
Richard Smith8baa5002018-09-28 18:44:09 +00001668 ForRangeInfo.RangeExpr = ParseBraceInitializer();
Richard Smith955bf012014-06-19 11:42:00 +00001669 else
Richard Smith8baa5002018-09-28 18:44:09 +00001670 ForRangeInfo.RangeExpr = ParseExpression();
Richard Smith955bf012014-06-19 11:42:00 +00001671
Richard Smith83d3f152014-11-27 01:54:27 +00001672 Diag(Loc, diag::err_for_range_identifier)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001673 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
Richard Smith955bf012014-06-19 11:42:00 +00001674 ? FixItHint::CreateInsertion(Loc, "auto &&")
1675 : FixItHint());
1676
Richard Smith8baa5002018-09-28 18:44:09 +00001677 ForRangeInfo.LoopVar = Actions.ActOnCXXForRangeIdentifier(
1678 getCurScope(), Loc, Name, attrs, attrs.Range.getEnd());
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001679 } else if (isForInitDeclaration()) { // for (int X = 4;
Richard Smithbf5bcf22018-06-26 23:20:26 +00001680 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1681
Chris Lattner53361ac2006-08-10 05:19:57 +00001682 // Parse declaration, which eats the ';'.
George Burgess IV4d456452018-06-28 21:36:00 +00001683 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001684 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
George Burgess IV4d456452018-06-28 21:36:00 +00001685 Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
1686 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001687
Richard Smith02e85f32011-04-14 22:09:26 +00001688 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001689 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001690 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1691
Chris Lattner49836b42009-04-02 04:16:50 +00001692 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00001693 DeclGroupPtrTy DG = ParseSimpleDeclaration(
Faisal Vali421b2d12017-12-29 05:41:00 +00001694 DeclaratorContext::ForContext, DeclEnd, attrs, false,
Richard Smith8baa5002018-09-28 18:44:09 +00001695 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001696 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Richard Smith8baa5002018-09-28 18:44:09 +00001697 if (ForRangeInfo.ParsedForRangeDecl()) {
1698 Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001699 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8baa5002018-09-28 18:44:09 +00001700 ForRangeInfo.LoopVar = FirstPart;
1701 FirstPart = StmtResult();
Richard Smith02e85f32011-04-14 22:09:26 +00001702 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001703 ConsumeToken();
1704 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001705 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001706 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001707 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001708
Douglas Gregor68762e72010-08-23 21:17:50 +00001709 if (Tok.is(tok::code_completion)) {
1710 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001711 cutOffParsing();
1712 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001713 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001714 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001715 } else {
1716 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001717 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001718 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001719 ProhibitAttributes(attrs);
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001720 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Chris Lattner71e23ce2006-11-04 20:18:38 +00001721
John McCall34376a62010-12-04 03:47:34 +00001722 ForEach = isTokIdentifier_in();
1723
Chris Lattnercd68f642007-06-27 01:06:29 +00001724 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001725 if (!Value.isInvalid()) {
1726 if (ForEach)
1727 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001728 else {
1729 // We already know this is not an init-statement within a for loop, so
1730 // if we are parsing a C++11 range-based for loop, we should treat this
1731 // expression statement as being a discarded value expression because
1732 // we will err below. This way we do not warn on an unused expression
1733 // that was an error in the first place, like with: for (expr : expr);
1734 bool IsRangeBasedFor =
1735 getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon);
1736 FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
1737 }
John McCall34376a62010-12-04 03:47:34 +00001738 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001739
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001740 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001741 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001742 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001743 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001744
Douglas Gregor68762e72010-08-23 21:17:50 +00001745 if (Tok.is(tok::code_completion)) {
David Blaikie0403cb12016-01-15 23:43:25 +00001746 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001747 cutOffParsing();
1748 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001749 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001750 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001751 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001752 // User tried to write the reasonable, but ill-formed, for-range-statement
1753 // for (expr : expr) { ... }
1754 Diag(Tok, diag::err_for_range_expected_decl)
1755 << FirstPart.get()->getSourceRange();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001756 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smith03a4aa32016-06-23 19:02:52 +00001757 SecondPart = Sema::ConditionError();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001758 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001759 if (!Value.isInvalid()) {
1760 Diag(Tok, diag::err_expected_semi_for);
1761 } else {
1762 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001763 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001764 if (Tok.is(tok::semi))
1765 ConsumeToken();
1766 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001767 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001768 }
Serge Pavlov09f99242014-01-23 15:05:00 +00001769
1770 // Parse the second part of the for specifier.
1771 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smith8baa5002018-09-28 18:44:09 +00001772 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
1773 !SecondPart.isInvalid()) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001774 // Parse the second part of the for specifier.
1775 if (Tok.is(tok::semi)) { // for (...;;
1776 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001777 } else if (Tok.is(tok::r_paren)) {
1778 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001779 } else {
Richard Smith8baa5002018-09-28 18:44:09 +00001780 if (getLangOpts().CPlusPlus) {
1781 // C++2a: We've parsed an init-statement; we might have a
1782 // for-range-declaration next.
1783 bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
1784 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
Richard Smithc7a05a92016-06-29 21:17:59 +00001785 SecondPart =
Richard Smith8baa5002018-09-28 18:44:09 +00001786 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean,
1787 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
1788
1789 if (ForRangeInfo.ParsedForRangeDecl()) {
1790 Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
1791 : ForRangeInfo.ColonLoc,
1792 getLangOpts().CPlusPlus2a
1793 ? diag::warn_cxx17_compat_for_range_init_stmt
1794 : diag::ext_for_range_init_stmt)
1795 << (FirstPart.get() ? FirstPart.get()->getSourceRange()
1796 : SourceRange());
Roman Lebedev377748f2018-11-20 18:59:05 +00001797 if (EmptyInitStmtSemiLoc.isValid()) {
1798 Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
1799 << /*for-loop*/ 2
1800 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
1801 }
Richard Smith8baa5002018-09-28 18:44:09 +00001802 }
1803 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001804 ExprResult SecondExpr = ParseExpression();
1805 if (SecondExpr.isInvalid())
1806 SecondPart = Sema::ConditionError();
1807 else
1808 SecondPart =
1809 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1810 Sema::ConditionKind::Boolean);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001811 }
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001812 }
Richard Smith8baa5002018-09-28 18:44:09 +00001813 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001814
Richard Smith8baa5002018-09-28 18:44:09 +00001815 // Parse the third part of the for statement.
1816 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001817 if (Tok.isNot(tok::semi)) {
Richard Smith03a4aa32016-06-23 19:02:52 +00001818 if (!SecondPart.isInvalid())
Douglas Gregor230a7e62011-02-17 03:38:46 +00001819 Diag(Tok, diag::err_expected_semi_for);
1820 else
1821 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001822 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001823 }
1824
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001825 if (Tok.is(tok::semi)) {
1826 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001827 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001828
Douglas Gregore60e41a2010-05-06 17:25:47 +00001829 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001830 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001831 // FIXME: The C++11 standard doesn't actually say that this is a
1832 // discarded-value expression, but it clearly should be.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001833 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001834 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001835 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001836 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001837 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001838
Richard Smith0e304ea2015-10-22 04:46:14 +00001839 // C++ Coroutines [stmt.iter]:
1840 // 'co_await' can only be used for a range-based for statement.
Richard Smith8baa5002018-09-28 18:44:09 +00001841 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
Richard Smith0e304ea2015-10-22 04:46:14 +00001842 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1843 CoawaitLoc = SourceLocation();
1844 }
1845
Richard Smith02e85f32011-04-14 22:09:26 +00001846 // We need to perform most of the semantic analysis for a C++0x for-range
1847 // statememt before parsing the body, in order to be able to deduce the type
1848 // of an auto-typed loop variable.
1849 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001850 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001851
Richard Smith8baa5002018-09-28 18:44:09 +00001852 if (ForRangeInfo.ParsedForRangeDecl()) {
Denis Zobnin7d6b9242016-02-02 17:33:09 +00001853 ExprResult CorrectedRange =
Richard Smith8baa5002018-09-28 18:44:09 +00001854 Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());
Richard Smith9f690bd2015-10-27 06:02:45 +00001855 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1856 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
Richard Smith8baa5002018-09-28 18:44:09 +00001857 ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00001858 T.getCloseLocation(), Sema::BFRK_Build);
John McCall53848232011-07-27 01:07:15 +00001859
1860 // Similarly, we need to do the semantic analysis for a for-range
1861 // statement immediately in order to close over temporaries correctly.
1862 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001863 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001864 FirstPart.get(),
1865 Collection.get(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001866 T.getCloseLocation());
Alexey Bataev9c821032015-04-30 04:23:23 +00001867 } else {
1868 // In OpenMP loop region loop control variable must be captured and be
1869 // private. Perform analysis of first part (if any).
1870 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1871 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1872 }
John McCall53848232011-07-27 01:07:15 +00001873 }
1874
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001875 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001876 // there is no compound stmt. C90 does not have this clause. We only do this
1877 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001878 //
1879 // C++ 6.5p2:
1880 // The substatement in an iteration-statement implicitly defines a local scope
1881 // which is entered and exited each time through the loop.
1882 //
1883 // See comments in ParseIfStatement for why we create a scope for
1884 // for-init-statement/condition and a new scope for substatement in C++.
1885 //
David Majnemer2206bf52014-03-05 08:57:59 +00001886 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1887 Tok.is(tok::l_brace));
1888
1889 // The body of the for loop has the same local mangling number as the
1890 // for-init-statement.
1891 // It will only be incremented if the body contains other things that would
1892 // normally increment the mangling number (like a compound statement).
1893 if (C99orCXXorObjC)
David Majnemera7f8c462015-03-19 21:54:30 +00001894 getCurScope()->decrementMSManglingNumber();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001895
Chris Lattner9075bd72006-08-10 04:59:57 +00001896 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001897 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001898
Chris Lattner8fb26252007-08-22 05:28:50 +00001899 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001900 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001901
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001902 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001903 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001904
1905 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001906 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001907
Richard Smith02e85f32011-04-14 22:09:26 +00001908 if (ForEach)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001909 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1910 Body.get());
Mike Stump11289f42009-09-09 15:08:12 +00001911
Richard Smith8baa5002018-09-28 18:44:09 +00001912 if (ForRangeInfo.ParsedForRangeDecl())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001913 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001914
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001915 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
Richard Smith03a4aa32016-06-23 19:02:52 +00001916 SecondPart, ThirdPart, T.getCloseLocation(),
1917 Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001918}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001919
Chris Lattner503fadc2006-08-10 05:45:44 +00001920/// ParseGotoStatement
1921/// jump-statement:
1922/// 'goto' identifier ';'
1923/// [GNU] 'goto' '*' expression ';'
1924///
1925/// Note: this lets the caller parse the end ';'.
1926///
Richard Smithc202b282012-04-14 00:33:13 +00001927StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001928 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001929 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001930
John McCalldadc5752010-08-24 06:29:42 +00001931 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001932 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001933 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1934 Tok.getLocation());
1935 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001936 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001937 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001938 // GNU indirect goto extension.
1939 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001940 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001941 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001942 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001943 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001944 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001945 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001946 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001947 } else {
Alp Tokerec543272013-12-24 09:48:30 +00001948 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001949 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001950 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001951
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001952 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001953}
1954
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001955/// ParseContinueStatement
1956/// jump-statement:
1957/// 'continue' ';'
1958///
1959/// Note: this lets the caller parse the end ';'.
1960///
Richard Smithc202b282012-04-14 00:33:13 +00001961StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001962 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001963 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001964}
1965
1966/// ParseBreakStatement
1967/// jump-statement:
1968/// 'break' ';'
1969///
1970/// Note: this lets the caller parse the end ';'.
1971///
Richard Smithc202b282012-04-14 00:33:13 +00001972StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001973 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001974 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001975}
1976
Chris Lattner503fadc2006-08-10 05:45:44 +00001977/// ParseReturnStatement
1978/// jump-statement:
1979/// 'return' expression[opt] ';'
Richard Smith0e304ea2015-10-22 04:46:14 +00001980/// 'return' braced-init-list ';'
1981/// 'co_return' expression[opt] ';'
1982/// 'co_return' braced-init-list ';'
Richard Smithc202b282012-04-14 00:33:13 +00001983StmtResult Parser::ParseReturnStatement() {
Richard Smith0e304ea2015-10-22 04:46:14 +00001984 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1985 "Not a return stmt!");
1986 bool IsCoreturn = Tok.is(tok::kw_co_return);
Chris Lattneraf635312006-10-16 06:06:51 +00001987 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001988
John McCalldadc5752010-08-24 06:29:42 +00001989 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001990 if (Tok.isNot(tok::semi)) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001991 if (!IsCoreturn)
1992 PreferredType.enterReturn(Actions, Tok.getLocation());
Richard Smith0e304ea2015-10-22 04:46:14 +00001993 // FIXME: Code completion for co_return.
1994 if (Tok.is(tok::code_completion) && !IsCoreturn) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001995 Actions.CodeCompleteExpression(getCurScope(),
1996 PreferredType.get(Tok.getLocation()));
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001997 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001998 return StmtError();
1999 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002000
David Blaikiebbafb8a2012-03-11 07:00:24 +00002001 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00002002 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00002003 if (R.isUsable())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002004 Diag(R.get()->getBeginLoc(),
2005 getLangOpts().CPlusPlus11
2006 ? diag::warn_cxx98_compat_generalized_initializer_lists
2007 : diag::ext_generalized_initializer_lists)
2008 << R.get()->getSourceRange();
Douglas Gregore9e27d92011-03-11 23:10:44 +00002009 } else
Nico Weber3ce01c32015-01-04 08:07:54 +00002010 R = ParseExpression();
Serge Pavlovf79bd5c2013-12-04 03:51:59 +00002011 if (R.isInvalid()) {
2012 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002013 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00002014 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00002015 }
Richard Smithcfd53b42015-10-22 06:13:50 +00002016 if (IsCoreturn)
Eric Fiselier20f25cb2017-03-06 23:38:15 +00002017 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002018 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
Chris Lattner503fadc2006-08-10 05:45:44 +00002019}
Chris Lattner0116c472006-08-15 06:03:28 +00002020
Alexey Bataevc4fad652016-01-13 11:18:54 +00002021StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
Richard Smitha6e8d5e2019-02-15 00:27:53 +00002022 ParsedStmtContext StmtCtx,
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002023 SourceLocation *TrailingElseLoc,
2024 ParsedAttributesWithRange &Attrs) {
2025 // Create temporary attribute list.
2026 ParsedAttributesWithRange TempAttrs(AttrFactory);
2027
Mark Heffernanbd26f5e2014-07-21 18:08:34 +00002028 // Get loop hints and consume annotated token.
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002029 while (Tok.is(tok::annot_pragma_loop_hint)) {
Tyler Nowicki0c9b34b2014-07-31 20:15:14 +00002030 LoopHint Hint;
2031 if (!HandlePragmaLoopHint(Hint))
2032 continue;
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002033
Tyler Nowicki0c9b34b2014-07-31 20:15:14 +00002034 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002035 ArgsUnion(Hint.ValueExpr)};
Mark Heffernanbd26f5e2014-07-21 18:08:34 +00002036 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
2037 Hint.PragmaNameLoc->Loc, ArgHints, 4,
Erich Keanee891aa92018-07-13 15:07:47 +00002038 ParsedAttr::AS_Pragma);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002039 }
2040
2041 // Get the next statement.
2042 MaybeParseCXX11Attributes(Attrs);
2043
2044 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
Richard Smitha6e8d5e2019-02-15 00:27:53 +00002045 Stmts, StmtCtx, TrailingElseLoc, Attrs);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00002046
2047 Attrs.takeAllFrom(TempAttrs);
2048 return S;
2049}
2050
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002051Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002052 assert(Tok.is(tok::l_brace));
2053 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002054
Jordan Rose1e879d82018-03-23 00:07:18 +00002055 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00002056 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002057
Alexey Bataev3d42f342015-11-20 07:02:57 +00002058 // Save and reset current vtordisp stack if we have entered a C++ method body.
2059 bool IsCXXMethod =
2060 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
Denis Zobnin2290dac2016-04-29 11:27:00 +00002061 Sema::PragmaStackSentinelRAII
2062 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
Alexey Bataev3d42f342015-11-20 07:02:57 +00002063
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002064 // Do not enter a scope for the brace, as the arguments are in the same scope
2065 // (the function body) as the body itself. Instead, just read the statement
2066 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002067 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002068
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002069 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002070 if (FnBody.isInvalid()) {
2071 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002072 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002073 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002074
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002075 BodyScope.Exit();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002076 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002077}
Sebastian Redlb219c902008-12-21 16:41:36 +00002078
Sebastian Redla7b98a72009-04-26 20:35:05 +00002079/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2080///
2081/// function-try-block:
2082/// 'try' ctor-initializer[opt] compound-statement handler-seq
2083///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002084Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002085 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2086 SourceLocation TryLoc = ConsumeToken();
2087
Jordan Rose1e879d82018-03-23 00:07:18 +00002088 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00002089 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002090
2091 // Constructor initializer list?
2092 if (Tok.is(tok::colon))
2093 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002094 else
2095 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002096
Alexey Bataev3d42f342015-11-20 07:02:57 +00002097 // Save and reset current vtordisp stack if we have entered a C++ method body.
2098 bool IsCXXMethod =
2099 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
Denis Zobnin2290dac2016-04-29 11:27:00 +00002100 Sema::PragmaStackSentinelRAII
2101 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
Alexey Bataev3d42f342015-11-20 07:02:57 +00002102
Sebastian Redld98ecd62009-04-26 21:08:36 +00002103 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002104 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00002105 // If we failed to parse the try-catch, we just give the function an empty
2106 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002107 if (FnBody.isInvalid()) {
2108 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002109 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002110 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002111
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002112 BodyScope.Exit();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002113 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002114}
2115
Erik Verbruggen6e922512012-04-12 10:11:59 +00002116bool Parser::trySkippingFunctionBody() {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002117 assert(SkipFunctionBodies &&
2118 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002119 if (!PP.isCodeCompletionEnabled()) {
Olivier Goffartf9e890c2016-06-16 21:40:06 +00002120 SkipFunctionBody();
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002121 return true;
2122 }
2123
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002124 // We're in code-completion mode. Skip parsing for all function bodies unless
2125 // the body contains the code-completion point.
2126 TentativeParsingAction PA(*this);
Olivier Goffartf9e890c2016-06-16 21:40:06 +00002127 bool IsTryCatch = Tok.is(tok::kw_try);
2128 CachedTokens Toks;
2129 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2130 if (llvm::any_of(Toks, [](const Token &Tok) {
2131 return Tok.is(tok::code_completion);
2132 })) {
2133 PA.Revert();
2134 return false;
2135 }
2136 if (ErrorInPrologue) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002137 PA.Commit();
Olivier Goffartf9e890c2016-06-16 21:40:06 +00002138 SkipMalformedDecl();
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002139 return true;
2140 }
Olivier Goffartf9e890c2016-06-16 21:40:06 +00002141 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2142 PA.Revert();
2143 return false;
2144 }
2145 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2146 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2147 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2148 PA.Revert();
2149 return false;
2150 }
2151 }
2152 PA.Commit();
2153 return true;
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002154}
2155
Sebastian Redlb219c902008-12-21 16:41:36 +00002156/// ParseCXXTryBlock - Parse a C++ try-block.
2157///
2158/// try-block:
2159/// 'try' compound-statement handler-seq
2160///
Richard Smithc202b282012-04-14 00:33:13 +00002161StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002162 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2163
2164 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002165 return ParseCXXTryBlockCommon(TryLoc);
2166}
2167
2168/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2169/// function-try-block.
2170///
2171/// try-block:
2172/// 'try' compound-statement handler-seq
2173///
2174/// function-try-block:
2175/// 'try' ctor-initializer[opt] compound-statement handler-seq
2176///
2177/// handler-seq:
2178/// handler handler-seq[opt]
2179///
John Wiegley1c0675e2011-04-28 01:08:34 +00002180/// [Borland] try-block:
2181/// 'try' compound-statement seh-except-block
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002182/// 'try' compound-statement seh-finally-block
John Wiegley1c0675e2011-04-28 01:08:34 +00002183///
David Blaikie1c9c9042012-11-10 01:04:23 +00002184StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002185 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002186 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Richard Smithc202b282012-04-14 00:33:13 +00002187
Momchil Velikov57c681f2017-08-10 15:43:06 +00002188 StmtResult TryBlock(ParseCompoundStatement(
2189 /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2190 Scope::CompoundStmtScope |
2191 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002192 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002193 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002194
John Wiegley1c0675e2011-04-28 01:08:34 +00002195 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002196
Richard Smithc202b282012-04-14 00:33:13 +00002197 if ((Tok.is(tok::identifier) &&
2198 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2199 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002200 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2201 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002202 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002203 SourceLocation Loc = ConsumeToken();
2204 Handler = ParseSEHExceptBlock(Loc);
2205 }
2206 else {
2207 SourceLocation Loc = ConsumeToken();
2208 Handler = ParseSEHFinallyBlock(Loc);
2209 }
2210 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002211 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002212
John Wiegley1c0675e2011-04-28 01:08:34 +00002213 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2214 TryLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002215 TryBlock.get(),
Warren Huntf6be4cb2014-07-25 20:52:51 +00002216 Handler.get());
Sebastian Redlb219c902008-12-21 16:41:36 +00002217 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002218 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002219 StmtVector Handlers;
Richard Smithc2c8bb82013-10-15 01:34:54 +00002220
2221 // C++11 attributes can't appear here, despite this context seeming
2222 // statement-like.
2223 DiagnoseAndSkipCXX11Attributes();
Sebastian Redlb219c902008-12-21 16:41:36 +00002224
John Wiegley1c0675e2011-04-28 01:08:34 +00002225 if (Tok.isNot(tok::kw_catch))
2226 return StmtError(Diag(Tok, diag::err_expected_catch));
2227 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002228 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002229 if (!Handler.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002230 Handlers.push_back(Handler.get());
John Wiegley1c0675e2011-04-28 01:08:34 +00002231 }
2232 // Don't bother creating the full statement if we don't have any usable
2233 // handlers.
2234 if (Handlers.empty())
2235 return StmtError();
2236
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002237 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002238 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002239}
2240
2241/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2242///
Richard Smith1dba27c2013-01-29 09:02:09 +00002243/// handler:
2244/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002245///
Richard Smith1dba27c2013-01-29 09:02:09 +00002246/// exception-declaration:
2247/// attribute-specifier-seq[opt] type-specifier-seq declarator
2248/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2249/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002250///
David Blaikie1c9c9042012-11-10 01:04:23 +00002251StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002252 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2253
2254 SourceLocation CatchLoc = ConsumeToken();
2255
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002256 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002257 if (T.expectAndConsume())
Sebastian Redlb219c902008-12-21 16:41:36 +00002258 return StmtError();
2259
2260 // C++ 3.3.2p3:
2261 // The name in a catch exception-declaration is local to the handler and
2262 // shall not be redeclared in the outermost block of the handler.
Brian Gesiake8b3d632019-03-22 16:08:29 +00002263 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2264 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002265
2266 // exception-declaration is equivalent to '...' or a parameter-declaration
2267 // without default arguments.
Craig Topper161e4db2014-05-21 06:02:52 +00002268 Decl *ExceptionDecl = nullptr;
Sebastian Redlb219c902008-12-21 16:41:36 +00002269 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002270 ParsedAttributesWithRange Attributes(AttrFactory);
2271 MaybeParseCXX11Attributes(Attributes);
2272
John McCall084e83d2011-03-24 11:26:52 +00002273 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002274 DS.takeAttributesFrom(Attributes);
2275
Sebastian Redl54c04d42008-12-22 19:15:10 +00002276 if (ParseCXXTypeSpecifierSeq(DS))
2277 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002278
Faisal Vali421b2d12017-12-29 05:41:00 +00002279 Declarator ExDecl(DS, DeclaratorContext::CXXCatchContext);
Sebastian Redlb219c902008-12-21 16:41:36 +00002280 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002281 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002282 } else
2283 ConsumeToken();
2284
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002285 T.consumeClose();
2286 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002287 return StmtError();
2288
2289 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002290 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redlb219c902008-12-21 16:41:36 +00002291
Alexis Hunt96d5c762009-11-21 08:43:09 +00002292 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Brian Gesiake8b3d632019-03-22 16:08:29 +00002293 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002294 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002295 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002296
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002297 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
Sebastian Redlb219c902008-12-21 16:41:36 +00002298}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002299
2300void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002301 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002302 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002303 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002304
Douglas Gregor43edb322011-10-24 22:31:10 +00002305 // Handle dependent statements by parsing the braces as a compound statement.
2306 // This is not the same behavior as Visual C++, which don't treat this as a
2307 // compound statement, but for Clang's type checking we can't have anything
2308 // inside these braces escaping to the surrounding code.
2309 if (Result.Behavior == IEB_Dependent) {
2310 if (!Tok.is(tok::l_brace)) {
Alp Tokerec543272013-12-24 09:48:30 +00002311 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smithc202b282012-04-14 00:33:13 +00002312 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002313 }
Richard Smithc202b282012-04-14 00:33:13 +00002314
2315 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002316 if (Compound.isInvalid())
2317 return;
Richard Smithc202b282012-04-14 00:33:13 +00002318
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002319 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2320 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002321 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002322 Result.Name,
2323 Compound.get());
2324 if (DepResult.isUsable())
2325 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002326 return;
2327 }
Richard Smithc202b282012-04-14 00:33:13 +00002328
Douglas Gregor43edb322011-10-24 22:31:10 +00002329 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2330 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00002331 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002332 return;
2333 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002334
Douglas Gregor43edb322011-10-24 22:31:10 +00002335 switch (Result.Behavior) {
2336 case IEB_Parse:
2337 // Parse the statements below.
2338 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002339
Douglas Gregor43edb322011-10-24 22:31:10 +00002340 case IEB_Dependent:
2341 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002342
Douglas Gregor43edb322011-10-24 22:31:10 +00002343 case IEB_Skip:
2344 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002345 return;
2346 }
2347
2348 // Condition is true, parse the statements.
2349 while (Tok.isNot(tok::r_brace)) {
Richard Smitha6e8d5e2019-02-15 00:27:53 +00002350 StmtResult R =
2351 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002352 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002353 Stmts.push_back(R.get());
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002354 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002355 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002356}
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00002357
2358bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2359 MaybeParseGNUAttributes(Attrs);
2360
2361 if (Attrs.empty())
2362 return true;
2363
Erich Keanee891aa92018-07-13 15:07:47 +00002364 if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00002365 return true;
2366
2367 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2368 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);
2369 return false;
2370 }
2371 return true;
2372}