blob: e77f07ab030cd1e8d9880b13056025aab0af62ab [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerd167ca02009-12-10 00:21:05 +000016#include "RAIIObjectsForParser.h"
John McCallaeeacf72013-05-03 00:10:13 +000017#include "clang/AST/ASTContext.h"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070018#include "clang/Basic/Attributes.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/PrettyStackTrace.h"
John McCall19510852010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070022#include "clang/Sema/LoopHint.h"
John McCallf312b1e2010-08-26 23:41:50 +000023#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall19510852010-08-20 18:27:03 +000024#include "clang/Sema/Scope.h"
Richard Smith05766812012-08-18 00:55:03 +000025#include "clang/Sema/TypoCorrection.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070026#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// C99 6.8: Statements and Blocks.
31//===----------------------------------------------------------------------===//
32
Richard Smith961d0572013-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kyrtzidisdcdd55f2008-09-07 18:58:01 +000060/// [C++] declaration-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +000061/// [C++] try-block
John Wiegley28bbe4b2011-04-28 01:08:34 +000062/// [MS] seh-try-block
Fariborz Jahanianb384d322007-10-04 20:19:06 +000063/// [OBC] objc-throw-statement
64/// [OBC] objc-try-catch-statement
Fariborz Jahanianc385c902008-01-29 18:21:32 +000065/// [OBC] objc-synchronized-statement
Reid Spencer5f016e22007-07-11 17:01:13 +000066/// [GNU] asm-statement
67/// [OMP] openmp-construct [TODO]
68///
69/// labeled-statement:
70/// identifier ':' statement
71/// 'case' constant-expression ':' statement
72/// 'default' ':' statement
73///
74/// selection-statement:
75/// if-statement
76/// switch-statement
77///
78/// iteration-statement:
79/// while-statement
80/// do-statement
81/// for-statement
82///
83/// expression-statement:
84/// expression[opt] ';'
85///
86/// jump-statement:
87/// 'goto' identifier ';'
88/// 'continue' ';'
89/// 'break' ';'
90/// 'return' expression[opt] ';'
91/// [GNU] 'goto' '*' expression ';'
92///
Fariborz Jahanianb384d322007-10-04 20:19:06 +000093/// [OBC] objc-throw-statement:
94/// [OBC] '@' 'throw' expression ';'
Mike Stump1eb44332009-09-09 15:08:12 +000095/// [OBC] '@' 'throw' ';'
96///
John McCall60d7b3a2010-08-24 06:29:42 +000097StmtResult
Nico Weber5cb94a72011-12-22 23:26:17 +000098Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
99 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000100
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +0000101 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000102
Richard Smith534986f2012-04-14 00:33:13 +0000103 ParsedAttributesWithRange Attrs(AttrFactory);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700104 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
Richard Smith534986f2012-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 Uhrain6243f622013-09-27 19:40:12 +0000118namespace {
119class StatementFilterCCC : public CorrectionCandidateCallback {
120public:
121 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
122 WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) ||
123 nextTok.is(tok::identifier) || nextTok.is(tok::star) ||
124 nextTok.is(tok::amp) || nextTok.is(tok::l_square);
125 WantExpressionKeywords = nextTok.is(tok::l_paren) ||
126 nextTok.is(tok::identifier) ||
127 nextTok.is(tok::arrow) || nextTok.is(tok::period);
128 WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) ||
129 nextTok.is(tok::identifier) ||
130 nextTok.is(tok::l_brace);
131 WantCXXNamedCasts = false;
132 }
133
Stephen Hines651f13c2014-04-23 16:59:28 -0700134 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain6243f622013-09-27 19:40:12 +0000135 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
Kaelyn Uhraina89ee572013-10-01 22:00:28 +0000136 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain0f90ee02013-09-27 19:40:16 +0000137 if (NextToken.is(tok::equal))
138 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain2ceb67a2013-09-27 23:54:23 +0000139 if (NextToken.is(tok::period) &&
140 candidate.getCorrectionDeclAs<NamespaceDecl>())
141 return false;
Kaelyn Uhrain6243f622013-09-27 19:40:12 +0000142 return CorrectionCandidateCallback::ValidateCandidate(candidate);
143 }
144
145private:
146 Token NextToken;
147};
148}
149
Richard Smith534986f2012-04-14 00:33:13 +0000150StmtResult
151Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
152 bool OnlyStatement, SourceLocation *TrailingElseLoc,
153 ParsedAttributesWithRange &Attrs) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700154 const char *SemiError = nullptr;
Richard Smith534986f2012-04-14 00:33:13 +0000155 StmtResult Res;
Sean Huntbbd37c62009-11-21 08:43:09 +0000156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 // Cases in this switch statement should fall through if the parser expects
158 // the token to end in a semicolon (in which case SemiError should be set),
159 // or they directly 'return;' if not.
Douglas Gregor312eadb2011-04-24 05:37:28 +0000160Retry:
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000161 tok::TokenKind Kind = Tok.getKind();
162 SourceLocation AtLoc;
163 switch (Kind) {
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000164 case tok::at: // May be a @try or @throw statement
165 {
Richard Smith534986f2012-04-14 00:33:13 +0000166 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000167 AtLoc = ConsumeToken(); // consume @
Sebastian Redl43bc2a02008-12-11 20:12:42 +0000168 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000169 }
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000170
Douglas Gregor791215b2009-09-21 20:51:25 +0000171 case tok::code_completion:
John McCallf312b1e2010-08-26 23:41:50 +0000172 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000173 cutOffParsing();
174 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000175
Douglas Gregor312eadb2011-04-24 05:37:28 +0000176 case tok::identifier: {
177 Token Next = NextToken();
178 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000179 // identifier ':' statement
Richard Smith534986f2012-04-14 00:33:13 +0000180 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000181 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000182
Richard Smith05766812012-08-18 00:55:03 +0000183 // Look up the identifier, and typo-correct it to a keyword if it's not
184 // found.
Douglas Gregor3b887352011-04-27 04:48:22 +0000185 if (Next.isNot(tok::coloncolon)) {
Richard Smith05766812012-08-18 00:55:03 +0000186 // Try to limit which sets of keywords should be included in typo
187 // correction based on what the next token is.
Stephen Hines176edba2014-12-01 14:53:08 -0800188 if (TryAnnotateName(/*IsAddressOfOperand*/ false,
189 llvm::make_unique<StatementFilterCCC>(Next)) ==
190 ANK_Error) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000191 // Handle errors here by skipping up to the next semicolon or '}', and
192 // eat the semicolon if that's what stopped us.
Alexey Bataev8fe24752013-11-18 08:17:37 +0000193 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000194 if (Tok.is(tok::semi))
195 ConsumeToken();
196 return StmtError();
Richard Smith05766812012-08-18 00:55:03 +0000197 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000198
Richard Smith05766812012-08-18 00:55:03 +0000199 // If the identifier was typo-corrected, try again.
200 if (Tok.isNot(tok::identifier))
Douglas Gregor312eadb2011-04-24 05:37:28 +0000201 goto Retry;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000202 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000203
Douglas Gregor312eadb2011-04-24 05:37:28 +0000204 // Fall through
205 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000206
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000207 default: {
David Blaikie4e4d0842012-03-11 07:00:24 +0000208 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner97144fc2009-04-02 04:16:50 +0000209 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Stephen Hines176edba2014-12-01 14:53:08 -0800210 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
Richard Smith534986f2012-04-14 00:33:13 +0000211 DeclEnd, Attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000212 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000213 }
214
215 if (Tok.is(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 Diag(Tok, diag::err_expected_statement);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000217 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Richard Smith534986f2012-04-14 00:33:13 +0000220 return ParseExprStatement();
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000221 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000222
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000224 return ParseCaseStatement();
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000226 return ParseDefaultStatement();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000227
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smith534986f2012-04-14 00:33:13 +0000229 return ParseCompoundStatement();
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000230 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +0000231 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
232 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000233 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000234
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smith534986f2012-04-14 00:33:13 +0000236 return ParseIfStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smith534986f2012-04-14 00:33:13 +0000238 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000239
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smith534986f2012-04-14 00:33:13 +0000241 return ParseWhileStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smith534986f2012-04-14 00:33:13 +0000243 Res = ParseDoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000244 SemiError = "do/while";
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 break;
246 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smith534986f2012-04-14 00:33:13 +0000247 return ParseForStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000248
249 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smith534986f2012-04-14 00:33:13 +0000250 Res = ParseGotoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000251 SemiError = "goto";
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 break;
253 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smith534986f2012-04-14 00:33:13 +0000254 Res = ParseContinueStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000255 SemiError = "continue";
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 break;
257 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smith534986f2012-04-14 00:33:13 +0000258 Res = ParseBreakStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000259 SemiError = "break";
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 break;
261 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smith534986f2012-04-14 00:33:13 +0000262 Res = ParseReturnStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000263 SemiError = "return";
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 break;
Sebastian Redl61364dd2008-12-11 19:30:53 +0000265
Sebastian Redla0fd8652008-12-21 16:41:36 +0000266 case tok::kw_asm: {
Richard Smith534986f2012-04-14 00:33:13 +0000267 ProhibitAttributes(Attrs);
Steve Naroffd62701b2008-02-07 03:50:06 +0000268 bool msAsm = false;
269 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +0000270 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000271 if (msAsm) return Res;
Chris Lattner6869d8e2009-06-14 00:07:48 +0000272 SemiError = "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 break;
274 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000275
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700276 case tok::kw___if_exists:
277 case tok::kw___if_not_exists:
278 ProhibitAttributes(Attrs);
279 ParseMicrosoftIfExistsStatement(Stmts);
280 // An __if_exists block is like a compound statement, but it doesn't create
281 // a new scope.
282 return StmtEmpty();
283
Sebastian Redla0fd8652008-12-21 16:41:36 +0000284 case tok::kw_try: // C++ 15: try-block
Richard Smith534986f2012-04-14 00:33:13 +0000285 return ParseCXXTryBlock();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000286
287 case tok::kw___try:
Richard Smith534986f2012-04-14 00:33:13 +0000288 ProhibitAttributes(Attrs); // TODO: is it correct?
289 return ParseSEHTryBlock();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000290
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700291 case tok::kw___leave:
292 Res = ParseSEHLeaveStatement();
293 SemiError = "__leave";
294 break;
295
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000296 case tok::annot_pragma_vis:
Richard Smith534986f2012-04-14 00:33:13 +0000297 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000298 HandlePragmaVisibility();
299 return StmtEmpty();
300
301 case tok::annot_pragma_pack:
Richard Smith534986f2012-04-14 00:33:13 +0000302 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000303 HandlePragmaPack();
304 return StmtEmpty();
Eli Friedman9595c7e2012-10-04 02:36:51 +0000305
Eli Friedman8b2bfdd2012-10-09 22:46:54 +0000306 case tok::annot_pragma_msstruct:
307 ProhibitAttributes(Attrs);
308 HandlePragmaMSStruct();
309 return StmtEmpty();
310
Eli Friedman3ef38ee2012-10-08 23:52:38 +0000311 case tok::annot_pragma_align:
312 ProhibitAttributes(Attrs);
313 HandlePragmaAlign();
314 return StmtEmpty();
315
Eli Friedman8b2bfdd2012-10-09 22:46:54 +0000316 case tok::annot_pragma_weak:
317 ProhibitAttributes(Attrs);
318 HandlePragmaWeak();
319 return StmtEmpty();
320
321 case tok::annot_pragma_weakalias:
322 ProhibitAttributes(Attrs);
323 HandlePragmaWeakAlias();
324 return StmtEmpty();
325
326 case tok::annot_pragma_redefine_extname:
327 ProhibitAttributes(Attrs);
328 HandlePragmaRedefineExtname();
329 return StmtEmpty();
330
Eli Friedman9595c7e2012-10-04 02:36:51 +0000331 case tok::annot_pragma_fp_contract:
Richard Smithaed01162013-11-15 21:10:54 +0000332 ProhibitAttributes(Attrs);
Lang Hames860022c2012-10-21 01:10:01 +0000333 Diag(Tok, diag::err_pragma_fp_contract_scope);
334 ConsumeToken();
335 return StmtError();
336
Eli Friedman9595c7e2012-10-04 02:36:51 +0000337 case tok::annot_pragma_opencl_extension:
338 ProhibitAttributes(Attrs);
339 HandlePragmaOpenCLExtension();
340 return StmtEmpty();
Alexey Bataevc6400582013-03-22 06:34:35 +0000341
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000342 case tok::annot_pragma_captured:
Richard Smith175d4172013-09-16 21:17:44 +0000343 ProhibitAttributes(Attrs);
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000344 return HandlePragmaCaptured();
345
Alexey Bataevc6400582013-03-22 06:34:35 +0000346 case tok::annot_pragma_openmp:
Richard Smith175d4172013-09-16 21:17:44 +0000347 ProhibitAttributes(Attrs);
Stephen Hines176edba2014-12-01 14:53:08 -0800348 return ParseOpenMPDeclarativeOrExecutableDirective(!OnlyStatement);
Alexey Bataev4fa7eab2013-07-19 03:13:43 +0000349
Stephen Hines651f13c2014-04-23 16:59:28 -0700350 case tok::annot_pragma_ms_pointers_to_members:
351 ProhibitAttributes(Attrs);
352 HandlePragmaMSPointersToMembers();
353 return StmtEmpty();
354
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700355 case tok::annot_pragma_ms_pragma:
356 ProhibitAttributes(Attrs);
357 HandlePragmaMSPragma();
358 return StmtEmpty();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700359
360 case tok::annot_pragma_loop_hint:
361 ProhibitAttributes(Attrs);
362 return ParsePragmaLoopHint(Stmts, OnlyStatement, TrailingElseLoc, Attrs);
Sebastian Redla0fd8652008-12-21 16:41:36 +0000363 }
364
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 // If we reached this code, the statement must end in a semicolon.
Stephen Hines651f13c2014-04-23 16:59:28 -0700366 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner7b3684a2009-06-14 00:23:56 +0000367 // If the result was valid, then we do want to diagnose this. Use
368 // ExpectAndConsume to emit the diagnostic, even though we know it won't
369 // succeed.
370 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner19504402008-11-13 18:52:53 +0000371 // Skip until we see a } or ;, but don't eat it.
Alexey Bataev8fe24752013-11-18 08:17:37 +0000372 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000375 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000376}
377
Douglas Gregor312eadb2011-04-24 05:37:28 +0000378/// \brief Parse an expression statement.
Richard Smith534986f2012-04-14 00:33:13 +0000379StmtResult Parser::ParseExprStatement() {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000380 // If a case keyword is missing, this is where it should be inserted.
381 Token OldToken = Tok;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000382
Douglas Gregor312eadb2011-04-24 05:37:28 +0000383 // expression[opt] ';'
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000384 ExprResult Expr(ParseExpression());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000385 if (Expr.isInvalid()) {
386 // If the expression is invalid, skip ahead to the next semicolon or '}'.
387 // Not doing this opens us up to the possibility of infinite loops if
388 // ParseExpression does not consume any tokens.
Alexey Bataev8fe24752013-11-18 08:17:37 +0000389 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000390 if (Tok.is(tok::semi))
391 ConsumeToken();
John McCallb760f112013-03-22 02:10:40 +0000392 return Actions.ActOnExprStmtError();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000393 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000394
Douglas Gregor312eadb2011-04-24 05:37:28 +0000395 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
396 Actions.CheckCaseExpression(Expr.get())) {
397 // If a constant expression is followed by a colon inside a switch block,
398 // suggest a missing case keyword.
399 Diag(OldToken, diag::err_expected_case_before_expression)
400 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000401
Douglas Gregor312eadb2011-04-24 05:37:28 +0000402 // Recover parsing as a case statement.
Richard Smith534986f2012-04-14 00:33:13 +0000403 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000404 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000405
Douglas Gregor312eadb2011-04-24 05:37:28 +0000406 // Otherwise, eat the semicolon.
407 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000408 return Actions.ActOnExprStmt(Expr);
John Wiegley28bbe4b2011-04-28 01:08:34 +0000409}
Douglas Gregor312eadb2011-04-24 05:37:28 +0000410
John Wiegley28bbe4b2011-04-28 01:08:34 +0000411/// ParseSEHTryBlockCommon
412///
413/// seh-try-block:
414/// '__try' compound-statement seh-handler
415///
416/// seh-handler:
417/// seh-except-block
418/// seh-finally-block
419///
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700420StmtResult Parser::ParseSEHTryBlock() {
421 assert(Tok.is(tok::kw___try) && "Expected '__try'");
422 SourceLocation TryLoc = ConsumeToken();
423
424 if (Tok.isNot(tok::l_brace))
Stephen Hines651f13c2014-04-23 16:59:28 -0700425 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley28bbe4b2011-04-28 01:08:34 +0000426
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700427 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
428 Scope::DeclScope | Scope::SEHTryScope));
John Wiegley28bbe4b2011-04-28 01:08:34 +0000429 if(TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000430 return TryBlock;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000431
432 StmtResult Handler;
Richard Smith534986f2012-04-14 00:33:13 +0000433 if (Tok.is(tok::identifier) &&
Douglas Gregorb57791e2011-10-21 03:57:52 +0000434 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000435 SourceLocation Loc = ConsumeToken();
436 Handler = ParseSEHExceptBlock(Loc);
437 } else if (Tok.is(tok::kw___finally)) {
438 SourceLocation Loc = ConsumeToken();
439 Handler = ParseSEHFinallyBlock(Loc);
440 } else {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700441 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
John Wiegley28bbe4b2011-04-28 01:08:34 +0000442 }
443
444 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000445 return Handler;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000446
447 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
448 TryLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700449 TryBlock.get(),
450 Handler.get());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000451}
452
453/// ParseSEHExceptBlock - Handle __except
454///
455/// seh-except-block:
456/// '__except' '(' seh-filter-expression ')' compound-statement
457///
458StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
459 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
460 raii2(Ident___exception_code, false),
461 raii3(Ident_GetExceptionCode, false);
462
Stephen Hines651f13c2014-04-23 16:59:28 -0700463 if (ExpectAndConsume(tok::l_paren))
John Wiegley28bbe4b2011-04-28 01:08:34 +0000464 return StmtError();
465
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700466 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
467 Scope::SEHExceptScope);
John Wiegley28bbe4b2011-04-28 01:08:34 +0000468
David Blaikie4e4d0842012-03-11 07:00:24 +0000469 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000470 Ident__exception_info->setIsPoisoned(false);
471 Ident___exception_info->setIsPoisoned(false);
472 Ident_GetExceptionInfo->setIsPoisoned(false);
473 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700474
475 ExprResult FilterExpr;
476 {
477 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
478 Scope::SEHFilterScope);
479 FilterExpr = ParseExpression();
480 }
Francois Pichetd7f02df2011-04-28 03:14:31 +0000481
David Blaikie4e4d0842012-03-11 07:00:24 +0000482 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000483 Ident__exception_info->setIsPoisoned(true);
484 Ident___exception_info->setIsPoisoned(true);
485 Ident_GetExceptionInfo->setIsPoisoned(true);
486 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000487
488 if(FilterExpr.isInvalid())
489 return StmtError();
490
Stephen Hines651f13c2014-04-23 16:59:28 -0700491 if (ExpectAndConsume(tok::r_paren))
John Wiegley28bbe4b2011-04-28 01:08:34 +0000492 return StmtError();
493
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700494 if (Tok.isNot(tok::l_brace))
495 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
496
Richard Smith534986f2012-04-14 00:33:13 +0000497 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000498
499 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000500 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000501
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700502 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000503}
504
505/// ParseSEHFinallyBlock - Handle __finally
506///
507/// seh-finally-block:
508/// '__finally' compound-statement
509///
510StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
511 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
512 raii2(Ident___abnormal_termination, false),
513 raii3(Ident_AbnormalTermination, false);
514
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700515 if (Tok.isNot(tok::l_brace))
516 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
517
Richard Smith534986f2012-04-14 00:33:13 +0000518 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000519 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000520 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000521
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700522 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.get());
523}
524
525/// Handle __leave
526///
527/// seh-leave-statement:
528/// '__leave' ';'
529///
530StmtResult Parser::ParseSEHLeaveStatement() {
531 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
532 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000533}
534
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000535/// ParseLabeledStatement - We have an identifier and a ':' after it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000536///
537/// labeled-statement:
538/// identifier ':' statement
539/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000540///
Richard Smith534986f2012-04-14 00:33:13 +0000541StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000542 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
543 "Not an identifier!");
544
545 Token IdentTok = Tok; // Save the whole token.
546 ConsumeToken(); // eat the identifier.
547
548 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000549
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000550 // identifier ':' statement
551 SourceLocation ColonLoc = ConsumeToken();
552
Richard Smith93982a72013-11-15 22:45:29 +0000553 // Read label attributes, if present.
554 StmtResult SubStmt;
555 if (Tok.is(tok::kw___attribute)) {
556 ParsedAttributesWithRange TempAttrs(AttrFactory);
557 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000558
Richard Smith93982a72013-11-15 22:45:29 +0000559 // In C++, GNU attributes only apply to the label if they are followed by a
560 // semicolon, to disambiguate label attributes from attributes on a labeled
561 // declaration.
562 //
563 // This doesn't quite match what GCC does; if the attribute list is empty
564 // and followed by a semicolon, GCC will reject (it appears to parse the
565 // attributes as part of a statement in that case). That looks like a bug.
566 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
567 attrs.takeAllFrom(TempAttrs);
568 else if (isDeclarationStatement()) {
569 StmtVector Stmts;
570 // FIXME: We should do this whether or not we have a declaration
571 // statement, but that doesn't work correctly (because ProhibitAttributes
572 // can't handle GNU attributes), so only call it in the one case where
573 // GNU attributes are allowed.
574 SubStmt = ParseStatementOrDeclarationAfterAttributes(
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700575 Stmts, /*OnlyStmts*/ true, nullptr, TempAttrs);
Richard Smith93982a72013-11-15 22:45:29 +0000576 if (!TempAttrs.empty() && !SubStmt.isInvalid())
577 SubStmt = Actions.ProcessStmtAttributes(
578 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
579 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -0700580 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smith93982a72013-11-15 22:45:29 +0000581 }
582 }
583
584 // If we've not parsed a statement yet, parse one now.
585 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
586 SubStmt = ParseStatement();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000587
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000588 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000589 if (SubStmt.isInvalid())
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000590 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000591
Chris Lattner337e5502011-02-18 01:27:55 +0000592 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
593 IdentTok.getLocation());
Richard Smith534986f2012-04-14 00:33:13 +0000594 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattner337e5502011-02-18 01:27:55 +0000595 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smith534986f2012-04-14 00:33:13 +0000596 attrs.clear();
597 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000598
Chris Lattner337e5502011-02-18 01:27:55 +0000599 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
600 SubStmt.get());
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000601}
Reid Spencer5f016e22007-07-11 17:01:13 +0000602
603/// ParseCaseStatement
604/// labeled-statement:
605/// 'case' constant-expression ':' statement
606/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
607///
Richard Smith534986f2012-04-14 00:33:13 +0000608StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smith46f11102011-04-21 22:48:40 +0000609 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Chris Lattner24e1e702009-03-04 04:23:07 +0000611 // It is very very common for code to contain many case statements recursively
612 // nested, as in (but usually without indentation):
613 // case 1:
614 // case 2:
615 // case 3:
616 // case 4:
617 // case 5: etc.
618 //
619 // Parsing this naively works, but is both inefficient and can cause us to run
620 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner26140c62009-03-04 18:24:58 +0000621 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner24e1e702009-03-04 04:23:07 +0000622 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smith93982a72013-11-15 22:45:29 +0000623 // weirdness in the actions), so this is just local grossness :).
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Chris Lattner24e1e702009-03-04 04:23:07 +0000625 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
626 // example above.
John McCall60d7b3a2010-08-24 06:29:42 +0000627 StmtResult TopLevelCase(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattner24e1e702009-03-04 04:23:07 +0000629 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
630 // gets updated each time a new case is parsed, and whose body is unset so
631 // far. When parsing 'case 4', this is the 'case 3' node.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700632 Stmt *DeepestParsedCaseStmt = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattner24e1e702009-03-04 04:23:07 +0000634 // While we have case statements, eat and stack them.
David Majnemer0e1e69c2011-06-13 05:50:12 +0000635 SourceLocation ColonLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000636 do {
Richard Trieubb9b80c2011-04-21 21:44:26 +0000637 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
638 ConsumeToken(); // eat the 'case'.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700639 ColonLoc = SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000641 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000642 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000643 cutOffParsing();
644 return StmtError();
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000645 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000646
Chris Lattner6fb09c82009-12-10 00:38:54 +0000647 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
648 /// Disable this form of error recovery while we're parsing the case
649 /// expression.
650 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000651
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700652 ExprResult LHS;
653 if (!MissingCase) {
654 LHS = ParseConstantExpression();
Stephen Hines176edba2014-12-01 14:53:08 -0800655 if (!getLangOpts().CPlusPlus11) {
656 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
657 return Actions.VerifyIntegerConstantExpression(E);
658 });
659 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700660 if (LHS.isInvalid()) {
661 // If constant-expression is parsed unsuccessfully, recover by skipping
662 // current case statement (moving to the colon that ends it).
663 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
664 TryConsumeToken(tok::colon, ColonLoc);
665 continue;
666 }
667 return StmtError();
668 }
669 } else {
670 LHS = Expr;
671 MissingCase = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000673
Chris Lattner24e1e702009-03-04 04:23:07 +0000674 // GNU case range extension.
675 SourceLocation DotDotDotLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000676 ExprResult RHS;
Stephen Hines651f13c2014-04-23 16:59:28 -0700677 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
678 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Chris Lattner24e1e702009-03-04 04:23:07 +0000679 RHS = ParseConstantExpression();
680 if (RHS.isInvalid()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700681 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
682 TryConsumeToken(tok::colon, ColonLoc);
683 continue;
684 }
Chris Lattner24e1e702009-03-04 04:23:07 +0000685 return StmtError();
686 }
687 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000688
Chris Lattner6fb09c82009-12-10 00:38:54 +0000689 ColonProtection.restore();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000690
Stephen Hines651f13c2014-04-23 16:59:28 -0700691 if (TryConsumeToken(tok::colon, ColonLoc)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700692 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
693 TryConsumeToken(tok::coloncolon, ColonLoc)) {
694 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Stephen Hines651f13c2014-04-23 16:59:28 -0700695 Diag(ColonLoc, diag::err_expected_after)
696 << "'case'" << tok::colon
697 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCallf6a3ab02011-01-22 09:28:32 +0000698 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000699 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Stephen Hines651f13c2014-04-23 16:59:28 -0700700 Diag(ExpectedLoc, diag::err_expected_after)
701 << "'case'" << tok::colon
702 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor662a4822010-12-23 22:56:40 +0000703 ColonLoc = ExpectedLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000704 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000705
John McCall60d7b3a2010-08-24 06:29:42 +0000706 StmtResult Case =
John McCall9ae2f072010-08-23 23:25:46 +0000707 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
708 RHS.get(), ColonLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattner24e1e702009-03-04 04:23:07 +0000710 // If we had a sema error parsing this case, then just ignore it and
711 // continue parsing the sub-stmt.
712 if (Case.isInvalid()) {
713 if (TopLevelCase.isInvalid()) // No parsed case stmts.
714 return ParseStatement();
715 // Otherwise, just don't add it as a nested case.
716 } else {
717 // If this is the first case statement we parsed, it becomes TopLevelCase.
718 // Otherwise we link it into the current chain.
John McCallca0408f2010-08-23 06:44:23 +0000719 Stmt *NextDeepest = Case.get();
Chris Lattner24e1e702009-03-04 04:23:07 +0000720 if (TopLevelCase.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000721 TopLevelCase = Case;
Chris Lattner24e1e702009-03-04 04:23:07 +0000722 else
John McCall9ae2f072010-08-23 23:25:46 +0000723 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner24e1e702009-03-04 04:23:07 +0000724 DeepestParsedCaseStmt = NextDeepest;
725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Chris Lattner24e1e702009-03-04 04:23:07 +0000727 // Handle all case statements.
728 } while (Tok.is(tok::kw_case));
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Chris Lattner24e1e702009-03-04 04:23:07 +0000730 // If we found a non-case statement, start by parsing it.
John McCall60d7b3a2010-08-24 06:29:42 +0000731 StmtResult SubStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattner24e1e702009-03-04 04:23:07 +0000733 if (Tok.isNot(tok::r_brace)) {
734 SubStmt = ParseStatement();
735 } else {
736 // Nicely diagnose the common error "switch (X) { case 4: }", which is
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700737 // not valid. If ColonLoc doesn't point to a valid text location, there was
738 // another parsing error, so avoid producing extra diagnostics.
739 if (ColonLoc.isValid()) {
740 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
741 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
742 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
743 }
744 SubStmt = StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 }
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Chris Lattner24e1e702009-03-04 04:23:07 +0000747 // Install the body into the most deeply-nested case.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700748 if (DeepestParsedCaseStmt) {
749 // Broken sub-stmt shouldn't prevent forming the case statement properly.
750 if (SubStmt.isInvalid())
751 SubStmt = Actions.ActOnNullStmt(SourceLocation());
752 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
753 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000754
Chris Lattner24e1e702009-03-04 04:23:07 +0000755 // Return the top level parsed statement tree.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000756 return TopLevelCase;
Reid Spencer5f016e22007-07-11 17:01:13 +0000757}
758
759/// ParseDefaultStatement
760/// labeled-statement:
761/// 'default' ':' statement
762/// Note that this does not parse the 'statement' at the end.
763///
Richard Smith534986f2012-04-14 00:33:13 +0000764StmtResult Parser::ParseDefaultStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000765 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000766 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
767
Douglas Gregor662a4822010-12-23 22:56:40 +0000768 SourceLocation ColonLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -0700769 if (TryConsumeToken(tok::colon, ColonLoc)) {
770 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
771 // Treat "default;" as a typo for "default:".
772 Diag(ColonLoc, diag::err_expected_after)
773 << "'default'" << tok::colon
774 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCallf6a3ab02011-01-22 09:28:32 +0000775 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000776 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Stephen Hines651f13c2014-04-23 16:59:28 -0700777 Diag(ExpectedLoc, diag::err_expected_after)
778 << "'default'" << tok::colon
779 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor662a4822010-12-23 22:56:40 +0000780 ColonLoc = ExpectedLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +0000781 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000782
Richard Smith85b29a42012-02-17 01:35:32 +0000783 StmtResult SubStmt;
784
785 if (Tok.isNot(tok::r_brace)) {
786 SubStmt = ParseStatement();
787 } else {
788 // Diagnose the common error "switch (X) {... default: }", which is
789 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000790 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000791 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
792 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
793 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 }
795
Richard Smith85b29a42012-02-17 01:35:32 +0000796 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000797 if (SubStmt.isInvalid())
Richard Smith85b29a42012-02-17 01:35:32 +0000798 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000799
Sebastian Redl117054a2008-12-28 16:13:43 +0000800 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000801 SubStmt.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +0000802}
803
Richard Smith534986f2012-04-14 00:33:13 +0000804StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
805 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregorbca01b42011-07-06 22:04:06 +0000806}
Reid Spencer5f016e22007-07-11 17:01:13 +0000807
808/// ParseCompoundStatement - Parse a "{}" block.
809///
810/// compound-statement: [C99 6.8.2]
811/// { block-item-list[opt] }
812/// [GNU] { label-declarations block-item-list } [TODO]
813///
814/// block-item-list:
815/// block-item
816/// block-item-list block-item
817///
818/// block-item:
819/// declaration
Chris Lattner45a566c2007-08-27 01:01:57 +0000820/// [GNU] '__extension__' declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000821/// statement
Reid Spencer5f016e22007-07-11 17:01:13 +0000822///
823/// [GNU] label-declarations:
824/// [GNU] label-declaration
825/// [GNU] label-declarations label-declaration
826///
827/// [GNU] label-declaration:
828/// [GNU] '__label__' identifier-list ';'
829///
Richard Smith534986f2012-04-14 00:33:13 +0000830StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000831 unsigned ScopeFlags) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000832 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000833
Chris Lattner31e05722007-08-26 06:24:45 +0000834 // Enter a scope to hold everything within the compound stmt. Compound
835 // statements can always hold declarations.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000836 ParseScope CompoundScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000837
838 // Parse the statements in the body.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000839 return ParseCompoundStatementBody(isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000840}
841
Lang Hamesa60d21d2012-11-03 22:29:05 +0000842/// Parse any pragmas at the start of the compound expression. We handle these
843/// separately since some pragmas (FP_CONTRACT) must appear before any C
844/// statement in the compound, but may be intermingled with other pragmas.
845void Parser::ParseCompoundStatementLeadingPragmas() {
846 bool checkForPragmas = true;
847 while (checkForPragmas) {
848 switch (Tok.getKind()) {
849 case tok::annot_pragma_vis:
850 HandlePragmaVisibility();
851 break;
852 case tok::annot_pragma_pack:
853 HandlePragmaPack();
854 break;
855 case tok::annot_pragma_msstruct:
856 HandlePragmaMSStruct();
857 break;
858 case tok::annot_pragma_align:
859 HandlePragmaAlign();
860 break;
861 case tok::annot_pragma_weak:
862 HandlePragmaWeak();
863 break;
864 case tok::annot_pragma_weakalias:
865 HandlePragmaWeakAlias();
866 break;
867 case tok::annot_pragma_redefine_extname:
868 HandlePragmaRedefineExtname();
869 break;
870 case tok::annot_pragma_opencl_extension:
871 HandlePragmaOpenCLExtension();
872 break;
873 case tok::annot_pragma_fp_contract:
874 HandlePragmaFPContract();
875 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700876 case tok::annot_pragma_ms_pointers_to_members:
877 HandlePragmaMSPointersToMembers();
878 break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700879 case tok::annot_pragma_ms_pragma:
880 HandlePragmaMSPragma();
881 break;
Lang Hamesa60d21d2012-11-03 22:29:05 +0000882 default:
883 checkForPragmas = false;
884 break;
885 }
886 }
887
888}
889
Reid Spencer5f016e22007-07-11 17:01:13 +0000890/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff1b273c42007-09-16 14:56:35 +0000891/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Reid Spencer5f016e22007-07-11 17:01:13 +0000892/// consume the '}' at the end of the block. It does not manipulate the scope
893/// stack.
John McCall60d7b3a2010-08-24 06:29:42 +0000894StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump1eb44332009-09-09 15:08:12 +0000895 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerae50fa02009-03-05 00:00:31 +0000896 Tok.getLocation(),
897 "in compound statement ('{}')");
Lang Hamesbe9af122012-10-02 04:45:10 +0000898
899 // Record the state of the FP_CONTRACT pragma, restore on leaving the
900 // compound statement.
901 Sema::FPContractStateRAII SaveFPContractState(Actions);
902
Douglas Gregor0fbda682010-09-15 14:51:05 +0000903 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000904 BalancedDelimiterTracker T(*this, tok::l_brace);
905 if (T.consumeOpen())
906 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000907
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000908 Sema::CompoundScopeRAII CompoundScope(Actions);
909
Lang Hamesa60d21d2012-11-03 22:29:05 +0000910 // Parse any pragmas at the beginning of the compound statement.
911 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000912
Lang Hamesa60d21d2012-11-03 22:29:05 +0000913 StmtVector Stmts;
Lang Hames860022c2012-10-21 01:10:01 +0000914
Chris Lattner4ae493c2011-02-18 02:08:43 +0000915 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
916 // only allowed at the start of a compound stmt regardless of the language.
917 while (Tok.is(tok::kw___label__)) {
918 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000919
Chris Lattner5f9e2722011-07-23 10:55:15 +0000920 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000921 while (1) {
922 if (Tok.isNot(tok::identifier)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700923 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000924 break;
925 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000926
Chris Lattner4ae493c2011-02-18 02:08:43 +0000927 IdentifierInfo *II = Tok.getIdentifierInfo();
928 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara67843042011-03-05 18:21:20 +0000929 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000930
Stephen Hines651f13c2014-04-23 16:59:28 -0700931 if (!TryConsumeToken(tok::comma))
Chris Lattner4ae493c2011-02-18 02:08:43 +0000932 break;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000933 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000934
John McCall0b7e6782011-03-24 11:26:52 +0000935 DeclSpec DS(AttrFactory);
Rafael Espindola4549d7f2013-07-09 12:05:01 +0000936 DeclGroupPtrTy Res =
937 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000938 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000939
Chris Lattner8bb21d32012-04-28 16:12:17 +0000940 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000941 if (R.isUsable())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700942 Stmts.push_back(R.get());
Chris Lattner4ae493c2011-02-18 02:08:43 +0000943 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000944
Stephen Hines651f13c2014-04-23 16:59:28 -0700945 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000946 if (Tok.is(tok::annot_pragma_unused)) {
947 HandlePragmaUnused();
948 continue;
949 }
950
John McCall60d7b3a2010-08-24 06:29:42 +0000951 StmtResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000952 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000953 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattner45a566c2007-08-27 01:01:57 +0000954 } else {
955 // __extension__ can start declarations and it can also be a unary
956 // operator for expressions. Consume multiple __extension__ markers here
957 // until we can determine which is which.
Eli Friedmanadf077f2009-01-27 08:43:38 +0000958 // FIXME: This loses extension expressions in the AST!
Chris Lattner45a566c2007-08-27 01:01:57 +0000959 SourceLocation ExtLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000960 while (Tok.is(tok::kw___extension__))
Chris Lattner45a566c2007-08-27 01:01:57 +0000961 ConsumeToken();
Chris Lattner39146d62008-10-20 06:51:33 +0000962
John McCall0b7e6782011-03-24 11:26:52 +0000963 ParsedAttributesWithRange attrs(AttrFactory);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700964 MaybeParseCXX11Attributes(attrs, nullptr,
965 /*MightBeObjCMessageSend*/ true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000966
Chris Lattner45a566c2007-08-27 01:01:57 +0000967 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis5404a152008-10-05 00:06:24 +0000968 if (isDeclarationStatement()) {
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000969 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner97144fc2009-04-02 04:16:50 +0000970 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000971 ExtensionRAIIObject O(Diags);
972
Chris Lattner97144fc2009-04-02 04:16:50 +0000973 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Stephen Hines176edba2014-12-01 14:53:08 -0800974 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000975 attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000976 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattner45a566c2007-08-27 01:01:57 +0000977 } else {
Eli Friedmanadf077f2009-01-27 08:43:38 +0000978 // Otherwise this was a unary __extension__ marker.
John McCall60d7b3a2010-08-24 06:29:42 +0000979 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattner043a0b52008-03-13 06:32:11 +0000980
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000981 if (Res.isInvalid()) {
Chris Lattner45a566c2007-08-27 01:01:57 +0000982 SkipUntil(tok::semi);
983 continue;
984 }
Sebastian Redlf512e822009-01-18 18:03:53 +0000985
Sean Huntbbd37c62009-11-21 08:43:09 +0000986 // FIXME: Use attributes?
Chris Lattner39146d62008-10-20 06:51:33 +0000987 // Eat the semicolon at the end of stmt and convert the expr into a
988 // statement.
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000989 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000990 R = Actions.ActOnExprStmt(Res);
Chris Lattner45a566c2007-08-27 01:01:57 +0000991 }
992 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000993
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000994 if (R.isUsable())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700995 Stmts.push_back(R.get());
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000997
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000998 SourceLocation CloseLoc = Tok.getLocation();
999
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 // We broke out of the while loop because we found a '}' or EOF.
Nico Weberd11f4352012-12-30 23:36:56 +00001001 if (!T.consumeClose())
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +00001002 // Recover by creating a compound statement with what we parsed so far,
1003 // instead of dropping everything and returning StmtError();
Nico Weberd11f4352012-12-30 23:36:56 +00001004 CloseLoc = T.getCloseLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001005
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +00001006 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001007 Stmts, isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001008}
1009
Chris Lattner15ff1112008-12-12 06:31:07 +00001010/// ParseParenExprOrCondition:
1011/// [C ] '(' expression ')'
Chris Lattnerff871fb2008-12-12 06:35:28 +00001012/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattner15ff1112008-12-12 06:31:07 +00001013///
1014/// This function parses and performs error recovery on the specified condition
1015/// or expression (depending on whether we're in C++ or C mode). This function
1016/// goes out of its way to recover well. It returns true if there was a parser
1017/// error (the right paren couldn't be found), which indicates that the caller
1018/// should try to recover harder. It returns false if the condition is
1019/// successfully parsed. Note that a successful parse can still have semantic
1020/// errors in the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001021bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCalld226f652010-08-21 09:40:31 +00001022 Decl *&DeclResult,
Douglas Gregor586596f2010-05-06 17:25:47 +00001023 SourceLocation Loc,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001024 bool ConvertToBoolean) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001025 BalancedDelimiterTracker T(*this, tok::l_paren);
1026 T.consumeOpen();
1027
David Blaikie4e4d0842012-03-11 07:00:24 +00001028 if (getLangOpts().CPlusPlus)
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001029 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001030 else {
1031 ExprResult = ParseExpression();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001032 DeclResult = nullptr;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001033
Douglas Gregor586596f2010-05-06 17:25:47 +00001034 // If required, convert to a boolean value.
1035 if (!ExprResult.isInvalid() && ConvertToBoolean)
1036 ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00001037 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner15ff1112008-12-12 06:31:07 +00001040 // If the parser was confused by the condition and we don't have a ')', try to
1041 // recover by skipping ahead to a semi and bailing out. If condexp is
1042 // semantically invalid but we have well formed code, keep going.
John McCalld226f652010-08-21 09:40:31 +00001043 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattner15ff1112008-12-12 06:31:07 +00001044 SkipUntil(tok::semi);
1045 // Skipping may have stopped if it found the containing ')'. If so, we can
1046 // continue parsing the if statement.
1047 if (Tok.isNot(tok::r_paren))
1048 return true;
1049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Chris Lattner15ff1112008-12-12 06:31:07 +00001051 // Otherwise the condition is valid or the rparen is present.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001052 T.consumeClose();
Chad Rosierb6604462012-07-10 21:35:27 +00001053
Chris Lattnerbddc7e52012-04-28 16:24:20 +00001054 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1055 // that all callers are looking for a statement after the condition, so ")"
1056 // isn't valid.
1057 while (Tok.is(tok::r_paren)) {
1058 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1059 << FixItHint::CreateRemoval(Tok.getLocation());
1060 ConsumeParen();
1061 }
Chad Rosierb6604462012-07-10 21:35:27 +00001062
Chris Lattner15ff1112008-12-12 06:31:07 +00001063 return false;
1064}
1065
1066
Reid Spencer5f016e22007-07-11 17:01:13 +00001067/// ParseIfStatement
1068/// if-statement: [C99 6.8.4.1]
1069/// 'if' '(' expression ')' statement
1070/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001071/// [C++] 'if' '(' condition ')' statement
1072/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +00001073///
Richard Smith534986f2012-04-14 00:33:13 +00001074StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001075 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1077
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001078 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001079 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +00001080 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +00001081 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001083
David Blaikie4e4d0842012-03-11 07:00:24 +00001084 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001085
Chris Lattner22153252007-08-26 23:08:06 +00001086 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1087 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001088 //
1089 // C++ 6.4p3:
1090 // A name introduced by a declaration in a condition is in scope from its
1091 // point of declaration until the end of the substatements controlled by the
1092 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001093 // C++ 3.3.2p4:
1094 // Names declared in the for-init-statement, and in the condition of if,
1095 // while, for, and switch statements are local to the if, while, for, or
1096 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001097 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001098 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +00001099
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001101 ExprResult CondExp;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001102 Decl *CondVar = nullptr;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001103 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001104 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +00001105
David Blaikiedef07622012-05-16 04:20:04 +00001106 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Chris Lattner0ecea032007-08-22 05:28:50 +00001108 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001109 // there is no compound stmt. C90 does not have this clause. We only do this
1110 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001111 //
1112 // C++ 6.4p1:
1113 // The substatement in a selection-statement (each substatement, in the else
1114 // form of the if statement) implicitly defines a local scope.
1115 //
1116 // For C++ we create a scope for the condition and a new scope for
1117 // substatements because:
1118 // -When the 'then' scope exits, we want the condition declaration to still be
1119 // active for the 'else' scope too.
1120 // -Sema will detect name clashes by considering declarations of a
1121 // 'ControlScope' as part of its direct subscope.
1122 // -If we wanted the condition and substatement to be in the same scope, we
1123 // would have to notify ParseStatement not to create a new scope. It's
1124 // simpler to let it create a new scope.
1125 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001126 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001127
Chris Lattnerb96728d2007-10-29 05:08:52 +00001128 // Read the 'then' stmt.
1129 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +00001130
1131 SourceLocation InnerStatementTrailingElseLoc;
1132 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001133
Chris Lattnera36ce712007-08-22 05:16:28 +00001134 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001135 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001136
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 // If it has an else, parse it.
1138 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +00001139 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +00001140 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001141
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001142 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +00001143 if (TrailingElseLoc)
1144 *TrailingElseLoc = Tok.getLocation();
1145
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +00001147 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001148
Chris Lattner0ecea032007-08-22 05:28:50 +00001149 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001150 // there is no compound stmt. C90 does not have this clause. We only do
1151 // this if the body isn't a compound statement to avoid push/pop in common
1152 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001153 //
1154 // C++ 6.4p1:
1155 // The substatement in a selection-statement (each substatement, in the else
1156 // form of the if statement) implicitly defines a local scope.
1157 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001158 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001159
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001161
Chris Lattnera36ce712007-08-22 05:16:28 +00001162 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001163 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +00001164 } else if (Tok.is(tok::code_completion)) {
1165 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001166 cutOffParsing();
1167 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +00001168 } else if (InnerStatementTrailingElseLoc.isValid()) {
1169 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001171
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001172 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Chris Lattnerb96728d2007-10-29 05:08:52 +00001174 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +00001175 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +00001176 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001177 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001178 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1179 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +00001180 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +00001181 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +00001182 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001183
Chris Lattnerb96728d2007-10-29 05:08:52 +00001184 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001185 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001186 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001187 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001188 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001189
John McCall9ae2f072010-08-23 23:25:46 +00001190 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001191 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001192}
1193
1194/// ParseSwitchStatement
1195/// switch-statement:
1196/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001197/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001198StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001199 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1201
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001202 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001203 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001205 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 }
Chris Lattner22153252007-08-26 23:08:06 +00001207
David Blaikie4e4d0842012-03-11 07:00:24 +00001208 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001209
Chris Lattner22153252007-08-26 23:08:06 +00001210 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1211 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001212 //
1213 // C++ 6.4p3:
1214 // A name introduced by a declaration in a condition is in scope from its
1215 // point of declaration until the end of the substatements controlled by the
1216 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001217 // C++ 3.3.2p4:
1218 // Names declared in the for-init-statement, and in the condition of if,
1219 // while, for, and switch statements are local to the if, while, for, or
1220 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001221 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001222 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001223 if (C99orCXX)
1224 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001225 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001226
1227 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001228 ExprResult Cond;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001229 Decl *CondVar = nullptr;
Douglas Gregor586596f2010-05-06 17:25:47 +00001230 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001231 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001232
John McCall60d7b3a2010-08-24 06:29:42 +00001233 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001234 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001235
Douglas Gregor586596f2010-05-06 17:25:47 +00001236 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001237 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001238 // FIXME: This is not optimal recovery, but parsing the body is more
1239 // dangerous due to the presence of case and default statements, which
1240 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001241 if (Tok.is(tok::l_brace)) {
1242 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001243 SkipUntil(tok::r_brace);
Douglas Gregor4186ff42010-05-20 23:20:59 +00001244 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001245 SkipUntil(tok::semi);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001246 return Switch;
Douglas Gregor586596f2010-05-06 17:25:47 +00001247 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001248
Chris Lattner0ecea032007-08-22 05:28:50 +00001249 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001250 // there is no compound stmt. C90 does not have this clause. We only do this
1251 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001252 //
1253 // C++ 6.4p1:
1254 // The substatement in a selection-statement (each substatement, in the else
1255 // form of the if statement) implicitly defines a local scope.
1256 //
1257 // See comments in ParseIfStatement for why we create a scope for the
1258 // condition and a new scope for substatement in C++.
1259 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001260 getCurScope()->AddFlags(Scope::BreakScope);
1261 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001262
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001263 // We have incremented the mangling number for the SwitchScope and the
1264 // InnerScope, which is one too many.
1265 if (C99orCXX)
1266 getCurScope()->decrementMSLocalManglingNumber();
1267
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001269 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001270
Chris Lattner7e52de42010-01-24 01:50:29 +00001271 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001272 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001273 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001274
John McCall9ae2f072010-08-23 23:25:46 +00001275 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001276}
1277
1278/// ParseWhileStatement
1279/// while-statement: [C99 6.8.5.1]
1280/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001281/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001282StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001283 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 SourceLocation WhileLoc = Tok.getLocation();
1285 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001286
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001287 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001288 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001290 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001292
David Blaikie4e4d0842012-03-11 07:00:24 +00001293 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001294
Chris Lattner22153252007-08-26 23:08:06 +00001295 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1296 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001297 //
1298 // C++ 6.4p3:
1299 // A name introduced by a declaration in a condition is in scope from its
1300 // point of declaration until the end of the substatements controlled by the
1301 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001302 // C++ 3.3.2p4:
1303 // Names declared in the for-init-statement, and in the condition of if,
1304 // while, for, and switch statements are local to the if, while, for, or
1305 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001306 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001307 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001308 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001309 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1310 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001311 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001312 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1313 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001314
1315 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001316 ExprResult Cond;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001317 Decl *CondVar = nullptr;
Douglas Gregor586596f2010-05-06 17:25:47 +00001318 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001319 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001320
David Blaikiedef07622012-05-16 04:20:04 +00001321 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Stephen Hines651f13c2014-04-23 16:59:28 -07001323 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001324 // there is no compound stmt. C90 does not have this clause. We only do this
1325 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001326 //
1327 // C++ 6.5p2:
1328 // The substatement in an iteration-statement implicitly defines a local scope
1329 // which is entered and exited each time through the loop.
1330 //
1331 // See comments in ParseIfStatement for why we create a scope for the
1332 // condition and a new scope for substatement in C++.
1333 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001334 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001335
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001337 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001338
Chris Lattner0ecea032007-08-22 05:28:50 +00001339 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001340 InnerScope.Exit();
1341 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001342
John McCalld226f652010-08-21 09:40:31 +00001343 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001344 return StmtError();
1345
John McCall9ae2f072010-08-23 23:25:46 +00001346 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001347}
1348
1349/// ParseDoStatement
1350/// do-statement: [C99 6.8.5.2]
1351/// 'do' statement 'while' '(' expression ')' ';'
1352/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001353StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001354 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001356
Chris Lattner22153252007-08-26 23:08:06 +00001357 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1358 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001359 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001360 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001361 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001362 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001363 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001364
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001365 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001366
Stephen Hines651f13c2014-04-23 16:59:28 -07001367 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001368 // there is no compound stmt. C90 does not have this clause. We only do this
1369 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001370 //
1371 // C++ 6.5p2:
1372 // The substatement in an iteration-statement implicitly defines a local scope
1373 // which is entered and exited each time through the loop.
1374 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001375 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1376 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001377
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001379 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001380
Chris Lattner0ecea032007-08-22 05:28:50 +00001381 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001382 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001383
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001384 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001385 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001386 Diag(Tok, diag::err_expected_while);
Stephen Hines651f13c2014-04-23 16:59:28 -07001387 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataev8fe24752013-11-18 08:17:37 +00001388 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner19504402008-11-13 18:52:53 +00001389 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001390 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 }
1392 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001393
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001394 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001395 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataev8fe24752013-11-18 08:17:37 +00001396 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001397 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001399
Richard Smith5eed7e02013-10-15 01:34:54 +00001400 // Parse the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001401 BalancedDelimiterTracker T(*this, tok::l_paren);
1402 T.consumeOpen();
Chad Rosierb6604462012-07-10 21:35:27 +00001403
Richard Smith5eed7e02013-10-15 01:34:54 +00001404 // A do-while expression is not a condition, so can't have attributes.
1405 DiagnoseAndSkipCXX11Attributes();
Sean Hunt2edf0a22012-06-23 05:07:58 +00001406
John McCall60d7b3a2010-08-24 06:29:42 +00001407 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001408 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001409 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001410
Sebastian Redl9a920342008-12-11 19:48:14 +00001411 if (Cond.isInvalid() || Body.isInvalid())
1412 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001413
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001414 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1415 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001416}
1417
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001418bool Parser::isForRangeIdentifier() {
1419 assert(Tok.is(tok::identifier));
1420
1421 const Token &Next = NextToken();
1422 if (Next.is(tok::colon))
1423 return true;
1424
1425 if (Next.is(tok::l_square) || Next.is(tok::kw_alignas)) {
1426 TentativeParsingAction PA(*this);
1427 ConsumeToken();
1428 SkipCXX11Attributes();
1429 bool Result = Tok.is(tok::colon);
1430 PA.Revert();
1431 return Result;
1432 }
1433
1434 return false;
1435}
1436
Reid Spencer5f016e22007-07-11 17:01:13 +00001437/// ParseForStatement
1438/// for-statement: [C99 6.8.5.3]
1439/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1440/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001441/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1442/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001443/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001444/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1445/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001446///
1447/// [C++] for-init-statement:
1448/// [C++] expression-statement
1449/// [C++] simple-declaration
1450///
Richard Smithad762fc2011-04-14 22:09:26 +00001451/// [C++0x] for-range-declaration:
1452/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1453/// [C++0x] for-range-initializer:
1454/// [C++0x] expression
1455/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001456StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001457 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001459
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001460 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001461 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001462 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001463 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001465
Chad Rosierb6604462012-07-10 21:35:27 +00001466 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1467 getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001468
Chris Lattner22153252007-08-26 23:08:06 +00001469 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1470 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001471 //
1472 // C++ 6.4p3:
1473 // A name introduced by a declaration in a condition is in scope from its
1474 // point of declaration until the end of the substatements controlled by the
1475 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001476 // C++ 3.3.2p4:
1477 // Names declared in the for-init-statement, and in the condition of if,
1478 // while, for, and switch statements are local to the if, while, for, or
1479 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001480 // C++ 6.5.3p1:
1481 // Names declared in the for-init-statement are in the same declarative-region
1482 // as those declared in the condition.
1483 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001484 unsigned ScopeFlags = 0;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001485 if (C99orCXXorObjC)
Stephen Hines651f13c2014-04-23 16:59:28 -07001486 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001487
1488 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001489
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001490 BalancedDelimiterTracker T(*this, tok::l_paren);
1491 T.consumeOpen();
1492
John McCall60d7b3a2010-08-24 06:29:42 +00001493 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001494
Richard Smithad762fc2011-04-14 22:09:26 +00001495 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001496 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001497 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001498 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001499 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001500 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001501 FullExprArg ThirdPart(Actions);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001502 Decl *SecondVar = nullptr;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001503
Douglas Gregor791215b2009-09-21 20:51:25 +00001504 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001505 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001506 C99orCXXorObjC? Sema::PCC_ForInit
1507 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001508 cutOffParsing();
1509 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001510 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001511
Sean Hunt2edf0a22012-06-23 05:07:58 +00001512 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001513 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001516 if (Tok.is(tok::semi)) { // for (;
Sean Hunt2edf0a22012-06-23 05:07:58 +00001517 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 // no first part, eat the ';'.
1519 ConsumeToken();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001520 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1521 isForRangeIdentifier()) {
1522 ProhibitAttributes(attrs);
1523 IdentifierInfo *Name = Tok.getIdentifierInfo();
1524 SourceLocation Loc = ConsumeToken();
1525 MaybeParseCXX11Attributes(attrs);
1526
1527 ForRangeInit.ColonLoc = ConsumeToken();
1528 if (Tok.is(tok::l_brace))
1529 ForRangeInit.RangeExpr = ParseBraceInitializer();
1530 else
1531 ForRangeInit.RangeExpr = ParseExpression();
1532
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001533 Diag(Loc, diag::err_for_range_identifier)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001534 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1535 ? FixItHint::CreateInsertion(Loc, "auto &&")
1536 : FixItHint());
1537
1538 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1539 attrs, attrs.Range.getEnd());
1540 ForRange = true;
Eli Friedman9490ab42011-12-20 01:50:37 +00001541 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001543 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001545
Richard Smithad762fc2011-04-14 22:09:26 +00001546 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001547 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001548 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1549
Chris Lattner97144fc2009-04-02 04:16:50 +00001550 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001551 DeclGroupPtrTy DG = ParseSimpleDeclaration(
Stephen Hines176edba2014-12-01 14:53:08 -08001552 Declarator::ForContext, DeclEnd, attrs, false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001553 MightBeForRangeStmt ? &ForRangeInit : nullptr);
Chris Lattnercd147752009-03-29 17:27:48 +00001554 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Richard Smithad762fc2011-04-14 22:09:26 +00001555 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001556 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001557 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001558
Richard Smithad762fc2011-04-14 22:09:26 +00001559 ForRange = true;
1560 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001561 ConsumeToken();
1562 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001563 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001564 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001565 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001566
Douglas Gregorfb629412010-08-23 21:17:50 +00001567 if (Tok.is(tok::code_completion)) {
1568 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001569 cutOffParsing();
1570 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001571 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001572 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001573 } else {
1574 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001575 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 } else {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001577 ProhibitAttributes(attrs);
Stephen Hines176edba2014-12-01 14:53:08 -08001578 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Reid Spencer5f016e22007-07-11 17:01:13 +00001579
John McCallf6a16482010-12-04 03:47:34 +00001580 ForEach = isTokIdentifier_in();
1581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001583 if (!Value.isInvalid()) {
1584 if (ForEach)
1585 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1586 else
Richard Smith41956372013-01-14 22:39:08 +00001587 FirstPart = Actions.ActOnExprStmt(Value);
John McCallf6a16482010-12-04 03:47:34 +00001588 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001589
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001590 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001592 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001593 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001594
Douglas Gregorfb629412010-08-23 21:17:50 +00001595 if (Tok.is(tok::code_completion)) {
1596 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001597 cutOffParsing();
1598 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001599 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001600 Collection = ParseExpression();
Richard Smith80ad52f2013-01-02 11:42:31 +00001601 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001602 // User tried to write the reasonable, but ill-formed, for-range-statement
1603 // for (expr : expr) { ... }
1604 Diag(Tok, diag::err_for_range_expected_decl)
1605 << FirstPart.get()->getSourceRange();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001606 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smitha44854a2011-12-20 22:56:20 +00001607 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001608 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001609 if (!Value.isInvalid()) {
1610 Diag(Tok, diag::err_expected_semi_for);
1611 } else {
1612 // Skip until semicolon or rparen, don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001613 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregorb72c7782011-02-17 03:38:46 +00001614 if (Tok.is(tok::semi))
1615 ConsumeToken();
1616 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 }
1618 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001619
1620 // Parse the second part of the for specifier.
1621 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smithad762fc2011-04-14 22:09:26 +00001622 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001623 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001624 // Parse the second part of the for specifier.
1625 if (Tok.is(tok::semi)) { // for (...;;
1626 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001627 } else if (Tok.is(tok::r_paren)) {
1628 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001629 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001630 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001631 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001632 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1633 else {
1634 Second = ParseExpression();
1635 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001636 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001637 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001638 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001639 SecondPartIsInvalid = Second.isInvalid();
David Blaikiedef07622012-05-16 04:20:04 +00001640 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001641 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001642
Douglas Gregorb72c7782011-02-17 03:38:46 +00001643 if (Tok.isNot(tok::semi)) {
1644 if (!SecondPartIsInvalid || SecondVar)
1645 Diag(Tok, diag::err_expected_semi_for);
1646 else
1647 // Skip until semicolon or rparen, don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001648 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregorb72c7782011-02-17 03:38:46 +00001649 }
1650
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001651 if (Tok.is(tok::semi)) {
1652 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001653 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001654
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001655 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001656 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001657 ExprResult Third = ParseExpression();
Richard Smith41956372013-01-14 22:39:08 +00001658 // FIXME: The C++11 standard doesn't actually say that this is a
1659 // discarded-value expression, but it clearly should be.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001660 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001661 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001664 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001665
Richard Smithad762fc2011-04-14 22:09:26 +00001666 // We need to perform most of the semantic analysis for a C++0x for-range
1667 // statememt before parsing the body, in order to be able to deduce the type
1668 // of an auto-typed loop variable.
1669 StmtResult ForRangeStmt;
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001670 StmtResult ForEachStmt;
Chad Rosierb6604462012-07-10 21:35:27 +00001671
John McCall990567c2011-07-27 01:07:15 +00001672 if (ForRange) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001673 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001674 ForRangeInit.ColonLoc,
1675 ForRangeInit.RangeExpr.get(),
Richard Smith8b533d92012-09-20 21:52:32 +00001676 T.getCloseLocation(),
1677 Sema::BFRK_Build);
Richard Smithad762fc2011-04-14 22:09:26 +00001678
John McCall990567c2011-07-27 01:07:15 +00001679
1680 // Similarly, we need to do the semantic analysis for a for-range
1681 // statement immediately in order to close over temporaries correctly.
1682 } else if (ForEach) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001683 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001684 FirstPart.get(),
1685 Collection.get(),
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001686 T.getCloseLocation());
John McCall990567c2011-07-27 01:07:15 +00001687 }
1688
Stephen Hines651f13c2014-04-23 16:59:28 -07001689 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001690 // there is no compound stmt. C90 does not have this clause. We only do this
1691 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001692 //
1693 // C++ 6.5p2:
1694 // The substatement in an iteration-statement implicitly defines a local scope
1695 // which is entered and exited each time through the loop.
1696 //
1697 // See comments in ParseIfStatement for why we create a scope for
1698 // for-init-statement/condition and a new scope for substatement in C++.
1699 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001700 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1701 Tok.is(tok::l_brace));
1702
1703 // The body of the for loop has the same local mangling number as the
1704 // for-init-statement.
1705 // It will only be incremented if the body contains other things that would
1706 // normally increment the mangling number (like a compound statement).
1707 if (C99orCXXorObjC)
1708 getCurScope()->decrementMSLocalManglingNumber();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001709
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001711 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001712
Chris Lattner0ecea032007-08-22 05:28:50 +00001713 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001714 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001715
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001717 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001718
1719 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001720 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001721
Richard Smithad762fc2011-04-14 22:09:26 +00001722 if (ForEach)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001723 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1724 Body.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Richard Smithad762fc2011-04-14 22:09:26 +00001726 if (ForRange)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001727 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001728
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001729 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001730 SecondPart, SecondVar, ThirdPart,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001731 T.getCloseLocation(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001732}
1733
1734/// ParseGotoStatement
1735/// jump-statement:
1736/// 'goto' identifier ';'
1737/// [GNU] 'goto' '*' expression ';'
1738///
1739/// Note: this lets the caller parse the end ';'.
1740///
Richard Smith534986f2012-04-14 00:33:13 +00001741StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001742 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001744
John McCall60d7b3a2010-08-24 06:29:42 +00001745 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001746 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001747 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1748 Tok.getLocation());
1749 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001751 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 // GNU indirect goto extension.
1753 Diag(Tok, diag::ext_gnu_indirect_goto);
1754 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001755 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001756 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001757 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001758 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001760 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
Chris Lattner95cfb852007-07-22 04:13:33 +00001761 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07001762 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redl9a920342008-12-11 19:48:14 +00001763 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001765
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001766 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +00001767}
1768
1769/// ParseContinueStatement
1770/// jump-statement:
1771/// 'continue' ';'
1772///
1773/// Note: this lets the caller parse the end ';'.
1774///
Richard Smith534986f2012-04-14 00:33:13 +00001775StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001777 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001778}
1779
1780/// ParseBreakStatement
1781/// jump-statement:
1782/// 'break' ';'
1783///
1784/// Note: this lets the caller parse the end ';'.
1785///
Richard Smith534986f2012-04-14 00:33:13 +00001786StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001788 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001789}
1790
1791/// ParseReturnStatement
1792/// jump-statement:
1793/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001794StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001795 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001797
John McCall60d7b3a2010-08-24 06:29:42 +00001798 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001799 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001800 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001801 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001802 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001803 return StmtError();
1804 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001805
David Blaikie4e4d0842012-03-11 07:00:24 +00001806 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001807 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001808 if (R.isUsable())
Richard Smith80ad52f2013-01-02 11:42:31 +00001809 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001810 diag::warn_cxx98_compat_generalized_initializer_lists :
1811 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001812 << R.get()->getSourceRange();
1813 } else
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001814 R = ParseExpression();
Stephen Hines651f13c2014-04-23 16:59:28 -07001815 if (R.isInvalid()) {
1816 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001817 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 }
1819 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001820 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001821}
1822
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001823StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts, bool OnlyStatement,
1824 SourceLocation *TrailingElseLoc,
1825 ParsedAttributesWithRange &Attrs) {
1826 // Create temporary attribute list.
1827 ParsedAttributesWithRange TempAttrs(AttrFactory);
John McCallaeeacf72013-05-03 00:10:13 +00001828
Stephen Hines176edba2014-12-01 14:53:08 -08001829 // Get loop hints and consume annotated token.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001830 while (Tok.is(tok::annot_pragma_loop_hint)) {
Stephen Hines176edba2014-12-01 14:53:08 -08001831 LoopHint Hint;
1832 if (!HandlePragmaLoopHint(Hint))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001833 continue;
1834
Stephen Hines176edba2014-12-01 14:53:08 -08001835 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001836 ArgsUnion(Hint.ValueExpr)};
Stephen Hines176edba2014-12-01 14:53:08 -08001837 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1838 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1839 AttributeList::AS_Pragma);
Chris Lattner64cb4752009-12-20 23:00:41 +00001840 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001841
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001842 // Get the next statement.
1843 MaybeParseCXX11Attributes(Attrs);
Chris Lattner64cb4752009-12-20 23:00:41 +00001844
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001845 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1846 Stmts, OnlyStatement, TrailingElseLoc, Attrs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001847
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001848 Attrs.takeAllFrom(TempAttrs);
1849 return S;
Reid Spencer5f016e22007-07-11 17:01:13 +00001850}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001851
Douglas Gregorc9977d02011-03-16 17:05:57 +00001852Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00001853 assert(Tok.is(tok::l_brace));
1854 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001855
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00001856 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1a5bd5d2012-11-19 21:13:18 +00001857 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001858 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00001859 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001860 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001861
John McCallf312b1e2010-08-26 23:41:50 +00001862 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1863 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001865 // Do not enter a scope for the brace, as the arguments are in the same scope
1866 // (the function body) as the body itself. Instead, just read the statement
1867 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00001868 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00001869
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001870 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001871 if (FnBody.isInvalid()) {
1872 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00001873 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001874 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001875
Douglas Gregorc9977d02011-03-16 17:05:57 +00001876 BodyScope.Exit();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001877 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00001878}
Sebastian Redla0fd8652008-12-21 16:41:36 +00001879
Sebastian Redld3a413d2009-04-26 20:35:05 +00001880/// ParseFunctionTryBlock - Parse a C++ function-try-block.
1881///
1882/// function-try-block:
1883/// 'try' ctor-initializer[opt] compound-statement handler-seq
1884///
Douglas Gregorc9977d02011-03-16 17:05:57 +00001885Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00001886 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1887 SourceLocation TryLoc = ConsumeToken();
1888
John McCallf312b1e2010-08-26 23:41:50 +00001889 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1890 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00001891
1892 // Constructor initializer list?
1893 if (Tok.is(tok::colon))
1894 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00001895 else
1896 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001897
Richard Smith1a5bd5d2012-11-19 21:13:18 +00001898 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
1899 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001900 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00001901 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001902 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001903
Sebastian Redlde1b60a2009-04-26 21:08:36 +00001904 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikiec4027c82012-11-10 01:04:23 +00001905 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redld3a413d2009-04-26 20:35:05 +00001906 // If we failed to parse the try-catch, we just give the function an empty
1907 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001908 if (FnBody.isInvalid()) {
1909 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00001910 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001911 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00001912
Douglas Gregorc9977d02011-03-16 17:05:57 +00001913 BodyScope.Exit();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001914 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Sebastian Redld3a413d2009-04-26 20:35:05 +00001915}
1916
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001917bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001918 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001919 assert(SkipFunctionBodies &&
1920 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001921
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00001922 if (!PP.isCodeCompletionEnabled()) {
1923 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001924 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00001925 return true;
1926 }
1927
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001928 // We're in code-completion mode. Skip parsing for all function bodies unless
1929 // the body contains the code-completion point.
1930 TentativeParsingAction PA(*this);
1931 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001932 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001933 PA.Commit();
1934 return true;
1935 }
1936
1937 PA.Revert();
1938 return false;
1939}
1940
Sebastian Redla0fd8652008-12-21 16:41:36 +00001941/// ParseCXXTryBlock - Parse a C++ try-block.
1942///
1943/// try-block:
1944/// 'try' compound-statement handler-seq
1945///
Richard Smith534986f2012-04-14 00:33:13 +00001946StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00001947 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1948
1949 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001950 return ParseCXXTryBlockCommon(TryLoc);
1951}
1952
1953/// ParseCXXTryBlockCommon - Parse the common part of try-block and
1954/// function-try-block.
1955///
1956/// try-block:
1957/// 'try' compound-statement handler-seq
1958///
1959/// function-try-block:
1960/// 'try' ctor-initializer[opt] compound-statement handler-seq
1961///
1962/// handler-seq:
1963/// handler handler-seq[opt]
1964///
John Wiegley28bbe4b2011-04-28 01:08:34 +00001965/// [Borland] try-block:
1966/// 'try' compound-statement seh-except-block
Stephen Hines651f13c2014-04-23 16:59:28 -07001967/// 'try' compound-statement seh-finally-block
John Wiegley28bbe4b2011-04-28 01:08:34 +00001968///
David Blaikiec4027c82012-11-10 01:04:23 +00001969StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00001970 if (Tok.isNot(tok::l_brace))
Stephen Hines651f13c2014-04-23 16:59:28 -07001971 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Richard Smith534986f2012-04-14 00:33:13 +00001972
1973 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikiee5afdcf2012-11-13 18:51:45 +00001974 Scope::DeclScope | Scope::TryScope |
1975 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redla0fd8652008-12-21 16:41:36 +00001976 if (TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001977 return TryBlock;
Sebastian Redla0fd8652008-12-21 16:41:36 +00001978
John Wiegley28bbe4b2011-04-28 01:08:34 +00001979 // Borland allows SEH-handlers with 'try'
Chad Rosierb6604462012-07-10 21:35:27 +00001980
Richard Smith534986f2012-04-14 00:33:13 +00001981 if ((Tok.is(tok::identifier) &&
1982 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
1983 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00001984 // TODO: Factor into common return ParseSEHHandlerCommon(...)
1985 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00001986 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00001987 SourceLocation Loc = ConsumeToken();
1988 Handler = ParseSEHExceptBlock(Loc);
1989 }
1990 else {
1991 SourceLocation Loc = ConsumeToken();
1992 Handler = ParseSEHFinallyBlock(Loc);
1993 }
1994 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001995 return Handler;
John McCall7f040a92010-12-24 02:08:15 +00001996
John Wiegley28bbe4b2011-04-28 01:08:34 +00001997 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
1998 TryLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001999 TryBlock.get(),
2000 Handler.get());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002001 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00002002 else {
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002003 StmtVector Handlers;
Richard Smith5eed7e02013-10-15 01:34:54 +00002004
2005 // C++11 attributes can't appear here, despite this context seeming
2006 // statement-like.
2007 DiagnoseAndSkipCXX11Attributes();
Sebastian Redla0fd8652008-12-21 16:41:36 +00002008
John Wiegley28bbe4b2011-04-28 01:08:34 +00002009 if (Tok.isNot(tok::kw_catch))
2010 return StmtError(Diag(Tok, diag::err_expected_catch));
2011 while (Tok.is(tok::kw_catch)) {
David Blaikiec4027c82012-11-10 01:04:23 +00002012 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley28bbe4b2011-04-28 01:08:34 +00002013 if (!Handler.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002014 Handlers.push_back(Handler.get());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002015 }
2016 // Don't bother creating the full statement if we don't have any usable
2017 // handlers.
2018 if (Handlers.empty())
2019 return StmtError();
2020
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002021 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002022 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002023}
2024
2025/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2026///
Richard Smith4cd81c52013-01-29 09:02:09 +00002027/// handler:
2028/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +00002029///
Richard Smith4cd81c52013-01-29 09:02:09 +00002030/// exception-declaration:
2031/// attribute-specifier-seq[opt] type-specifier-seq declarator
2032/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2033/// '...'
Sebastian Redla0fd8652008-12-21 16:41:36 +00002034///
David Blaikiec4027c82012-11-10 01:04:23 +00002035StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002036 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2037
2038 SourceLocation CatchLoc = ConsumeToken();
2039
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002040 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002041 if (T.expectAndConsume())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002042 return StmtError();
2043
2044 // C++ 3.3.2p3:
2045 // The name in a catch exception-declaration is local to the handler and
2046 // shall not be redeclared in the outermost block of the handler.
David Blaikiec4027c82012-11-10 01:04:23 +00002047 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikiee5afdcf2012-11-13 18:51:45 +00002048 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002049
2050 // exception-declaration is equivalent to '...' or a parameter-declaration
2051 // without default arguments.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002052 Decl *ExceptionDecl = nullptr;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002053 if (Tok.isNot(tok::ellipsis)) {
Richard Smith4cd81c52013-01-29 09:02:09 +00002054 ParsedAttributesWithRange Attributes(AttrFactory);
2055 MaybeParseCXX11Attributes(Attributes);
2056
John McCall0b7e6782011-03-24 11:26:52 +00002057 DeclSpec DS(AttrFactory);
Richard Smith4cd81c52013-01-29 09:02:09 +00002058 DS.takeAttributesFrom(Attributes);
2059
Sebastian Redl4b07b292008-12-22 19:15:10 +00002060 if (ParseCXXTypeSpecifierSeq(DS))
2061 return StmtError();
Richard Smith4cd81c52013-01-29 09:02:09 +00002062
Sebastian Redla0fd8652008-12-21 16:41:36 +00002063 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2064 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002065 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002066 } else
2067 ConsumeToken();
2068
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002069 T.consumeClose();
2070 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002071 return StmtError();
2072
2073 if (Tok.isNot(tok::l_brace))
Stephen Hines651f13c2014-04-23 16:59:28 -07002074 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002075
Sean Huntbbd37c62009-11-21 08:43:09 +00002076 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002077 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002078 if (Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002079 return Block;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002080
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002081 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002082}
Francois Pichet1e862692011-05-06 20:48:22 +00002083
2084void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002085 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002086 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002087 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002088
Douglas Gregor3896fc52011-10-24 22:31:10 +00002089 // Handle dependent statements by parsing the braces as a compound statement.
2090 // This is not the same behavior as Visual C++, which don't treat this as a
2091 // compound statement, but for Clang's type checking we can't have anything
2092 // inside these braces escaping to the surrounding code.
2093 if (Result.Behavior == IEB_Dependent) {
2094 if (!Tok.is(tok::l_brace)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002095 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smith534986f2012-04-14 00:33:13 +00002096 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002097 }
Richard Smith534986f2012-04-14 00:33:13 +00002098
2099 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002100 if (Compound.isInvalid())
2101 return;
Richard Smith534986f2012-04-14 00:33:13 +00002102
Douglas Gregorba0513d2011-10-25 01:33:02 +00002103 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2104 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002105 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002106 Result.Name,
2107 Compound.get());
2108 if (DepResult.isUsable())
2109 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002110 return;
2111 }
Richard Smith534986f2012-04-14 00:33:13 +00002112
Douglas Gregor3896fc52011-10-24 22:31:10 +00002113 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2114 if (Braces.consumeOpen()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002115 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet1e862692011-05-06 20:48:22 +00002116 return;
2117 }
Francois Pichet1e862692011-05-06 20:48:22 +00002118
Douglas Gregor3896fc52011-10-24 22:31:10 +00002119 switch (Result.Behavior) {
2120 case IEB_Parse:
2121 // Parse the statements below.
2122 break;
Chad Rosierb6604462012-07-10 21:35:27 +00002123
Douglas Gregor3896fc52011-10-24 22:31:10 +00002124 case IEB_Dependent:
2125 llvm_unreachable("Dependent case handled above");
Chad Rosierb6604462012-07-10 21:35:27 +00002126
Douglas Gregor3896fc52011-10-24 22:31:10 +00002127 case IEB_Skip:
2128 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002129 return;
2130 }
2131
2132 // Condition is true, parse the statements.
2133 while (Tok.isNot(tok::r_brace)) {
2134 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2135 if (R.isUsable())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002136 Stmts.push_back(R.get());
Francois Pichet1e862692011-05-06 20:48:22 +00002137 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002138 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002139}