blob: 1dafae0c94c9b9cb65642b9ee8f92be1edcb2e49 [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner0ccd51e2006-08-09 05:47:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Statement and Block portions of the Parser
11// interface.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Parse/Parser.h"
Chris Lattner8a9a97a2009-12-10 00:21:05 +000016#include "RAIIObjectsForParser.h"
John McCallf413f5e2013-05-03 00:10:13 +000017#include "clang/AST/ASTContext.h"
Aaron Ballmanb06b15a2014-06-06 12:40:24 +000018#include "clang/Basic/Attributes.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/PrettyStackTrace.h"
John McCall8b0666c2010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Aaron Ballmanb06b15a2014-06-06 12:40:24 +000022#include "clang/Sema/LoopHint.h"
John McCallfaf5fb42010-08-26 23:41:50 +000023#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/Scope.h"
Richard Smith4f605af2012-08-18 00:55:03 +000025#include "clang/Sema/TypoCorrection.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000026#include "llvm/ADT/SmallString.h"
Chris Lattner0ccd51e2006-08-09 05:47:47 +000027using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// C99 6.8: Statements and Blocks.
31//===----------------------------------------------------------------------===//
32
Richard Smith426a47b2013-10-28 22:04:30 +000033/// \brief Parse a standalone statement (for instance, as the body of an 'if',
34/// 'while', or 'for').
35StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) {
36 StmtResult Res;
37
38 // We may get back a null statement if we found a #pragma. Keep going until
39 // we get an actual statement.
40 do {
41 StmtVector Stmts;
42 Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
43 } while (!Res.isInvalid() && !Res.get());
44
45 return Res;
46}
47
Chris Lattner0ccd51e2006-08-09 05:47:47 +000048/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
49/// StatementOrDeclaration:
50/// statement
51/// declaration
52///
53/// statement:
54/// labeled-statement
55/// compound-statement
56/// expression-statement
57/// selection-statement
58/// iteration-statement
59/// jump-statement
Argyrios Kyrtzidisdee82912008-09-07 18:58:01 +000060/// [C++] declaration-statement
Sebastian Redlb219c902008-12-21 16:41:36 +000061/// [C++] try-block
John Wiegley1c0675e2011-04-28 01:08:34 +000062/// [MS] seh-try-block
Fariborz Jahanian90814572007-10-04 20:19:06 +000063/// [OBC] objc-throw-statement
64/// [OBC] objc-try-catch-statement
Fariborz Jahanianf89ca382008-01-29 18:21:32 +000065/// [OBC] objc-synchronized-statement
Chris Lattner0116c472006-08-15 06:03:28 +000066/// [GNU] asm-statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +000067/// [OMP] openmp-construct [TODO]
68///
69/// labeled-statement:
70/// identifier ':' statement
71/// 'case' constant-expression ':' statement
72/// 'default' ':' statement
73///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000074/// selection-statement:
75/// if-statement
76/// switch-statement
77///
78/// iteration-statement:
79/// while-statement
80/// do-statement
81/// for-statement
82///
Chris Lattner9075bd72006-08-10 04:59:57 +000083/// expression-statement:
84/// expression[opt] ';'
85///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000086/// jump-statement:
87/// 'goto' identifier ';'
88/// 'continue' ';'
89/// 'break' ';'
90/// 'return' expression[opt] ';'
Chris Lattner503fadc2006-08-10 05:45:44 +000091/// [GNU] 'goto' '*' expression ';'
Chris Lattner0ccd51e2006-08-09 05:47:47 +000092///
Fariborz Jahanian90814572007-10-04 20:19:06 +000093/// [OBC] objc-throw-statement:
94/// [OBC] '@' 'throw' expression ';'
Mike Stump11289f42009-09-09 15:08:12 +000095/// [OBC] '@' 'throw' ';'
96///
John McCalldadc5752010-08-24 06:29:42 +000097StmtResult
Nico Weber3cef1082011-12-22 23:26:17 +000098Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
99 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000100
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +0000101 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000102
Richard Smithc202b282012-04-14 00:33:13 +0000103 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +0000104 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
Richard Smithc202b282012-04-14 00:33:13 +0000105
106 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
107 OnlyStatement, TrailingElseLoc, Attrs);
108
109 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
110 "attributes on empty statement");
111
112 if (Attrs.empty() || Res.isInvalid())
113 return Res;
114
115 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
116}
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 Smithc202b282012-04-14 00:33:13 +0000147StmtResult
148Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
149 bool OnlyStatement, SourceLocation *TrailingElseLoc,
150 ParsedAttributesWithRange &Attrs) {
Craig Topper161e4db2014-05-21 06:02:52 +0000151 const char *SemiError = nullptr;
Richard Smithc202b282012-04-14 00:33:13 +0000152 StmtResult Res;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000153
Chris Lattner503fadc2006-08-10 05:45:44 +0000154 // Cases in this switch statement should fall through if the parser expects
155 // the token to end in a semicolon (in which case SemiError should be set),
156 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000157Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000158 tok::TokenKind Kind = Tok.getKind();
159 SourceLocation AtLoc;
160 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000161 case tok::at: // May be a @try or @throw statement
162 {
Richard Smithc202b282012-04-14 00:33:13 +0000163 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000164 AtLoc = ConsumeToken(); // consume @
Sebastian Redlbab9a4b2008-12-11 20:12:42 +0000165 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000166 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000167
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000168 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000169 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000170 cutOffParsing();
171 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000172
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000173 case tok::identifier: {
174 Token Next = NextToken();
175 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000176 // identifier ':' statement
Richard Smithc202b282012-04-14 00:33:13 +0000177 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000178 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000179
Richard Smith4f605af2012-08-18 00:55:03 +0000180 // Look up the identifier, and typo-correct it to a keyword if it's not
181 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000182 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000183 // Try to limit which sets of keywords should be included in typo
184 // correction based on what the next token is.
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000185 if (TryAnnotateName(/*IsAddressOfOperand*/ false,
186 llvm::make_unique<StatementFilterCCC>(Next)) ==
187 ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000188 // Handle errors here by skipping up to the next semicolon or '}', and
189 // eat the semicolon if that's what stopped us.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000190 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000191 if (Tok.is(tok::semi))
192 ConsumeToken();
193 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000194 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000195
Richard Smith4f605af2012-08-18 00:55:03 +0000196 // If the identifier was typo-corrected, try again.
197 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000198 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000199 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000200
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000201 // Fall through
202 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000203
Chris Lattner803802d2009-03-24 17:04:48 +0000204 default: {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000205 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000206 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Rafael Espindola1bd906d2014-10-22 14:27:08 +0000207 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000208 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000209 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000210 }
211
212 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000213 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000214 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Richard Smithc202b282012-04-14 00:33:13 +0000217 return ParseExprStatement();
Chris Lattner803802d2009-03-24 17:04:48 +0000218 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000219
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000220 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000221 return ParseCaseStatement();
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000222 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000223 return ParseDefaultStatement();
Sebastian Redl042ad952008-12-11 19:30:53 +0000224
Chris Lattner9075bd72006-08-10 04:59:57 +0000225 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000226 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000227 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000228 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
229 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000230 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000231
Chris Lattner9075bd72006-08-10 04:59:57 +0000232 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000233 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000234 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000235 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000236
Chris Lattner9075bd72006-08-10 04:59:57 +0000237 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000238 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000239 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000240 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000241 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000242 break;
243 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000244 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000245
246 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000247 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000248 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000249 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000250 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000251 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000252 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000253 break;
254 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000255 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000256 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000257 break;
258 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000259 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000260 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000261 break;
Richard Smith0e304ea2015-10-22 04:46:14 +0000262 case tok::kw_co_return: // C++ Coroutines: co_return statement
263 Res = ParseReturnStatement();
264 SemiError = "co_return";
265 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000266
Sebastian Redlb219c902008-12-21 16:41:36 +0000267 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000268 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000269 bool msAsm = false;
270 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000271 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000272 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000273 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000274 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000275 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000276
Reid Kleckner6d8d22a2014-06-25 00:28:35 +0000277 case tok::kw___if_exists:
278 case tok::kw___if_not_exists:
279 ProhibitAttributes(Attrs);
280 ParseMicrosoftIfExistsStatement(Stmts);
281 // An __if_exists block is like a compound statement, but it doesn't create
282 // a new scope.
283 return StmtEmpty();
284
Sebastian Redlb219c902008-12-21 16:41:36 +0000285 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000286 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000287
288 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000289 ProhibitAttributes(Attrs); // TODO: is it correct?
290 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000291
Nico Weberc7d05962014-07-06 22:32:59 +0000292 case tok::kw___leave:
293 Res = ParseSEHLeaveStatement();
294 SemiError = "__leave";
295 break;
296
Eli Friedmanec52f922012-02-23 23:47:16 +0000297 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000298 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000299 HandlePragmaVisibility();
300 return StmtEmpty();
301
302 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000303 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000304 HandlePragmaPack();
305 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000306
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000307 case tok::annot_pragma_msstruct:
308 ProhibitAttributes(Attrs);
309 HandlePragmaMSStruct();
310 return StmtEmpty();
311
Eli Friedmanae8ee252012-10-08 23:52:38 +0000312 case tok::annot_pragma_align:
313 ProhibitAttributes(Attrs);
314 HandlePragmaAlign();
315 return StmtEmpty();
316
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000317 case tok::annot_pragma_weak:
318 ProhibitAttributes(Attrs);
319 HandlePragmaWeak();
320 return StmtEmpty();
321
322 case tok::annot_pragma_weakalias:
323 ProhibitAttributes(Attrs);
324 HandlePragmaWeakAlias();
325 return StmtEmpty();
326
327 case tok::annot_pragma_redefine_extname:
328 ProhibitAttributes(Attrs);
329 HandlePragmaRedefineExtname();
330 return StmtEmpty();
331
Eli Friedman68be1642012-10-04 02:36:51 +0000332 case tok::annot_pragma_fp_contract:
Richard Smithca9b0b62013-11-15 21:10:54 +0000333 ProhibitAttributes(Attrs);
Lang Hamesa930e712012-10-21 01:10:01 +0000334 Diag(Tok, diag::err_pragma_fp_contract_scope);
335 ConsumeToken();
336 return StmtError();
337
Eli Friedman68be1642012-10-04 02:36:51 +0000338 case tok::annot_pragma_opencl_extension:
339 ProhibitAttributes(Attrs);
340 HandlePragmaOpenCLExtension();
341 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000342
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000343 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000344 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000345 return HandlePragmaCaptured();
346
Alexey Bataeva769e072013-03-22 06:34:35 +0000347 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000348 ProhibitAttributes(Attrs);
Alexey Bataev68446b72014-07-18 07:47:19 +0000349 return ParseOpenMPDeclarativeOrExecutableDirective(!OnlyStatement);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000350
David Majnemer4bb09802014-02-10 19:50:15 +0000351 case tok::annot_pragma_ms_pointers_to_members:
352 ProhibitAttributes(Attrs);
353 HandlePragmaMSPointersToMembers();
354 return StmtEmpty();
355
Warren Huntc3b18962014-04-08 22:30:47 +0000356 case tok::annot_pragma_ms_pragma:
357 ProhibitAttributes(Attrs);
358 HandlePragmaMSPragma();
359 return StmtEmpty();
Aaron Ballmanb06b15a2014-06-06 12:40:24 +0000360
Alexey Bataev3d42f342015-11-20 07:02:57 +0000361 case tok::annot_pragma_ms_vtordisp:
362 ProhibitAttributes(Attrs);
363 HandlePragmaMSVtorDisp();
364 return StmtEmpty();
365
Aaron Ballmanb06b15a2014-06-06 12:40:24 +0000366 case tok::annot_pragma_loop_hint:
367 ProhibitAttributes(Attrs);
368 return ParsePragmaLoopHint(Stmts, OnlyStatement, TrailingElseLoc, Attrs);
Richard Smithba3a4f92016-01-12 21:59:26 +0000369
370 case tok::annot_pragma_dump:
371 HandlePragmaDump();
372 return StmtEmpty();
Sebastian Redlb219c902008-12-21 16:41:36 +0000373 }
374
Chris Lattner503fadc2006-08-10 05:45:44 +0000375 // If we reached this code, the statement must end in a semicolon.
Alp Toker97650562014-01-10 11:19:30 +0000376 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000377 // If the result was valid, then we do want to diagnose this. Use
378 // ExpectAndConsume to emit the diagnostic, even though we know it won't
379 // succeed.
380 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000381 // Skip until we see a } or ;, but don't eat it.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000382 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner503fadc2006-08-10 05:45:44 +0000383 }
Mike Stump11289f42009-09-09 15:08:12 +0000384
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000385 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000386}
387
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000388/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000389StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000390 // If a case keyword is missing, this is where it should be inserted.
391 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000392
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000393 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000394 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000395 if (Expr.isInvalid()) {
396 // If the expression is invalid, skip ahead to the next semicolon or '}'.
397 // Not doing this opens us up to the possibility of infinite loops if
398 // ParseExpression does not consume any tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000399 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000400 if (Tok.is(tok::semi))
401 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000402 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000403 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000404
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000405 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
406 Actions.CheckCaseExpression(Expr.get())) {
407 // If a constant expression is followed by a colon inside a switch block,
408 // suggest a missing case keyword.
409 Diag(OldToken, diag::err_expected_case_before_expression)
410 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000411
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000412 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000413 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000414 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000415
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000416 // Otherwise, eat the semicolon.
417 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000418 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000419}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000420
John Wiegley1c0675e2011-04-28 01:08:34 +0000421/// ParseSEHTryBlockCommon
422///
423/// seh-try-block:
424/// '__try' compound-statement seh-handler
425///
426/// seh-handler:
427/// seh-except-block
428/// seh-finally-block
429///
Nico Weberdd256742015-02-25 01:43:27 +0000430StmtResult Parser::ParseSEHTryBlock() {
431 assert(Tok.is(tok::kw___try) && "Expected '__try'");
432 SourceLocation TryLoc = ConsumeToken();
433
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000434 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000435 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley1c0675e2011-04-28 01:08:34 +0000436
Warren Huntf6be4cb2014-07-25 20:52:51 +0000437 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
438 Scope::DeclScope | Scope::SEHTryScope));
John Wiegley1c0675e2011-04-28 01:08:34 +0000439 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000440 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000441
442 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000443 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000444 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000445 SourceLocation Loc = ConsumeToken();
446 Handler = ParseSEHExceptBlock(Loc);
447 } else if (Tok.is(tok::kw___finally)) {
448 SourceLocation Loc = ConsumeToken();
449 Handler = ParseSEHFinallyBlock(Loc);
450 } else {
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000451 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
John Wiegley1c0675e2011-04-28 01:08:34 +0000452 }
453
454 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000455 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000456
457 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
458 TryLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000459 TryBlock.get(),
Warren Huntf6be4cb2014-07-25 20:52:51 +0000460 Handler.get());
John Wiegley1c0675e2011-04-28 01:08:34 +0000461}
462
463/// ParseSEHExceptBlock - Handle __except
464///
465/// seh-except-block:
466/// '__except' '(' seh-filter-expression ')' compound-statement
467///
468StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
469 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
470 raii2(Ident___exception_code, false),
471 raii3(Ident_GetExceptionCode, false);
472
Alp Toker383d2c42014-01-01 03:08:43 +0000473 if (ExpectAndConsume(tok::l_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000474 return StmtError();
475
Reid Kleckner1d59f992015-01-22 01:36:17 +0000476 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
477 Scope::SEHExceptScope);
John Wiegley1c0675e2011-04-28 01:08:34 +0000478
David Blaikiebbafb8a2012-03-11 07:00:24 +0000479 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000480 Ident__exception_info->setIsPoisoned(false);
481 Ident___exception_info->setIsPoisoned(false);
482 Ident_GetExceptionInfo->setIsPoisoned(false);
483 }
Reid Kleckner1d59f992015-01-22 01:36:17 +0000484
485 ExprResult FilterExpr;
486 {
487 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
488 Scope::SEHFilterScope);
Reid Kleckner85368fb2015-04-02 22:09:32 +0000489 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Reid Kleckner1d59f992015-01-22 01:36:17 +0000490 }
Francois Pichetbfaf4772011-04-28 03:14:31 +0000491
David Blaikiebbafb8a2012-03-11 07:00:24 +0000492 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000493 Ident__exception_info->setIsPoisoned(true);
494 Ident___exception_info->setIsPoisoned(true);
495 Ident_GetExceptionInfo->setIsPoisoned(true);
496 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000497
498 if(FilterExpr.isInvalid())
499 return StmtError();
500
Alp Toker383d2c42014-01-01 03:08:43 +0000501 if (ExpectAndConsume(tok::r_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000502 return StmtError();
503
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000504 if (Tok.isNot(tok::l_brace))
505 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
506
Richard Smithc202b282012-04-14 00:33:13 +0000507 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000508
509 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000510 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000511
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000512 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
John Wiegley1c0675e2011-04-28 01:08:34 +0000513}
514
515/// ParseSEHFinallyBlock - Handle __finally
516///
517/// seh-finally-block:
518/// '__finally' compound-statement
519///
Nico Weberd64657f2015-03-09 02:47:59 +0000520StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000521 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
522 raii2(Ident___abnormal_termination, false),
523 raii3(Ident_AbnormalTermination, false);
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
Nico Weberd64657f2015-03-09 02:47:59 +0000528 ParseScope FinallyScope(this, 0);
529 Actions.ActOnStartSEHFinallyBlock();
530
Richard Smithc202b282012-04-14 00:33:13 +0000531 StmtResult Block(ParseCompoundStatement());
Nico Weberce903292015-03-09 03:17:15 +0000532 if(Block.isInvalid()) {
533 Actions.ActOnAbortSEHFinallyBlock();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000534 return Block;
Nico Weberce903292015-03-09 03:17:15 +0000535 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000536
Nico Weberd64657f2015-03-09 02:47:59 +0000537 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000538}
539
Nico Weberc7d05962014-07-06 22:32:59 +0000540/// Handle __leave
541///
542/// seh-leave-statement:
543/// '__leave' ';'
544///
545StmtResult Parser::ParseSEHLeaveStatement() {
546 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
547 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
548}
549
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000550/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000551///
552/// labeled-statement:
553/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000554/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000555///
Richard Smithc202b282012-04-14 00:33:13 +0000556StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000557 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
558 "Not an identifier!");
559
560 Token IdentTok = Tok; // Save the whole token.
561 ConsumeToken(); // eat the identifier.
562
563 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000564
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000565 // identifier ':' statement
566 SourceLocation ColonLoc = ConsumeToken();
567
Richard Smitha3e01cf2013-11-15 22:45:29 +0000568 // Read label attributes, if present.
569 StmtResult SubStmt;
570 if (Tok.is(tok::kw___attribute)) {
571 ParsedAttributesWithRange TempAttrs(AttrFactory);
572 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000573
Richard Smitha3e01cf2013-11-15 22:45:29 +0000574 // In C++, GNU attributes only apply to the label if they are followed by a
575 // semicolon, to disambiguate label attributes from attributes on a labeled
576 // declaration.
577 //
578 // This doesn't quite match what GCC does; if the attribute list is empty
579 // and followed by a semicolon, GCC will reject (it appears to parse the
580 // attributes as part of a statement in that case). That looks like a bug.
581 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
582 attrs.takeAllFrom(TempAttrs);
583 else if (isDeclarationStatement()) {
584 StmtVector Stmts;
585 // FIXME: We should do this whether or not we have a declaration
586 // statement, but that doesn't work correctly (because ProhibitAttributes
587 // can't handle GNU attributes), so only call it in the one case where
588 // GNU attributes are allowed.
589 SubStmt = ParseStatementOrDeclarationAfterAttributes(
Craig Topper161e4db2014-05-21 06:02:52 +0000590 Stmts, /*OnlyStmts*/ true, nullptr, TempAttrs);
Richard Smitha3e01cf2013-11-15 22:45:29 +0000591 if (!TempAttrs.empty() && !SubStmt.isInvalid())
592 SubStmt = Actions.ProcessStmtAttributes(
593 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
594 } else {
Alp Toker383d2c42014-01-01 03:08:43 +0000595 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smitha3e01cf2013-11-15 22:45:29 +0000596 }
597 }
598
599 // If we've not parsed a statement yet, parse one now.
600 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
601 SubStmt = ParseStatement();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000602
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000603 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000604 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000605 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000606
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000607 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
608 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000609 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000610 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000611 attrs.clear();
612 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000613
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000614 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
615 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000616}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000617
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000618/// ParseCaseStatement
619/// labeled-statement:
620/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000621/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000622///
Richard Smithc202b282012-04-14 00:33:13 +0000623StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000624 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000625
Chris Lattner34a22092009-03-04 04:23:07 +0000626 // It is very very common for code to contain many case statements recursively
627 // nested, as in (but usually without indentation):
628 // case 1:
629 // case 2:
630 // case 3:
631 // case 4:
632 // case 5: etc.
633 //
634 // Parsing this naively works, but is both inefficient and can cause us to run
635 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000636 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000637 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smitha3e01cf2013-11-15 22:45:29 +0000638 // weirdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000639
Chris Lattner34a22092009-03-04 04:23:07 +0000640 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
641 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000642 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000643
Chris Lattner34a22092009-03-04 04:23:07 +0000644 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
645 // gets updated each time a new case is parsed, and whose body is unset so
646 // far. When parsing 'case 4', this is the 'case 3' node.
Craig Topper161e4db2014-05-21 06:02:52 +0000647 Stmt *DeepestParsedCaseStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattner34a22092009-03-04 04:23:07 +0000649 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000650 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000651 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000652 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
653 ConsumeToken(); // eat the 'case'.
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000654 ColonLoc = SourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000655
Douglas Gregord328d572009-09-21 18:10:23 +0000656 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000657 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000658 cutOffParsing();
659 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000660 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000661
Chris Lattner125c0ee2009-12-10 00:38:54 +0000662 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
663 /// Disable this form of error recovery while we're parsing the case
664 /// expression.
665 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000666
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000667 ExprResult LHS;
668 if (!MissingCase) {
669 LHS = ParseConstantExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000670 if (!getLangOpts().CPlusPlus11) {
671 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
672 return Actions.VerifyIntegerConstantExpression(E);
673 });
674 }
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000675 if (LHS.isInvalid()) {
676 // If constant-expression is parsed unsuccessfully, recover by skipping
677 // current case statement (moving to the colon that ends it).
678 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
679 TryConsumeToken(tok::colon, ColonLoc);
680 continue;
681 }
682 return StmtError();
683 }
684 } else {
685 LHS = Expr;
686 MissingCase = false;
Chris Lattner476c3ad2006-08-13 22:09:58 +0000687 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000688
Chris Lattner34a22092009-03-04 04:23:07 +0000689 // GNU case range extension.
690 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000691 ExprResult RHS;
Alp Tokerec543272013-12-24 09:48:30 +0000692 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
693 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Chris Lattner34a22092009-03-04 04:23:07 +0000694 RHS = ParseConstantExpression();
695 if (RHS.isInvalid()) {
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000696 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
697 TryConsumeToken(tok::colon, ColonLoc);
698 continue;
699 }
Chris Lattner34a22092009-03-04 04:23:07 +0000700 return StmtError();
701 }
702 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000703
Chris Lattner125c0ee2009-12-10 00:38:54 +0000704 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000705
Alp Tokerec543272013-12-24 09:48:30 +0000706 if (TryConsumeToken(tok::colon, ColonLoc)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000707 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
708 TryConsumeToken(tok::coloncolon, ColonLoc)) {
709 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Alp Tokerec543272013-12-24 09:48:30 +0000710 Diag(ColonLoc, diag::err_expected_after)
711 << "'case'" << tok::colon
712 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000713 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000714 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000715 Diag(ExpectedLoc, diag::err_expected_after)
716 << "'case'" << tok::colon
717 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000718 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000719 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000720
John McCalldadc5752010-08-24 06:29:42 +0000721 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000722 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
723 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chris Lattner34a22092009-03-04 04:23:07 +0000725 // If we had a sema error parsing this case, then just ignore it and
726 // continue parsing the sub-stmt.
727 if (Case.isInvalid()) {
728 if (TopLevelCase.isInvalid()) // No parsed case stmts.
729 return ParseStatement();
730 // Otherwise, just don't add it as a nested case.
731 } else {
732 // If this is the first case statement we parsed, it becomes TopLevelCase.
733 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000734 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000735 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000736 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000737 else
John McCallb268a282010-08-23 23:25:46 +0000738 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000739 DeepestParsedCaseStmt = NextDeepest;
740 }
Mike Stump11289f42009-09-09 15:08:12 +0000741
Chris Lattner34a22092009-03-04 04:23:07 +0000742 // Handle all case statements.
743 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000744
Chris Lattner34a22092009-03-04 04:23:07 +0000745 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000746 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattner34a22092009-03-04 04:23:07 +0000748 if (Tok.isNot(tok::r_brace)) {
749 SubStmt = ParseStatement();
750 } else {
751 // Nicely diagnose the common error "switch (X) { case 4: }", which is
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000752 // not valid. If ColonLoc doesn't point to a valid text location, there was
753 // another parsing error, so avoid producing extra diagnostics.
754 if (ColonLoc.isValid()) {
755 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
756 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
757 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
758 }
759 SubStmt = StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +0000760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattner34a22092009-03-04 04:23:07 +0000762 // Install the body into the most deeply-nested case.
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000763 if (DeepestParsedCaseStmt) {
764 // Broken sub-stmt shouldn't prevent forming the case statement properly.
765 if (SubStmt.isInvalid())
766 SubStmt = Actions.ActOnNullStmt(SourceLocation());
767 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
768 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000769
Chris Lattner34a22092009-03-04 04:23:07 +0000770 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000771 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000772}
773
774/// ParseDefaultStatement
775/// labeled-statement:
776/// 'default' ':' statement
777/// Note that this does not parse the 'statement' at the end.
778///
Richard Smithc202b282012-04-14 00:33:13 +0000779StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000780 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000781 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000782
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000783 SourceLocation ColonLoc;
Alp Tokerec543272013-12-24 09:48:30 +0000784 if (TryConsumeToken(tok::colon, ColonLoc)) {
Alp Tokerec543272013-12-24 09:48:30 +0000785 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
Alp Toker97650562014-01-10 11:19:30 +0000786 // Treat "default;" as a typo for "default:".
Alp Tokerec543272013-12-24 09:48:30 +0000787 Diag(ColonLoc, diag::err_expected_after)
788 << "'default'" << tok::colon
789 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000790 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000791 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000792 Diag(ExpectedLoc, diag::err_expected_after)
793 << "'default'" << tok::colon
794 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000795 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000796 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000797
Richard Smith1002d102012-02-17 01:35:32 +0000798 StmtResult SubStmt;
799
800 if (Tok.isNot(tok::r_brace)) {
801 SubStmt = ParseStatement();
802 } else {
803 // Diagnose the common error "switch (X) {... default: }", which is
804 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000805 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000806 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
807 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
808 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000809 }
810
Richard Smith1002d102012-02-17 01:35:32 +0000811 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000812 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000813 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000814
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000815 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000816 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000817}
818
Richard Smithc202b282012-04-14 00:33:13 +0000819StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
820 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000821}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000822
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000823/// ParseCompoundStatement - Parse a "{}" block.
824///
825/// compound-statement: [C99 6.8.2]
826/// { block-item-list[opt] }
827/// [GNU] { label-declarations block-item-list } [TODO]
828///
829/// block-item-list:
830/// block-item
831/// block-item-list block-item
832///
833/// block-item:
834/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000835/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000836/// statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000837///
838/// [GNU] label-declarations:
839/// [GNU] label-declaration
840/// [GNU] label-declarations label-declaration
841///
842/// [GNU] label-declaration:
843/// [GNU] '__label__' identifier-list ';'
844///
Richard Smithc202b282012-04-14 00:33:13 +0000845StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000846 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000847 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000848
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000849 // Enter a scope to hold everything within the compound stmt. Compound
850 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000851 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000852
853 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000854 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000855}
856
Lang Hames2954cea2012-11-03 22:29:05 +0000857/// Parse any pragmas at the start of the compound expression. We handle these
858/// separately since some pragmas (FP_CONTRACT) must appear before any C
859/// statement in the compound, but may be intermingled with other pragmas.
860void Parser::ParseCompoundStatementLeadingPragmas() {
861 bool checkForPragmas = true;
862 while (checkForPragmas) {
863 switch (Tok.getKind()) {
864 case tok::annot_pragma_vis:
865 HandlePragmaVisibility();
866 break;
867 case tok::annot_pragma_pack:
868 HandlePragmaPack();
869 break;
870 case tok::annot_pragma_msstruct:
871 HandlePragmaMSStruct();
872 break;
873 case tok::annot_pragma_align:
874 HandlePragmaAlign();
875 break;
876 case tok::annot_pragma_weak:
877 HandlePragmaWeak();
878 break;
879 case tok::annot_pragma_weakalias:
880 HandlePragmaWeakAlias();
881 break;
882 case tok::annot_pragma_redefine_extname:
883 HandlePragmaRedefineExtname();
884 break;
885 case tok::annot_pragma_opencl_extension:
886 HandlePragmaOpenCLExtension();
887 break;
888 case tok::annot_pragma_fp_contract:
889 HandlePragmaFPContract();
890 break;
David Majnemer4bb09802014-02-10 19:50:15 +0000891 case tok::annot_pragma_ms_pointers_to_members:
892 HandlePragmaMSPointersToMembers();
893 break;
Warren Huntc3b18962014-04-08 22:30:47 +0000894 case tok::annot_pragma_ms_pragma:
895 HandlePragmaMSPragma();
896 break;
Alexey Bataev3d42f342015-11-20 07:02:57 +0000897 case tok::annot_pragma_ms_vtordisp:
898 HandlePragmaMSVtorDisp();
899 break;
Richard Smithba3a4f92016-01-12 21:59:26 +0000900 case tok::annot_pragma_dump:
901 HandlePragmaDump();
902 break;
Lang Hames2954cea2012-11-03 22:29:05 +0000903 default:
904 checkForPragmas = false;
905 break;
906 }
907 }
908
909}
910
Chris Lattnerf2978802007-01-21 06:52:16 +0000911/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000912/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000913/// consume the '}' at the end of the block. It does not manipulate the scope
914/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000915StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000916 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000917 Tok.getLocation(),
918 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000919
920 // Record the state of the FP_CONTRACT pragma, restore on leaving the
921 // compound statement.
922 Sema::FPContractStateRAII SaveFPContractState(Actions);
923
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000924 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000925 BalancedDelimiterTracker T(*this, tok::l_brace);
926 if (T.consumeOpen())
927 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000928
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000929 Sema::CompoundScopeRAII CompoundScope(Actions);
930
Lang Hames2954cea2012-11-03 22:29:05 +0000931 // Parse any pragmas at the beginning of the compound statement.
932 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000933
Lang Hames2954cea2012-11-03 22:29:05 +0000934 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000935
Chris Lattner43e7f312011-02-18 02:08:43 +0000936 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
937 // only allowed at the start of a compound stmt regardless of the language.
938 while (Tok.is(tok::kw___label__)) {
939 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000940
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000941 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000942 while (1) {
943 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +0000944 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner43e7f312011-02-18 02:08:43 +0000945 break;
946 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000947
Chris Lattner43e7f312011-02-18 02:08:43 +0000948 IdentifierInfo *II = Tok.getIdentifierInfo();
949 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000950 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000951
Alp Tokerec543272013-12-24 09:48:30 +0000952 if (!TryConsumeToken(tok::comma))
Chris Lattner43e7f312011-02-18 02:08:43 +0000953 break;
Chris Lattner43e7f312011-02-18 02:08:43 +0000954 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000955
John McCall084e83d2011-03-24 11:26:52 +0000956 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000957 DeclGroupPtrTy Res =
958 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000959 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000960
Chris Lattner02f1b612012-04-28 16:12:17 +0000961 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000962 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000963 Stmts.push_back(R.get());
Chris Lattner43e7f312011-02-18 02:08:43 +0000964 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000965
Richard Smith752ada82015-11-17 23:32:01 +0000966 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
967 Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000968 if (Tok.is(tok::annot_pragma_unused)) {
969 HandlePragmaUnused();
970 continue;
971 }
972
John McCalldadc5752010-08-24 06:29:42 +0000973 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000974 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000975 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000976 } else {
977 // __extension__ can start declarations and it can also be a unary
978 // operator for expressions. Consume multiple __extension__ markers here
979 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000980 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000981 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000982 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000983 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000984
John McCall084e83d2011-03-24 11:26:52 +0000985 ParsedAttributesWithRange attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +0000986 MaybeParseCXX11Attributes(attrs, nullptr,
987 /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000988
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000989 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +0000990 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +0000991 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +0000992 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +0000993 ExtensionRAIIObject O(Diags);
994
Chris Lattner49836b42009-04-02 04:16:50 +0000995 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Rafael Espindola1bd906d2014-10-22 14:27:08 +0000996 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000997 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000998 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000999 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +00001000 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +00001001 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +00001002
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001003 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001004 SkipUntil(tok::semi);
1005 continue;
1006 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +00001007
Alexis Hunt96d5c762009-11-21 08:43:09 +00001008 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +00001009 // Eat the semicolon at the end of stmt and convert the expr into a
1010 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +00001011 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +00001012 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001013 }
1014 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001015
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001016 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001017 Stmts.push_back(R.get());
Chris Lattner30f910e2006-10-16 05:52:41 +00001018 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001019
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001020 SourceLocation CloseLoc = Tok.getLocation();
1021
Chris Lattner0ccd51e2006-08-09 05:47:47 +00001022 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +00001023 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001024 // Recover by creating a compound statement with what we parsed so far,
1025 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +00001026 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001027
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001028 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001029 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +00001030}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001031
Chris Lattnerc0081db2008-12-12 06:31:07 +00001032/// ParseParenExprOrCondition:
1033/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +00001034/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +00001035///
1036/// This function parses and performs error recovery on the specified condition
1037/// or expression (depending on whether we're in C++ or C mode). This function
1038/// goes out of its way to recover well. It returns true if there was a parser
1039/// error (the right paren couldn't be found), which indicates that the caller
1040/// should try to recover harder. It returns false if the condition is
1041/// successfully parsed. Note that a successful parse can still have semantic
1042/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +00001043bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +00001044 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001045 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001046 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001047 BalancedDelimiterTracker T(*this, tok::l_paren);
1048 T.consumeOpen();
1049
David Blaikiebbafb8a2012-03-11 07:00:24 +00001050 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001051 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001052 else {
1053 ExprResult = ParseExpression();
Craig Topper161e4db2014-05-21 06:02:52 +00001054 DeclResult = nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001055
Douglas Gregore60e41a2010-05-06 17:25:47 +00001056 // If required, convert to a boolean value.
1057 if (!ExprResult.isInvalid() && ConvertToBoolean)
1058 ExprResult
John McCallb268a282010-08-23 23:25:46 +00001059 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061
Chris Lattnerc0081db2008-12-12 06:31:07 +00001062 // If the parser was confused by the condition and we don't have a ')', try to
1063 // recover by skipping ahead to a semi and bailing out. If condexp is
1064 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +00001065 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +00001066 SkipUntil(tok::semi);
1067 // Skipping may have stopped if it found the containing ')'. If so, we can
1068 // continue parsing the if statement.
1069 if (Tok.isNot(tok::r_paren))
1070 return true;
1071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattnerc0081db2008-12-12 06:31:07 +00001073 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001074 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +00001075
Chris Lattner70d44982012-04-28 16:24:20 +00001076 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1077 // that all callers are looking for a statement after the condition, so ")"
1078 // isn't valid.
1079 while (Tok.is(tok::r_paren)) {
1080 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1081 << FixItHint::CreateRemoval(Tok.getLocation());
1082 ConsumeParen();
1083 }
Chad Rosier67055f52012-07-10 21:35:27 +00001084
Chris Lattnerc0081db2008-12-12 06:31:07 +00001085 return false;
1086}
1087
1088
Chris Lattnerc951dae2006-08-10 04:23:57 +00001089/// ParseIfStatement
1090/// if-statement: [C99 6.8.4.1]
1091/// 'if' '(' expression ')' statement
1092/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001093/// [C++] 'if' '(' condition ')' statement
1094/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +00001095///
Richard Smithc202b282012-04-14 00:33:13 +00001096StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001097 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001098 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +00001099
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001100 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001101 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +00001102 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +00001103 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +00001104 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001105
David Blaikiebbafb8a2012-03-11 07:00:24 +00001106 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001107
Chris Lattner2dd1b722007-08-26 23:08:06 +00001108 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1109 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001110 //
1111 // C++ 6.4p3:
1112 // A name introduced by a declaration in a condition is in scope from its
1113 // point of declaration until the end of the substatements controlled by the
1114 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001115 // C++ 3.3.2p4:
1116 // Names declared in the for-init-statement, and in the condition of if,
1117 // while, for, and switch statements are local to the if, while, for, or
1118 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001119 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001120 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001121
Chris Lattnerc951dae2006-08-10 04:23:57 +00001122 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001123 ExprResult CondExp;
Craig Topper161e4db2014-05-21 06:02:52 +00001124 Decl *CondVar = nullptr;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001125 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001126 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001127
David Blaikiea5696df2012-05-16 04:20:04 +00001128 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001129
Chris Lattner8fb26252007-08-22 05:28:50 +00001130 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001131 // there is no compound stmt. C90 does not have this clause. We only do this
1132 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001133 //
1134 // C++ 6.4p1:
1135 // The substatement in a selection-statement (each substatement, in the else
1136 // form of the if statement) implicitly defines a local scope.
1137 //
1138 // For C++ we create a scope for the condition and a new scope for
1139 // substatements because:
1140 // -When the 'then' scope exits, we want the condition declaration to still be
1141 // active for the 'else' scope too.
1142 // -Sema will detect name clashes by considering declarations of a
1143 // 'ControlScope' as part of its direct subscope.
1144 // -If we wanted the condition and substatement to be in the same scope, we
1145 // would have to notify ParseStatement not to create a new scope. It's
1146 // simpler to let it create a new scope.
1147 //
David Majnemer2206bf52014-03-05 08:57:59 +00001148 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001149
Chris Lattner5c5808a2007-10-29 05:08:52 +00001150 // Read the 'then' stmt.
1151 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001152
1153 SourceLocation InnerStatementTrailingElseLoc;
1154 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001155
Chris Lattner37e54f42007-08-22 05:16:28 +00001156 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001157 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001158
Chris Lattnerc951dae2006-08-10 04:23:57 +00001159 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001160 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001161 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001162 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001163
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001164 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001165 if (TrailingElseLoc)
1166 *TrailingElseLoc = Tok.getLocation();
1167
Chris Lattneraf635312006-10-16 06:06:51 +00001168 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001169 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001170
Chris Lattner8fb26252007-08-22 05:28:50 +00001171 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001172 // there is no compound stmt. C90 does not have this clause. We only do
1173 // this if the body isn't a compound statement to avoid push/pop in common
1174 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001175 //
1176 // C++ 6.4p1:
1177 // The substatement in a selection-statement (each substatement, in the else
1178 // form of the if statement) implicitly defines a local scope.
1179 //
David Majnemer2206bf52014-03-05 08:57:59 +00001180 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001181
Chris Lattner30f910e2006-10-16 05:52:41 +00001182 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001183
Chris Lattner37e54f42007-08-22 05:16:28 +00001184 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001185 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001186 } else if (Tok.is(tok::code_completion)) {
1187 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001188 cutOffParsing();
1189 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001190 } else if (InnerStatementTrailingElseLoc.isValid()) {
1191 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001192 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001193
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001194 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001195
Chris Lattner5c5808a2007-10-29 05:08:52 +00001196 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001197 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001198 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001199 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
Craig Topper161e4db2014-05-21 06:02:52 +00001200 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1201 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001202 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001203 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001204 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001205
Chris Lattner5c5808a2007-10-29 05:08:52 +00001206 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001207 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001208 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001209 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001210 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001211
John McCallb268a282010-08-23 23:25:46 +00001212 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001213 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001214}
1215
Chris Lattner9075bd72006-08-10 04:59:57 +00001216/// ParseSwitchStatement
1217/// switch-statement:
1218/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001219/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001220StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001221 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001222 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001223
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001224 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001225 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001226 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001227 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001228 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001229
David Blaikiebbafb8a2012-03-11 07:00:24 +00001230 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001231
Chris Lattner2dd1b722007-08-26 23:08:06 +00001232 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1233 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001234 //
1235 // C++ 6.4p3:
1236 // A name introduced by a declaration in a condition is in scope from its
1237 // point of declaration until the end of the substatements controlled by the
1238 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001239 // C++ 3.3.2p4:
1240 // Names declared in the for-init-statement, and in the condition of if,
1241 // while, for, and switch statements are local to the if, while, for, or
1242 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001243 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001244 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001245 if (C99orCXX)
1246 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001247 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001248
Chris Lattner9075bd72006-08-10 04:59:57 +00001249 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001250 ExprResult Cond;
Craig Topper161e4db2014-05-21 06:02:52 +00001251 Decl *CondVar = nullptr;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001252 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001253 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001254
John McCalldadc5752010-08-24 06:29:42 +00001255 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001256 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001257
Douglas Gregore60e41a2010-05-06 17:25:47 +00001258 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001259 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001260 // FIXME: This is not optimal recovery, but parsing the body is more
1261 // dangerous due to the presence of case and default statements, which
1262 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001263 if (Tok.is(tok::l_brace)) {
1264 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001265 SkipUntil(tok::r_brace);
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001266 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001267 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001268 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001269 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001270
Chris Lattner8fb26252007-08-22 05:28:50 +00001271 // C99 6.8.4p3 - In C99, the body of the switch 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 this
1273 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001274 //
1275 // C++ 6.4p1:
1276 // The substatement in a selection-statement (each substatement, in the else
1277 // form of the if statement) implicitly defines a local scope.
1278 //
1279 // See comments in ParseIfStatement for why we create a scope for the
1280 // condition and a new scope for substatement in C++.
1281 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001282 getCurScope()->AddFlags(Scope::BreakScope);
David Majnemer2206bf52014-03-05 08:57:59 +00001283 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001284
Hans Wennborg852c3462014-06-17 00:09:05 +00001285 // We have incremented the mangling number for the SwitchScope and the
1286 // InnerScope, which is one too many.
1287 if (C99orCXX)
David Majnemera7f8c462015-03-19 21:54:30 +00001288 getCurScope()->decrementMSManglingNumber();
Hans Wennborg852c3462014-06-17 00:09:05 +00001289
Chris Lattner9075bd72006-08-10 04:59:57 +00001290 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001291 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001292
Chris Lattner8fd2d012010-01-24 01:50:29 +00001293 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001294 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001295 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001296
John McCallb268a282010-08-23 23:25:46 +00001297 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001298}
1299
1300/// ParseWhileStatement
1301/// while-statement: [C99 6.8.5.1]
1302/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001303/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001304StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001305 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001306 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001307 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001308
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001309 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001310 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001311 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001312 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001313 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001314
David Blaikiebbafb8a2012-03-11 07:00:24 +00001315 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001316
Chris Lattner2dd1b722007-08-26 23:08:06 +00001317 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1318 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001319 //
1320 // C++ 6.4p3:
1321 // A name introduced by a declaration in a condition is in scope from its
1322 // point of declaration until the end of the substatements controlled by the
1323 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001324 // C++ 3.3.2p4:
1325 // Names declared in the for-init-statement, and in the condition of if,
1326 // while, for, and switch statements are local to the if, while, for, or
1327 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001328 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001329 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001330 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001331 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1332 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001333 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001334 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1335 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001336
Chris Lattner9075bd72006-08-10 04:59:57 +00001337 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001338 ExprResult Cond;
Craig Topper161e4db2014-05-21 06:02:52 +00001339 Decl *CondVar = nullptr;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001340 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001341 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001342
David Blaikiea5696df2012-05-16 04:20:04 +00001343 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001344
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001345 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001346 // there is no compound stmt. C90 does not have this clause. We only do this
1347 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001348 //
1349 // C++ 6.5p2:
1350 // The substatement in an iteration-statement implicitly defines a local scope
1351 // which is entered and exited each time through the loop.
1352 //
1353 // See comments in ParseIfStatement for why we create a scope for the
1354 // condition and a new scope for substatement in C++.
1355 //
David Majnemer2206bf52014-03-05 08:57:59 +00001356 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001357
Chris Lattner9075bd72006-08-10 04:59:57 +00001358 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001359 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001360
Chris Lattner8fb26252007-08-22 05:28:50 +00001361 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001362 InnerScope.Exit();
1363 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001364
John McCall48871652010-08-21 09:40:31 +00001365 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001366 return StmtError();
1367
John McCallb268a282010-08-23 23:25:46 +00001368 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001369}
1370
1371/// ParseDoStatement
1372/// do-statement: [C99 6.8.5.2]
1373/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001374/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001375StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001376 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001377 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001378
Chris Lattner2dd1b722007-08-26 23:08:06 +00001379 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1380 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001381 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001382 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001383 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001384 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001385 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001386
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001387 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001388
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001389 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001390 // there is no compound stmt. C90 does not have this clause. We only do this
1391 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001392 //
1393 // C++ 6.5p2:
1394 // The substatement in an iteration-statement implicitly defines a local scope
1395 // which is entered and exited each time through the loop.
1396 //
David Majnemer2206bf52014-03-05 08:57:59 +00001397 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1398 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001399
Chris Lattner9075bd72006-08-10 04:59:57 +00001400 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001401 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001402
Chris Lattner8fb26252007-08-22 05:28:50 +00001403 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001404 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001405
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001406 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001407 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001408 Diag(Tok, diag::err_expected_while);
Alp Tokerec543272013-12-24 09:48:30 +00001409 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001410 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner0046de12008-11-13 18:52:53 +00001411 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001412 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001413 }
Chris Lattneraf635312006-10-16 06:06:51 +00001414 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001415
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001416 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001417 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001418 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001419 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001420 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001421
Richard Smithc2c8bb82013-10-15 01:34:54 +00001422 // Parse the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001423 BalancedDelimiterTracker T(*this, tok::l_paren);
1424 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001425
Richard Smithc2c8bb82013-10-15 01:34:54 +00001426 // A do-while expression is not a condition, so can't have attributes.
1427 DiagnoseAndSkipCXX11Attributes();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001428
John McCalldadc5752010-08-24 06:29:42 +00001429 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001430 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001431 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001432
Sebastian Redlb62406f2008-12-11 19:48:14 +00001433 if (Cond.isInvalid() || Body.isInvalid())
1434 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001435
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001436 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1437 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001438}
1439
Richard Smith955bf012014-06-19 11:42:00 +00001440bool Parser::isForRangeIdentifier() {
1441 assert(Tok.is(tok::identifier));
1442
1443 const Token &Next = NextToken();
1444 if (Next.is(tok::colon))
1445 return true;
1446
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001447 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
Richard Smith955bf012014-06-19 11:42:00 +00001448 TentativeParsingAction PA(*this);
1449 ConsumeToken();
1450 SkipCXX11Attributes();
1451 bool Result = Tok.is(tok::colon);
1452 PA.Revert();
1453 return Result;
1454 }
1455
1456 return false;
1457}
1458
Chris Lattner9075bd72006-08-10 04:59:57 +00001459/// ParseForStatement
1460/// for-statement: [C99 6.8.5.3]
1461/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1462/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001463/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1464/// [C++] statement
Richard Smith0e304ea2015-10-22 04:46:14 +00001465/// [C++0x] 'for'
1466/// 'co_await'[opt] [Coroutines]
1467/// '(' for-range-declaration ':' for-range-initializer ')'
1468/// statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001469/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1470/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001471///
1472/// [C++] for-init-statement:
1473/// [C++] expression-statement
1474/// [C++] simple-declaration
1475///
Richard Smith02e85f32011-04-14 22:09:26 +00001476/// [C++0x] for-range-declaration:
1477/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1478/// [C++0x] for-range-initializer:
1479/// [C++0x] expression
1480/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001481StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001482 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001483 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001484
Richard Smith0e304ea2015-10-22 04:46:14 +00001485 SourceLocation CoawaitLoc;
1486 if (Tok.is(tok::kw_co_await))
1487 CoawaitLoc = ConsumeToken();
1488
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001489 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001490 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001491 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001492 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001493 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001494
Chad Rosier67055f52012-07-10 21:35:27 +00001495 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1496 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001497
Chris Lattner2dd1b722007-08-26 23:08:06 +00001498 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1499 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001500 //
1501 // C++ 6.4p3:
1502 // A name introduced by a declaration in a condition is in scope from its
1503 // point of declaration until the end of the substatements controlled by the
1504 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001505 // C++ 3.3.2p4:
1506 // Names declared in the for-init-statement, and in the condition of if,
1507 // while, for, and switch statements are local to the if, while, for, or
1508 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001509 // C++ 6.5.3p1:
1510 // Names declared in the for-init-statement are in the same declarative-region
1511 // as those declared in the condition.
1512 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001513 unsigned ScopeFlags = 0;
Chris Lattner934074c2009-04-22 00:54:41 +00001514 if (C99orCXXorObjC)
Serge Pavlov09f99242014-01-23 15:05:00 +00001515 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001516
1517 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001518
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001519 BalancedDelimiterTracker T(*this, tok::l_paren);
1520 T.consumeOpen();
1521
John McCalldadc5752010-08-24 06:29:42 +00001522 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001523
Richard Smith02e85f32011-04-14 22:09:26 +00001524 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001525 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001526 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001527 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001528 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001529 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001530 FullExprArg ThirdPart(Actions);
Craig Topper161e4db2014-05-21 06:02:52 +00001531 Decl *SecondVar = nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001532
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001533 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001534 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001535 C99orCXXorObjC? Sema::PCC_ForInit
1536 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001537 cutOffParsing();
1538 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001539 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001540
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001541 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001542 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001543
Chris Lattner9075bd72006-08-10 04:59:57 +00001544 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001545 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001546 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001547 // no first part, eat the ';'.
1548 ConsumeToken();
Richard Smith955bf012014-06-19 11:42:00 +00001549 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1550 isForRangeIdentifier()) {
1551 ProhibitAttributes(attrs);
1552 IdentifierInfo *Name = Tok.getIdentifierInfo();
1553 SourceLocation Loc = ConsumeToken();
1554 MaybeParseCXX11Attributes(attrs);
1555
1556 ForRangeInit.ColonLoc = ConsumeToken();
1557 if (Tok.is(tok::l_brace))
1558 ForRangeInit.RangeExpr = ParseBraceInitializer();
1559 else
1560 ForRangeInit.RangeExpr = ParseExpression();
1561
Richard Smith83d3f152014-11-27 01:54:27 +00001562 Diag(Loc, diag::err_for_range_identifier)
Richard Smith955bf012014-06-19 11:42:00 +00001563 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1564 ? FixItHint::CreateInsertion(Loc, "auto &&")
1565 : FixItHint());
1566
1567 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1568 attrs, attrs.Range.getEnd());
1569 ForRange = true;
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001570 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001571 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001572 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001573 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001574
Richard Smith02e85f32011-04-14 22:09:26 +00001575 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001576 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001577 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1578
Chris Lattner49836b42009-04-02 04:16:50 +00001579 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00001580 DeclGroupPtrTy DG = ParseSimpleDeclaration(
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001581 Declarator::ForContext, DeclEnd, attrs, false,
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00001582 MightBeForRangeStmt ? &ForRangeInit : nullptr);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001583 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Richard Smith02e85f32011-04-14 22:09:26 +00001584 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001585 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001586 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001587
Richard Smith02e85f32011-04-14 22:09:26 +00001588 ForRange = true;
1589 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001590 ConsumeToken();
1591 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001592 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001593 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001594 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001595
Douglas Gregor68762e72010-08-23 21:17:50 +00001596 if (Tok.is(tok::code_completion)) {
1597 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001598 cutOffParsing();
1599 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001600 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001601 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001602 } else {
1603 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001604 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001605 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001606 ProhibitAttributes(attrs);
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001607 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Chris Lattner71e23ce2006-11-04 20:18:38 +00001608
John McCall34376a62010-12-04 03:47:34 +00001609 ForEach = isTokIdentifier_in();
1610
Chris Lattnercd68f642007-06-27 01:06:29 +00001611 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001612 if (!Value.isInvalid()) {
1613 if (ForEach)
1614 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1615 else
Richard Smith945f8d32013-01-14 22:39:08 +00001616 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001617 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001618
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001619 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001620 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001621 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001622 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001623
Douglas Gregor68762e72010-08-23 21:17:50 +00001624 if (Tok.is(tok::code_completion)) {
1625 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001626 cutOffParsing();
1627 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001628 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001629 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001630 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001631 // User tried to write the reasonable, but ill-formed, for-range-statement
1632 // for (expr : expr) { ... }
1633 Diag(Tok, diag::err_for_range_expected_decl)
1634 << FirstPart.get()->getSourceRange();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001635 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smith4f848f12011-12-20 22:56:20 +00001636 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001637 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001638 if (!Value.isInvalid()) {
1639 Diag(Tok, diag::err_expected_semi_for);
1640 } else {
1641 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001642 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001643 if (Tok.is(tok::semi))
1644 ConsumeToken();
1645 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001646 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001647 }
Serge Pavlov09f99242014-01-23 15:05:00 +00001648
1649 // Parse the second part of the for specifier.
1650 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smith02e85f32011-04-14 22:09:26 +00001651 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001652 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001653 // Parse the second part of the for specifier.
1654 if (Tok.is(tok::semi)) { // for (...;;
1655 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001656 } else if (Tok.is(tok::r_paren)) {
1657 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001658 } else {
John McCalldadc5752010-08-24 06:29:42 +00001659 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001660 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001661 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1662 else {
1663 Second = ParseExpression();
1664 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001665 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001666 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001667 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001668 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001669 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001670 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001671
Douglas Gregor230a7e62011-02-17 03:38:46 +00001672 if (Tok.isNot(tok::semi)) {
1673 if (!SecondPartIsInvalid || SecondVar)
1674 Diag(Tok, diag::err_expected_semi_for);
1675 else
1676 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001677 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001678 }
1679
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001680 if (Tok.is(tok::semi)) {
1681 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001682 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001683
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001684 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001685 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001686 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001687 // FIXME: The C++11 standard doesn't actually say that this is a
1688 // discarded-value expression, but it clearly should be.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001689 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001690 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001691 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001692 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001693 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001694
Richard Smith0e304ea2015-10-22 04:46:14 +00001695 // C++ Coroutines [stmt.iter]:
1696 // 'co_await' can only be used for a range-based for statement.
1697 if (CoawaitLoc.isValid() && !ForRange) {
1698 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1699 CoawaitLoc = SourceLocation();
1700 }
1701
Richard Smith02e85f32011-04-14 22:09:26 +00001702 // We need to perform most of the semantic analysis for a C++0x for-range
1703 // statememt before parsing the body, in order to be able to deduce the type
1704 // of an auto-typed loop variable.
1705 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001706 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001707
John McCall53848232011-07-27 01:07:15 +00001708 if (ForRange) {
Richard Smith9f690bd2015-10-27 06:02:45 +00001709 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1710 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1711 ForRangeInit.ColonLoc, ForRangeInit.RangeExpr.get(),
1712 T.getCloseLocation(), Sema::BFRK_Build);
John McCall53848232011-07-27 01:07:15 +00001713
1714 // Similarly, we need to do the semantic analysis for a for-range
1715 // statement immediately in order to close over temporaries correctly.
1716 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001717 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001718 FirstPart.get(),
1719 Collection.get(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001720 T.getCloseLocation());
Alexey Bataev9c821032015-04-30 04:23:23 +00001721 } else {
1722 // In OpenMP loop region loop control variable must be captured and be
1723 // private. Perform analysis of first part (if any).
1724 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1725 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1726 }
John McCall53848232011-07-27 01:07:15 +00001727 }
1728
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001729 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001730 // there is no compound stmt. C90 does not have this clause. We only do this
1731 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001732 //
1733 // C++ 6.5p2:
1734 // The substatement in an iteration-statement implicitly defines a local scope
1735 // which is entered and exited each time through the loop.
1736 //
1737 // See comments in ParseIfStatement for why we create a scope for
1738 // for-init-statement/condition and a new scope for substatement in C++.
1739 //
David Majnemer2206bf52014-03-05 08:57:59 +00001740 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1741 Tok.is(tok::l_brace));
1742
1743 // The body of the for loop has the same local mangling number as the
1744 // for-init-statement.
1745 // It will only be incremented if the body contains other things that would
1746 // normally increment the mangling number (like a compound statement).
1747 if (C99orCXXorObjC)
David Majnemera7f8c462015-03-19 21:54:30 +00001748 getCurScope()->decrementMSManglingNumber();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001749
Chris Lattner9075bd72006-08-10 04:59:57 +00001750 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001751 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001752
Chris Lattner8fb26252007-08-22 05:28:50 +00001753 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001754 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001755
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001756 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001757 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001758
1759 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001760 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001761
Richard Smith02e85f32011-04-14 22:09:26 +00001762 if (ForEach)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001763 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1764 Body.get());
Mike Stump11289f42009-09-09 15:08:12 +00001765
Richard Smith02e85f32011-04-14 22:09:26 +00001766 if (ForRange)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001767 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001768
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001769 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001770 SecondPart, SecondVar, ThirdPart,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001771 T.getCloseLocation(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001772}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001773
Chris Lattner503fadc2006-08-10 05:45:44 +00001774/// ParseGotoStatement
1775/// jump-statement:
1776/// 'goto' identifier ';'
1777/// [GNU] 'goto' '*' expression ';'
1778///
1779/// Note: this lets the caller parse the end ';'.
1780///
Richard Smithc202b282012-04-14 00:33:13 +00001781StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001782 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001783 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001784
John McCalldadc5752010-08-24 06:29:42 +00001785 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001786 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001787 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1788 Tok.getLocation());
1789 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001790 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001791 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001792 // GNU indirect goto extension.
1793 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001794 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001795 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001796 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001797 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001798 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001799 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001800 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001801 } else {
Alp Tokerec543272013-12-24 09:48:30 +00001802 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001803 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001804 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001805
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001806 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001807}
1808
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001809/// ParseContinueStatement
1810/// jump-statement:
1811/// 'continue' ';'
1812///
1813/// Note: this lets the caller parse the end ';'.
1814///
Richard Smithc202b282012-04-14 00:33:13 +00001815StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001816 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001817 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001818}
1819
1820/// ParseBreakStatement
1821/// jump-statement:
1822/// 'break' ';'
1823///
1824/// Note: this lets the caller parse the end ';'.
1825///
Richard Smithc202b282012-04-14 00:33:13 +00001826StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001827 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001828 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001829}
1830
Chris Lattner503fadc2006-08-10 05:45:44 +00001831/// ParseReturnStatement
1832/// jump-statement:
1833/// 'return' expression[opt] ';'
Richard Smith0e304ea2015-10-22 04:46:14 +00001834/// 'return' braced-init-list ';'
1835/// 'co_return' expression[opt] ';'
1836/// 'co_return' braced-init-list ';'
Richard Smithc202b282012-04-14 00:33:13 +00001837StmtResult Parser::ParseReturnStatement() {
Richard Smith0e304ea2015-10-22 04:46:14 +00001838 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1839 "Not a return stmt!");
1840 bool IsCoreturn = Tok.is(tok::kw_co_return);
Chris Lattneraf635312006-10-16 06:06:51 +00001841 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001842
John McCalldadc5752010-08-24 06:29:42 +00001843 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001844 if (Tok.isNot(tok::semi)) {
Richard Smith0e304ea2015-10-22 04:46:14 +00001845 // FIXME: Code completion for co_return.
1846 if (Tok.is(tok::code_completion) && !IsCoreturn) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001847 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001848 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001849 return StmtError();
1850 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001851
David Blaikiebbafb8a2012-03-11 07:00:24 +00001852 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001853 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001854 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001855 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001856 diag::warn_cxx98_compat_generalized_initializer_lists :
1857 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001858 << R.get()->getSourceRange();
1859 } else
Nico Weber3ce01c32015-01-04 08:07:54 +00001860 R = ParseExpression();
Serge Pavlovf79bd5c2013-12-04 03:51:59 +00001861 if (R.isInvalid()) {
1862 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001863 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001864 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001865 }
Richard Smithcfd53b42015-10-22 06:13:50 +00001866 if (IsCoreturn)
1867 return Actions.ActOnCoreturnStmt(ReturnLoc, R.get());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001868 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
Chris Lattner503fadc2006-08-10 05:45:44 +00001869}
Chris Lattner0116c472006-08-15 06:03:28 +00001870
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001871StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts, bool OnlyStatement,
1872 SourceLocation *TrailingElseLoc,
1873 ParsedAttributesWithRange &Attrs) {
1874 // Create temporary attribute list.
1875 ParsedAttributesWithRange TempAttrs(AttrFactory);
1876
Mark Heffernanbd26f5e2014-07-21 18:08:34 +00001877 // Get loop hints and consume annotated token.
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001878 while (Tok.is(tok::annot_pragma_loop_hint)) {
Tyler Nowicki0c9b34b2014-07-31 20:15:14 +00001879 LoopHint Hint;
1880 if (!HandlePragmaLoopHint(Hint))
1881 continue;
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001882
Tyler Nowicki0c9b34b2014-07-31 20:15:14 +00001883 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001884 ArgsUnion(Hint.ValueExpr)};
Mark Heffernanbd26f5e2014-07-21 18:08:34 +00001885 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1886 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1887 AttributeList::AS_Pragma);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001888 }
1889
1890 // Get the next statement.
1891 MaybeParseCXX11Attributes(Attrs);
1892
1893 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1894 Stmts, OnlyStatement, TrailingElseLoc, Attrs);
1895
1896 Attrs.takeAllFrom(TempAttrs);
1897 return S;
1898}
1899
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001900Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00001901 assert(Tok.is(tok::l_brace));
1902 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001903
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00001904 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00001905 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00001906 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00001907 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001908 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001909
John McCallfaf5fb42010-08-26 23:41:50 +00001910 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1911 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00001912
Alexey Bataev3d42f342015-11-20 07:02:57 +00001913 // Save and reset current vtordisp stack if we have entered a C++ method body.
1914 bool IsCXXMethod =
1915 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1916 Sema::VtorDispStackRAII SavedVtorDispStack(Actions, IsCXXMethod);
1917
Fariborz Jahanian8e632942007-11-08 19:01:26 +00001918 // Do not enter a scope for the brace, as the arguments are in the same scope
1919 // (the function body) as the body itself. Instead, just read the statement
1920 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00001921 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00001922
Fariborz Jahanian8e632942007-11-08 19:01:26 +00001923 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001924 if (FnBody.isInvalid()) {
1925 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00001926 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001927 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001928
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001929 BodyScope.Exit();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001930 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00001931}
Sebastian Redlb219c902008-12-21 16:41:36 +00001932
Sebastian Redla7b98a72009-04-26 20:35:05 +00001933/// ParseFunctionTryBlock - Parse a C++ function-try-block.
1934///
1935/// function-try-block:
1936/// 'try' ctor-initializer[opt] compound-statement handler-seq
1937///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001938Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00001939 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1940 SourceLocation TryLoc = ConsumeToken();
1941
John McCallfaf5fb42010-08-26 23:41:50 +00001942 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1943 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00001944
1945 // Constructor initializer list?
1946 if (Tok.is(tok::colon))
1947 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00001948 else
1949 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001950
Richard Smith1ab34b32012-11-19 21:13:18 +00001951 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
1952 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00001953 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00001954 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001955 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001956
Alexey Bataev3d42f342015-11-20 07:02:57 +00001957 // Save and reset current vtordisp stack if we have entered a C++ method body.
1958 bool IsCXXMethod =
1959 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1960 Sema::VtorDispStackRAII SavedVtorDispStack(Actions, IsCXXMethod);
1961
Sebastian Redld98ecd62009-04-26 21:08:36 +00001962 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00001963 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00001964 // If we failed to parse the try-catch, we just give the function an empty
1965 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001966 if (FnBody.isInvalid()) {
1967 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00001968 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001969 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00001970
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001971 BodyScope.Exit();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001972 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Sebastian Redla7b98a72009-04-26 20:35:05 +00001973}
1974
Erik Verbruggen6e922512012-04-12 10:11:59 +00001975bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001976 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00001977 assert(SkipFunctionBodies &&
1978 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001979
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00001980 if (!PP.isCodeCompletionEnabled()) {
1981 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001982 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00001983 return true;
1984 }
1985
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001986 // We're in code-completion mode. Skip parsing for all function bodies unless
1987 // the body contains the code-completion point.
1988 TentativeParsingAction PA(*this);
1989 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001990 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001991 PA.Commit();
1992 return true;
1993 }
1994
1995 PA.Revert();
1996 return false;
1997}
1998
Sebastian Redlb219c902008-12-21 16:41:36 +00001999/// ParseCXXTryBlock - Parse a C++ try-block.
2000///
2001/// try-block:
2002/// 'try' compound-statement handler-seq
2003///
Richard Smithc202b282012-04-14 00:33:13 +00002004StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002005 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2006
2007 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002008 return ParseCXXTryBlockCommon(TryLoc);
2009}
2010
2011/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2012/// function-try-block.
2013///
2014/// try-block:
2015/// 'try' compound-statement handler-seq
2016///
2017/// function-try-block:
2018/// 'try' ctor-initializer[opt] compound-statement handler-seq
2019///
2020/// handler-seq:
2021/// handler handler-seq[opt]
2022///
John Wiegley1c0675e2011-04-28 01:08:34 +00002023/// [Borland] try-block:
2024/// 'try' compound-statement seh-except-block
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002025/// 'try' compound-statement seh-finally-block
John Wiegley1c0675e2011-04-28 01:08:34 +00002026///
David Blaikie1c9c9042012-11-10 01:04:23 +00002027StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002028 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002029 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Richard Smithc202b282012-04-14 00:33:13 +00002030
Warren Huntf6be4cb2014-07-25 20:52:51 +00002031 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2032 Scope::DeclScope | Scope::TryScope |
2033 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002034 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002035 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002036
John Wiegley1c0675e2011-04-28 01:08:34 +00002037 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002038
Richard Smithc202b282012-04-14 00:33:13 +00002039 if ((Tok.is(tok::identifier) &&
2040 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2041 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002042 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2043 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002044 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002045 SourceLocation Loc = ConsumeToken();
2046 Handler = ParseSEHExceptBlock(Loc);
2047 }
2048 else {
2049 SourceLocation Loc = ConsumeToken();
2050 Handler = ParseSEHFinallyBlock(Loc);
2051 }
2052 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002053 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002054
John Wiegley1c0675e2011-04-28 01:08:34 +00002055 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2056 TryLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002057 TryBlock.get(),
Warren Huntf6be4cb2014-07-25 20:52:51 +00002058 Handler.get());
Sebastian Redlb219c902008-12-21 16:41:36 +00002059 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002060 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002061 StmtVector Handlers;
Richard Smithc2c8bb82013-10-15 01:34:54 +00002062
2063 // C++11 attributes can't appear here, despite this context seeming
2064 // statement-like.
2065 DiagnoseAndSkipCXX11Attributes();
Sebastian Redlb219c902008-12-21 16:41:36 +00002066
John Wiegley1c0675e2011-04-28 01:08:34 +00002067 if (Tok.isNot(tok::kw_catch))
2068 return StmtError(Diag(Tok, diag::err_expected_catch));
2069 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002070 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002071 if (!Handler.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002072 Handlers.push_back(Handler.get());
John Wiegley1c0675e2011-04-28 01:08:34 +00002073 }
2074 // Don't bother creating the full statement if we don't have any usable
2075 // handlers.
2076 if (Handlers.empty())
2077 return StmtError();
2078
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002079 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002080 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002081}
2082
2083/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2084///
Richard Smith1dba27c2013-01-29 09:02:09 +00002085/// handler:
2086/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002087///
Richard Smith1dba27c2013-01-29 09:02:09 +00002088/// exception-declaration:
2089/// attribute-specifier-seq[opt] type-specifier-seq declarator
2090/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2091/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002092///
David Blaikie1c9c9042012-11-10 01:04:23 +00002093StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002094 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2095
2096 SourceLocation CatchLoc = ConsumeToken();
2097
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002098 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002099 if (T.expectAndConsume())
Sebastian Redlb219c902008-12-21 16:41:36 +00002100 return StmtError();
2101
2102 // C++ 3.3.2p3:
2103 // The name in a catch exception-declaration is local to the handler and
2104 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002105 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002106 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002107
2108 // exception-declaration is equivalent to '...' or a parameter-declaration
2109 // without default arguments.
Craig Topper161e4db2014-05-21 06:02:52 +00002110 Decl *ExceptionDecl = nullptr;
Sebastian Redlb219c902008-12-21 16:41:36 +00002111 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002112 ParsedAttributesWithRange Attributes(AttrFactory);
2113 MaybeParseCXX11Attributes(Attributes);
2114
John McCall084e83d2011-03-24 11:26:52 +00002115 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002116 DS.takeAttributesFrom(Attributes);
2117
Sebastian Redl54c04d42008-12-22 19:15:10 +00002118 if (ParseCXXTypeSpecifierSeq(DS))
2119 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002120
Sebastian Redlb219c902008-12-21 16:41:36 +00002121 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2122 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002123 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002124 } else
2125 ConsumeToken();
2126
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002127 T.consumeClose();
2128 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002129 return StmtError();
2130
2131 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002132 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redlb219c902008-12-21 16:41:36 +00002133
Alexis Hunt96d5c762009-11-21 08:43:09 +00002134 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002135 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002136 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002137 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002138
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002139 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
Sebastian Redlb219c902008-12-21 16:41:36 +00002140}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002141
2142void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002143 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002144 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002145 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002146
Douglas Gregor43edb322011-10-24 22:31:10 +00002147 // Handle dependent statements by parsing the braces as a compound statement.
2148 // This is not the same behavior as Visual C++, which don't treat this as a
2149 // compound statement, but for Clang's type checking we can't have anything
2150 // inside these braces escaping to the surrounding code.
2151 if (Result.Behavior == IEB_Dependent) {
2152 if (!Tok.is(tok::l_brace)) {
Alp Tokerec543272013-12-24 09:48:30 +00002153 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smithc202b282012-04-14 00:33:13 +00002154 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002155 }
Richard Smithc202b282012-04-14 00:33:13 +00002156
2157 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002158 if (Compound.isInvalid())
2159 return;
Richard Smithc202b282012-04-14 00:33:13 +00002160
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002161 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2162 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002163 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002164 Result.Name,
2165 Compound.get());
2166 if (DepResult.isUsable())
2167 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002168 return;
2169 }
Richard Smithc202b282012-04-14 00:33:13 +00002170
Douglas Gregor43edb322011-10-24 22:31:10 +00002171 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2172 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00002173 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002174 return;
2175 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002176
Douglas Gregor43edb322011-10-24 22:31:10 +00002177 switch (Result.Behavior) {
2178 case IEB_Parse:
2179 // Parse the statements below.
2180 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002181
Douglas Gregor43edb322011-10-24 22:31:10 +00002182 case IEB_Dependent:
2183 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002184
Douglas Gregor43edb322011-10-24 22:31:10 +00002185 case IEB_Skip:
2186 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002187 return;
2188 }
2189
2190 // Condition is true, parse the statements.
2191 while (Tok.isNot(tok::r_brace)) {
2192 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2193 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002194 Stmts.push_back(R.get());
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002195 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002196 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002197}