blob: d29da837c09587da5365cfbc9dd63455b993011d [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.
Kaelyn Uhrain6243f622013-09-27 19:40:12 +0000188 StatementFilterCCC Validator(Next);
189 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
Richard Smith05766812012-08-18 00:55:03 +0000190 == 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;
Ted Kremenek8113ecf2010-11-10 05:59:39 +0000210 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, 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);
Alexey Bataev4fa7eab2013-07-19 03:13:43 +0000348 return ParseOpenMPDeclarativeOrExecutableDirective();
349
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
Richard Smith534986f2012-04-14 00:33:13 +0000411StmtResult Parser::ParseSEHTryBlock() {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000412 assert(Tok.is(tok::kw___try) && "Expected '__try'");
413 SourceLocation Loc = ConsumeToken();
414 return ParseSEHTryBlockCommon(Loc);
415}
416
417/// ParseSEHTryBlockCommon
418///
419/// seh-try-block:
420/// '__try' compound-statement seh-handler
421///
422/// seh-handler:
423/// seh-except-block
424/// seh-finally-block
425///
426StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
427 if(Tok.isNot(tok::l_brace))
Stephen Hines651f13c2014-04-23 16:59:28 -0700428 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley28bbe4b2011-04-28 01:08:34 +0000429
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700430 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
431 Scope::DeclScope | Scope::SEHTryScope));
John Wiegley28bbe4b2011-04-28 01:08:34 +0000432 if(TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000433 return TryBlock;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000434
435 StmtResult Handler;
Richard Smith534986f2012-04-14 00:33:13 +0000436 if (Tok.is(tok::identifier) &&
Douglas Gregorb57791e2011-10-21 03:57:52 +0000437 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000438 SourceLocation Loc = ConsumeToken();
439 Handler = ParseSEHExceptBlock(Loc);
440 } else if (Tok.is(tok::kw___finally)) {
441 SourceLocation Loc = ConsumeToken();
442 Handler = ParseSEHFinallyBlock(Loc);
443 } else {
444 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
445 }
446
447 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000448 return Handler;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000449
450 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
451 TryLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700452 TryBlock.get(),
453 Handler.get());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000454}
455
456/// ParseSEHExceptBlock - Handle __except
457///
458/// seh-except-block:
459/// '__except' '(' seh-filter-expression ')' compound-statement
460///
461StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
462 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
463 raii2(Ident___exception_code, false),
464 raii3(Ident_GetExceptionCode, false);
465
Stephen Hines651f13c2014-04-23 16:59:28 -0700466 if (ExpectAndConsume(tok::l_paren))
John Wiegley28bbe4b2011-04-28 01:08:34 +0000467 return StmtError();
468
469 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
470
David Blaikie4e4d0842012-03-11 07:00:24 +0000471 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000472 Ident__exception_info->setIsPoisoned(false);
473 Ident___exception_info->setIsPoisoned(false);
474 Ident_GetExceptionInfo->setIsPoisoned(false);
475 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000476 ExprResult FilterExpr(ParseExpression());
Francois Pichetd7f02df2011-04-28 03:14:31 +0000477
David Blaikie4e4d0842012-03-11 07:00:24 +0000478 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000479 Ident__exception_info->setIsPoisoned(true);
480 Ident___exception_info->setIsPoisoned(true);
481 Ident_GetExceptionInfo->setIsPoisoned(true);
482 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000483
484 if(FilterExpr.isInvalid())
485 return StmtError();
486
Stephen Hines651f13c2014-04-23 16:59:28 -0700487 if (ExpectAndConsume(tok::r_paren))
John Wiegley28bbe4b2011-04-28 01:08:34 +0000488 return StmtError();
489
Richard Smith534986f2012-04-14 00:33:13 +0000490 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000491
492 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000493 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000494
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700495 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000496}
497
498/// ParseSEHFinallyBlock - Handle __finally
499///
500/// seh-finally-block:
501/// '__finally' compound-statement
502///
503StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
504 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
505 raii2(Ident___abnormal_termination, false),
506 raii3(Ident_AbnormalTermination, false);
507
Richard Smith534986f2012-04-14 00:33:13 +0000508 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000509 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000510 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000511
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700512 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.get());
513}
514
515/// Handle __leave
516///
517/// seh-leave-statement:
518/// '__leave' ';'
519///
520StmtResult Parser::ParseSEHLeaveStatement() {
521 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
522 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000523}
524
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000525/// ParseLabeledStatement - We have an identifier and a ':' after it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000526///
527/// labeled-statement:
528/// identifier ':' statement
529/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000530///
Richard Smith534986f2012-04-14 00:33:13 +0000531StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000532 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
533 "Not an identifier!");
534
535 Token IdentTok = Tok; // Save the whole token.
536 ConsumeToken(); // eat the identifier.
537
538 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000539
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000540 // identifier ':' statement
541 SourceLocation ColonLoc = ConsumeToken();
542
Richard Smith93982a72013-11-15 22:45:29 +0000543 // Read label attributes, if present.
544 StmtResult SubStmt;
545 if (Tok.is(tok::kw___attribute)) {
546 ParsedAttributesWithRange TempAttrs(AttrFactory);
547 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000548
Richard Smith93982a72013-11-15 22:45:29 +0000549 // In C++, GNU attributes only apply to the label if they are followed by a
550 // semicolon, to disambiguate label attributes from attributes on a labeled
551 // declaration.
552 //
553 // This doesn't quite match what GCC does; if the attribute list is empty
554 // and followed by a semicolon, GCC will reject (it appears to parse the
555 // attributes as part of a statement in that case). That looks like a bug.
556 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
557 attrs.takeAllFrom(TempAttrs);
558 else if (isDeclarationStatement()) {
559 StmtVector Stmts;
560 // FIXME: We should do this whether or not we have a declaration
561 // statement, but that doesn't work correctly (because ProhibitAttributes
562 // can't handle GNU attributes), so only call it in the one case where
563 // GNU attributes are allowed.
564 SubStmt = ParseStatementOrDeclarationAfterAttributes(
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700565 Stmts, /*OnlyStmts*/ true, nullptr, TempAttrs);
Richard Smith93982a72013-11-15 22:45:29 +0000566 if (!TempAttrs.empty() && !SubStmt.isInvalid())
567 SubStmt = Actions.ProcessStmtAttributes(
568 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
569 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -0700570 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smith93982a72013-11-15 22:45:29 +0000571 }
572 }
573
574 // If we've not parsed a statement yet, parse one now.
575 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
576 SubStmt = ParseStatement();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000577
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000578 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000579 if (SubStmt.isInvalid())
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000580 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000581
Chris Lattner337e5502011-02-18 01:27:55 +0000582 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
583 IdentTok.getLocation());
Richard Smith534986f2012-04-14 00:33:13 +0000584 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattner337e5502011-02-18 01:27:55 +0000585 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smith534986f2012-04-14 00:33:13 +0000586 attrs.clear();
587 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000588
Chris Lattner337e5502011-02-18 01:27:55 +0000589 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
590 SubStmt.get());
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000591}
Reid Spencer5f016e22007-07-11 17:01:13 +0000592
593/// ParseCaseStatement
594/// labeled-statement:
595/// 'case' constant-expression ':' statement
596/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
597///
Richard Smith534986f2012-04-14 00:33:13 +0000598StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smith46f11102011-04-21 22:48:40 +0000599 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattner24e1e702009-03-04 04:23:07 +0000601 // It is very very common for code to contain many case statements recursively
602 // nested, as in (but usually without indentation):
603 // case 1:
604 // case 2:
605 // case 3:
606 // case 4:
607 // case 5: etc.
608 //
609 // Parsing this naively works, but is both inefficient and can cause us to run
610 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner26140c62009-03-04 18:24:58 +0000611 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner24e1e702009-03-04 04:23:07 +0000612 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smith93982a72013-11-15 22:45:29 +0000613 // weirdness in the actions), so this is just local grossness :).
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattner24e1e702009-03-04 04:23:07 +0000615 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
616 // example above.
John McCall60d7b3a2010-08-24 06:29:42 +0000617 StmtResult TopLevelCase(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattner24e1e702009-03-04 04:23:07 +0000619 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
620 // gets updated each time a new case is parsed, and whose body is unset so
621 // far. When parsing 'case 4', this is the 'case 3' node.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700622 Stmt *DeepestParsedCaseStmt = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattner24e1e702009-03-04 04:23:07 +0000624 // While we have case statements, eat and stack them.
David Majnemer0e1e69c2011-06-13 05:50:12 +0000625 SourceLocation ColonLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000626 do {
Richard Trieubb9b80c2011-04-21 21:44:26 +0000627 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
628 ConsumeToken(); // eat the 'case'.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700629 ColonLoc = SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000631 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000632 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000633 cutOffParsing();
634 return StmtError();
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000635 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000636
Chris Lattner6fb09c82009-12-10 00:38:54 +0000637 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
638 /// Disable this form of error recovery while we're parsing the case
639 /// expression.
640 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000641
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700642 ExprResult LHS;
643 if (!MissingCase) {
644 LHS = ParseConstantExpression();
645 if (LHS.isInvalid()) {
646 // If constant-expression is parsed unsuccessfully, recover by skipping
647 // current case statement (moving to the colon that ends it).
648 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
649 TryConsumeToken(tok::colon, ColonLoc);
650 continue;
651 }
652 return StmtError();
653 }
654 } else {
655 LHS = Expr;
656 MissingCase = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000658
Chris Lattner24e1e702009-03-04 04:23:07 +0000659 // GNU case range extension.
660 SourceLocation DotDotDotLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000661 ExprResult RHS;
Stephen Hines651f13c2014-04-23 16:59:28 -0700662 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
663 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Chris Lattner24e1e702009-03-04 04:23:07 +0000664 RHS = ParseConstantExpression();
665 if (RHS.isInvalid()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700666 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
667 TryConsumeToken(tok::colon, ColonLoc);
668 continue;
669 }
Chris Lattner24e1e702009-03-04 04:23:07 +0000670 return StmtError();
671 }
672 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000673
Chris Lattner6fb09c82009-12-10 00:38:54 +0000674 ColonProtection.restore();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000675
Stephen Hines651f13c2014-04-23 16:59:28 -0700676 if (TryConsumeToken(tok::colon, ColonLoc)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700677 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
678 TryConsumeToken(tok::coloncolon, ColonLoc)) {
679 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Stephen Hines651f13c2014-04-23 16:59:28 -0700680 Diag(ColonLoc, diag::err_expected_after)
681 << "'case'" << tok::colon
682 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCallf6a3ab02011-01-22 09:28:32 +0000683 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000684 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Stephen Hines651f13c2014-04-23 16:59:28 -0700685 Diag(ExpectedLoc, diag::err_expected_after)
686 << "'case'" << tok::colon
687 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor662a4822010-12-23 22:56:40 +0000688 ColonLoc = ExpectedLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000689 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000690
John McCall60d7b3a2010-08-24 06:29:42 +0000691 StmtResult Case =
John McCall9ae2f072010-08-23 23:25:46 +0000692 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
693 RHS.get(), ColonLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner24e1e702009-03-04 04:23:07 +0000695 // If we had a sema error parsing this case, then just ignore it and
696 // continue parsing the sub-stmt.
697 if (Case.isInvalid()) {
698 if (TopLevelCase.isInvalid()) // No parsed case stmts.
699 return ParseStatement();
700 // Otherwise, just don't add it as a nested case.
701 } else {
702 // If this is the first case statement we parsed, it becomes TopLevelCase.
703 // Otherwise we link it into the current chain.
John McCallca0408f2010-08-23 06:44:23 +0000704 Stmt *NextDeepest = Case.get();
Chris Lattner24e1e702009-03-04 04:23:07 +0000705 if (TopLevelCase.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000706 TopLevelCase = Case;
Chris Lattner24e1e702009-03-04 04:23:07 +0000707 else
John McCall9ae2f072010-08-23 23:25:46 +0000708 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner24e1e702009-03-04 04:23:07 +0000709 DeepestParsedCaseStmt = NextDeepest;
710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattner24e1e702009-03-04 04:23:07 +0000712 // Handle all case statements.
713 } while (Tok.is(tok::kw_case));
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattner24e1e702009-03-04 04:23:07 +0000715 // If we found a non-case statement, start by parsing it.
John McCall60d7b3a2010-08-24 06:29:42 +0000716 StmtResult SubStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattner24e1e702009-03-04 04:23:07 +0000718 if (Tok.isNot(tok::r_brace)) {
719 SubStmt = ParseStatement();
720 } else {
721 // Nicely diagnose the common error "switch (X) { case 4: }", which is
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700722 // not valid. If ColonLoc doesn't point to a valid text location, there was
723 // another parsing error, so avoid producing extra diagnostics.
724 if (ColonLoc.isValid()) {
725 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
726 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
727 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
728 }
729 SubStmt = StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 }
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattner24e1e702009-03-04 04:23:07 +0000732 // Install the body into the most deeply-nested case.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700733 if (DeepestParsedCaseStmt) {
734 // Broken sub-stmt shouldn't prevent forming the case statement properly.
735 if (SubStmt.isInvalid())
736 SubStmt = Actions.ActOnNullStmt(SourceLocation());
737 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
738 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000739
Chris Lattner24e1e702009-03-04 04:23:07 +0000740 // Return the top level parsed statement tree.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000741 return TopLevelCase;
Reid Spencer5f016e22007-07-11 17:01:13 +0000742}
743
744/// ParseDefaultStatement
745/// labeled-statement:
746/// 'default' ':' statement
747/// Note that this does not parse the 'statement' at the end.
748///
Richard Smith534986f2012-04-14 00:33:13 +0000749StmtResult Parser::ParseDefaultStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000750 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
752
Douglas Gregor662a4822010-12-23 22:56:40 +0000753 SourceLocation ColonLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -0700754 if (TryConsumeToken(tok::colon, ColonLoc)) {
755 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
756 // Treat "default;" as a typo for "default:".
757 Diag(ColonLoc, diag::err_expected_after)
758 << "'default'" << tok::colon
759 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCallf6a3ab02011-01-22 09:28:32 +0000760 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000761 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Stephen Hines651f13c2014-04-23 16:59:28 -0700762 Diag(ExpectedLoc, diag::err_expected_after)
763 << "'default'" << tok::colon
764 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor662a4822010-12-23 22:56:40 +0000765 ColonLoc = ExpectedLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +0000766 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000767
Richard Smith85b29a42012-02-17 01:35:32 +0000768 StmtResult SubStmt;
769
770 if (Tok.isNot(tok::r_brace)) {
771 SubStmt = ParseStatement();
772 } else {
773 // Diagnose the common error "switch (X) {... default: }", which is
774 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000775 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000776 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
777 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
778 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 }
780
Richard Smith85b29a42012-02-17 01:35:32 +0000781 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000782 if (SubStmt.isInvalid())
Richard Smith85b29a42012-02-17 01:35:32 +0000783 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000784
Sebastian Redl117054a2008-12-28 16:13:43 +0000785 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000786 SubStmt.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +0000787}
788
Richard Smith534986f2012-04-14 00:33:13 +0000789StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
790 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregorbca01b42011-07-06 22:04:06 +0000791}
Reid Spencer5f016e22007-07-11 17:01:13 +0000792
793/// ParseCompoundStatement - Parse a "{}" block.
794///
795/// compound-statement: [C99 6.8.2]
796/// { block-item-list[opt] }
797/// [GNU] { label-declarations block-item-list } [TODO]
798///
799/// block-item-list:
800/// block-item
801/// block-item-list block-item
802///
803/// block-item:
804/// declaration
Chris Lattner45a566c2007-08-27 01:01:57 +0000805/// [GNU] '__extension__' declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000806/// statement
807/// [OMP] openmp-directive [TODO]
808///
809/// [GNU] label-declarations:
810/// [GNU] label-declaration
811/// [GNU] label-declarations label-declaration
812///
813/// [GNU] label-declaration:
814/// [GNU] '__label__' identifier-list ';'
815///
816/// [OMP] openmp-directive: [TODO]
817/// [OMP] barrier-directive
818/// [OMP] flush-directive
819///
Richard Smith534986f2012-04-14 00:33:13 +0000820StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000821 unsigned ScopeFlags) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000822 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000823
Chris Lattner31e05722007-08-26 06:24:45 +0000824 // Enter a scope to hold everything within the compound stmt. Compound
825 // statements can always hold declarations.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000826 ParseScope CompoundScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000827
828 // Parse the statements in the body.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000829 return ParseCompoundStatementBody(isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000830}
831
Lang Hamesa60d21d2012-11-03 22:29:05 +0000832/// Parse any pragmas at the start of the compound expression. We handle these
833/// separately since some pragmas (FP_CONTRACT) must appear before any C
834/// statement in the compound, but may be intermingled with other pragmas.
835void Parser::ParseCompoundStatementLeadingPragmas() {
836 bool checkForPragmas = true;
837 while (checkForPragmas) {
838 switch (Tok.getKind()) {
839 case tok::annot_pragma_vis:
840 HandlePragmaVisibility();
841 break;
842 case tok::annot_pragma_pack:
843 HandlePragmaPack();
844 break;
845 case tok::annot_pragma_msstruct:
846 HandlePragmaMSStruct();
847 break;
848 case tok::annot_pragma_align:
849 HandlePragmaAlign();
850 break;
851 case tok::annot_pragma_weak:
852 HandlePragmaWeak();
853 break;
854 case tok::annot_pragma_weakalias:
855 HandlePragmaWeakAlias();
856 break;
857 case tok::annot_pragma_redefine_extname:
858 HandlePragmaRedefineExtname();
859 break;
860 case tok::annot_pragma_opencl_extension:
861 HandlePragmaOpenCLExtension();
862 break;
863 case tok::annot_pragma_fp_contract:
864 HandlePragmaFPContract();
865 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700866 case tok::annot_pragma_ms_pointers_to_members:
867 HandlePragmaMSPointersToMembers();
868 break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700869 case tok::annot_pragma_ms_pragma:
870 HandlePragmaMSPragma();
871 break;
Lang Hamesa60d21d2012-11-03 22:29:05 +0000872 default:
873 checkForPragmas = false;
874 break;
875 }
876 }
877
878}
879
Reid Spencer5f016e22007-07-11 17:01:13 +0000880/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff1b273c42007-09-16 14:56:35 +0000881/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Reid Spencer5f016e22007-07-11 17:01:13 +0000882/// consume the '}' at the end of the block. It does not manipulate the scope
883/// stack.
John McCall60d7b3a2010-08-24 06:29:42 +0000884StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump1eb44332009-09-09 15:08:12 +0000885 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerae50fa02009-03-05 00:00:31 +0000886 Tok.getLocation(),
887 "in compound statement ('{}')");
Lang Hamesbe9af122012-10-02 04:45:10 +0000888
889 // Record the state of the FP_CONTRACT pragma, restore on leaving the
890 // compound statement.
891 Sema::FPContractStateRAII SaveFPContractState(Actions);
892
Douglas Gregor0fbda682010-09-15 14:51:05 +0000893 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000894 BalancedDelimiterTracker T(*this, tok::l_brace);
895 if (T.consumeOpen())
896 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000897
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000898 Sema::CompoundScopeRAII CompoundScope(Actions);
899
Lang Hamesa60d21d2012-11-03 22:29:05 +0000900 // Parse any pragmas at the beginning of the compound statement.
901 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000902
Lang Hamesa60d21d2012-11-03 22:29:05 +0000903 StmtVector Stmts;
Lang Hames860022c2012-10-21 01:10:01 +0000904
Chris Lattner4ae493c2011-02-18 02:08:43 +0000905 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
906 // only allowed at the start of a compound stmt regardless of the language.
907 while (Tok.is(tok::kw___label__)) {
908 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000909
Chris Lattner5f9e2722011-07-23 10:55:15 +0000910 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000911 while (1) {
912 if (Tok.isNot(tok::identifier)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700913 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000914 break;
915 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000916
Chris Lattner4ae493c2011-02-18 02:08:43 +0000917 IdentifierInfo *II = Tok.getIdentifierInfo();
918 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara67843042011-03-05 18:21:20 +0000919 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000920
Stephen Hines651f13c2014-04-23 16:59:28 -0700921 if (!TryConsumeToken(tok::comma))
Chris Lattner4ae493c2011-02-18 02:08:43 +0000922 break;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000923 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000924
John McCall0b7e6782011-03-24 11:26:52 +0000925 DeclSpec DS(AttrFactory);
Rafael Espindola4549d7f2013-07-09 12:05:01 +0000926 DeclGroupPtrTy Res =
927 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000928 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000929
Chris Lattner8bb21d32012-04-28 16:12:17 +0000930 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000931 if (R.isUsable())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700932 Stmts.push_back(R.get());
Chris Lattner4ae493c2011-02-18 02:08:43 +0000933 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000934
Stephen Hines651f13c2014-04-23 16:59:28 -0700935 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000936 if (Tok.is(tok::annot_pragma_unused)) {
937 HandlePragmaUnused();
938 continue;
939 }
940
John McCall60d7b3a2010-08-24 06:29:42 +0000941 StmtResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000942 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000943 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattner45a566c2007-08-27 01:01:57 +0000944 } else {
945 // __extension__ can start declarations and it can also be a unary
946 // operator for expressions. Consume multiple __extension__ markers here
947 // until we can determine which is which.
Eli Friedmanadf077f2009-01-27 08:43:38 +0000948 // FIXME: This loses extension expressions in the AST!
Chris Lattner45a566c2007-08-27 01:01:57 +0000949 SourceLocation ExtLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000950 while (Tok.is(tok::kw___extension__))
Chris Lattner45a566c2007-08-27 01:01:57 +0000951 ConsumeToken();
Chris Lattner39146d62008-10-20 06:51:33 +0000952
John McCall0b7e6782011-03-24 11:26:52 +0000953 ParsedAttributesWithRange attrs(AttrFactory);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700954 MaybeParseCXX11Attributes(attrs, nullptr,
955 /*MightBeObjCMessageSend*/ true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000956
Chris Lattner45a566c2007-08-27 01:01:57 +0000957 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis5404a152008-10-05 00:06:24 +0000958 if (isDeclarationStatement()) {
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000959 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner97144fc2009-04-02 04:16:50 +0000960 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000961 ExtensionRAIIObject O(Diags);
962
Chris Lattner97144fc2009-04-02 04:16:50 +0000963 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000964 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
965 Declarator::BlockContext, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000966 attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000967 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattner45a566c2007-08-27 01:01:57 +0000968 } else {
Eli Friedmanadf077f2009-01-27 08:43:38 +0000969 // Otherwise this was a unary __extension__ marker.
John McCall60d7b3a2010-08-24 06:29:42 +0000970 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattner043a0b52008-03-13 06:32:11 +0000971
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000972 if (Res.isInvalid()) {
Chris Lattner45a566c2007-08-27 01:01:57 +0000973 SkipUntil(tok::semi);
974 continue;
975 }
Sebastian Redlf512e822009-01-18 18:03:53 +0000976
Sean Huntbbd37c62009-11-21 08:43:09 +0000977 // FIXME: Use attributes?
Chris Lattner39146d62008-10-20 06:51:33 +0000978 // Eat the semicolon at the end of stmt and convert the expr into a
979 // statement.
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000980 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000981 R = Actions.ActOnExprStmt(Res);
Chris Lattner45a566c2007-08-27 01:01:57 +0000982 }
983 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000984
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000985 if (R.isUsable())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700986 Stmts.push_back(R.get());
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000988
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000989 SourceLocation CloseLoc = Tok.getLocation();
990
Reid Spencer5f016e22007-07-11 17:01:13 +0000991 // We broke out of the while loop because we found a '}' or EOF.
Nico Weberd11f4352012-12-30 23:36:56 +0000992 if (!T.consumeClose())
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000993 // Recover by creating a compound statement with what we parsed so far,
994 // instead of dropping everything and returning StmtError();
Nico Weberd11f4352012-12-30 23:36:56 +0000995 CloseLoc = T.getCloseLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000996
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000997 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000998 Stmts, isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000999}
1000
Chris Lattner15ff1112008-12-12 06:31:07 +00001001/// ParseParenExprOrCondition:
1002/// [C ] '(' expression ')'
Chris Lattnerff871fb2008-12-12 06:35:28 +00001003/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattner15ff1112008-12-12 06:31:07 +00001004///
1005/// This function parses and performs error recovery on the specified condition
1006/// or expression (depending on whether we're in C++ or C mode). This function
1007/// goes out of its way to recover well. It returns true if there was a parser
1008/// error (the right paren couldn't be found), which indicates that the caller
1009/// should try to recover harder. It returns false if the condition is
1010/// successfully parsed. Note that a successful parse can still have semantic
1011/// errors in the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001012bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCalld226f652010-08-21 09:40:31 +00001013 Decl *&DeclResult,
Douglas Gregor586596f2010-05-06 17:25:47 +00001014 SourceLocation Loc,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001015 bool ConvertToBoolean) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001016 BalancedDelimiterTracker T(*this, tok::l_paren);
1017 T.consumeOpen();
1018
David Blaikie4e4d0842012-03-11 07:00:24 +00001019 if (getLangOpts().CPlusPlus)
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001020 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001021 else {
1022 ExprResult = ParseExpression();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001023 DeclResult = nullptr;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001024
Douglas Gregor586596f2010-05-06 17:25:47 +00001025 // If required, convert to a boolean value.
1026 if (!ExprResult.isInvalid() && ConvertToBoolean)
1027 ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00001028 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner15ff1112008-12-12 06:31:07 +00001031 // If the parser was confused by the condition and we don't have a ')', try to
1032 // recover by skipping ahead to a semi and bailing out. If condexp is
1033 // semantically invalid but we have well formed code, keep going.
John McCalld226f652010-08-21 09:40:31 +00001034 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattner15ff1112008-12-12 06:31:07 +00001035 SkipUntil(tok::semi);
1036 // Skipping may have stopped if it found the containing ')'. If so, we can
1037 // continue parsing the if statement.
1038 if (Tok.isNot(tok::r_paren))
1039 return true;
1040 }
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Chris Lattner15ff1112008-12-12 06:31:07 +00001042 // Otherwise the condition is valid or the rparen is present.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001043 T.consumeClose();
Chad Rosierb6604462012-07-10 21:35:27 +00001044
Chris Lattnerbddc7e52012-04-28 16:24:20 +00001045 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1046 // that all callers are looking for a statement after the condition, so ")"
1047 // isn't valid.
1048 while (Tok.is(tok::r_paren)) {
1049 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1050 << FixItHint::CreateRemoval(Tok.getLocation());
1051 ConsumeParen();
1052 }
Chad Rosierb6604462012-07-10 21:35:27 +00001053
Chris Lattner15ff1112008-12-12 06:31:07 +00001054 return false;
1055}
1056
1057
Reid Spencer5f016e22007-07-11 17:01:13 +00001058/// ParseIfStatement
1059/// if-statement: [C99 6.8.4.1]
1060/// 'if' '(' expression ')' statement
1061/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001062/// [C++] 'if' '(' condition ')' statement
1063/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +00001064///
Richard Smith534986f2012-04-14 00:33:13 +00001065StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001066 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1068
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001069 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001070 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +00001072 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001074
David Blaikie4e4d0842012-03-11 07:00:24 +00001075 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001076
Chris Lattner22153252007-08-26 23:08:06 +00001077 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1078 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001079 //
1080 // C++ 6.4p3:
1081 // A name introduced by a declaration in a condition is in scope from its
1082 // point of declaration until the end of the substatements controlled by the
1083 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001084 // C++ 3.3.2p4:
1085 // Names declared in the for-init-statement, and in the condition of if,
1086 // while, for, and switch statements are local to the if, while, for, or
1087 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001088 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001089 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +00001090
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001092 ExprResult CondExp;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001093 Decl *CondVar = nullptr;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001094 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001095 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +00001096
David Blaikiedef07622012-05-16 04:20:04 +00001097 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Chris Lattner0ecea032007-08-22 05:28:50 +00001099 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001100 // there is no compound stmt. C90 does not have this clause. We only do this
1101 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001102 //
1103 // C++ 6.4p1:
1104 // The substatement in a selection-statement (each substatement, in the else
1105 // form of the if statement) implicitly defines a local scope.
1106 //
1107 // For C++ we create a scope for the condition and a new scope for
1108 // substatements because:
1109 // -When the 'then' scope exits, we want the condition declaration to still be
1110 // active for the 'else' scope too.
1111 // -Sema will detect name clashes by considering declarations of a
1112 // 'ControlScope' as part of its direct subscope.
1113 // -If we wanted the condition and substatement to be in the same scope, we
1114 // would have to notify ParseStatement not to create a new scope. It's
1115 // simpler to let it create a new scope.
1116 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001117 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001118
Chris Lattnerb96728d2007-10-29 05:08:52 +00001119 // Read the 'then' stmt.
1120 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +00001121
1122 SourceLocation InnerStatementTrailingElseLoc;
1123 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001124
Chris Lattnera36ce712007-08-22 05:16:28 +00001125 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001126 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001127
Reid Spencer5f016e22007-07-11 17:01:13 +00001128 // If it has an else, parse it.
1129 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +00001130 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +00001131 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001132
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001133 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +00001134 if (TrailingElseLoc)
1135 *TrailingElseLoc = Tok.getLocation();
1136
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +00001138 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001139
Chris Lattner0ecea032007-08-22 05:28:50 +00001140 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001141 // there is no compound stmt. C90 does not have this clause. We only do
1142 // this if the body isn't a compound statement to avoid push/pop in common
1143 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001144 //
1145 // C++ 6.4p1:
1146 // The substatement in a selection-statement (each substatement, in the else
1147 // form of the if statement) implicitly defines a local scope.
1148 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001149 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001150
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001152
Chris Lattnera36ce712007-08-22 05:16:28 +00001153 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001154 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +00001155 } else if (Tok.is(tok::code_completion)) {
1156 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001157 cutOffParsing();
1158 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +00001159 } else if (InnerStatementTrailingElseLoc.isValid()) {
1160 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001162
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001163 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Chris Lattnerb96728d2007-10-29 05:08:52 +00001165 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +00001166 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +00001167 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001168 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001169 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1170 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +00001171 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +00001172 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +00001173 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001174
Chris Lattnerb96728d2007-10-29 05:08:52 +00001175 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001176 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001177 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001178 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001179 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001180
John McCall9ae2f072010-08-23 23:25:46 +00001181 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001182 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001183}
1184
1185/// ParseSwitchStatement
1186/// switch-statement:
1187/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001188/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001189StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001190 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1192
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001193 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001194 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001196 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 }
Chris Lattner22153252007-08-26 23:08:06 +00001198
David Blaikie4e4d0842012-03-11 07:00:24 +00001199 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001200
Chris Lattner22153252007-08-26 23:08:06 +00001201 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1202 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001203 //
1204 // C++ 6.4p3:
1205 // A name introduced by a declaration in a condition is in scope from its
1206 // point of declaration until the end of the substatements controlled by the
1207 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001208 // C++ 3.3.2p4:
1209 // Names declared in the for-init-statement, and in the condition of if,
1210 // while, for, and switch statements are local to the if, while, for, or
1211 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001212 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001213 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001214 if (C99orCXX)
1215 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001216 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001217
1218 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001219 ExprResult Cond;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001220 Decl *CondVar = nullptr;
Douglas Gregor586596f2010-05-06 17:25:47 +00001221 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001222 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001223
John McCall60d7b3a2010-08-24 06:29:42 +00001224 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001225 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001226
Douglas Gregor586596f2010-05-06 17:25:47 +00001227 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001228 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001229 // FIXME: This is not optimal recovery, but parsing the body is more
1230 // dangerous due to the presence of case and default statements, which
1231 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001232 if (Tok.is(tok::l_brace)) {
1233 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001234 SkipUntil(tok::r_brace);
Douglas Gregor4186ff42010-05-20 23:20:59 +00001235 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001236 SkipUntil(tok::semi);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001237 return Switch;
Douglas Gregor586596f2010-05-06 17:25:47 +00001238 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001239
Chris Lattner0ecea032007-08-22 05:28:50 +00001240 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001241 // there is no compound stmt. C90 does not have this clause. We only do this
1242 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001243 //
1244 // C++ 6.4p1:
1245 // The substatement in a selection-statement (each substatement, in the else
1246 // form of the if statement) implicitly defines a local scope.
1247 //
1248 // See comments in ParseIfStatement for why we create a scope for the
1249 // condition and a new scope for substatement in C++.
1250 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001251 getCurScope()->AddFlags(Scope::BreakScope);
1252 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001253
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001254 // We have incremented the mangling number for the SwitchScope and the
1255 // InnerScope, which is one too many.
1256 if (C99orCXX)
1257 getCurScope()->decrementMSLocalManglingNumber();
1258
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001260 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001261
Chris Lattner7e52de42010-01-24 01:50:29 +00001262 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001263 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001264 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001265
John McCall9ae2f072010-08-23 23:25:46 +00001266 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001267}
1268
1269/// ParseWhileStatement
1270/// while-statement: [C99 6.8.5.1]
1271/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001272/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001273StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001274 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 SourceLocation WhileLoc = Tok.getLocation();
1276 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001277
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001278 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001279 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001281 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001283
David Blaikie4e4d0842012-03-11 07:00:24 +00001284 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001285
Chris Lattner22153252007-08-26 23:08:06 +00001286 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1287 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001288 //
1289 // C++ 6.4p3:
1290 // A name introduced by a declaration in a condition is in scope from its
1291 // point of declaration until the end of the substatements controlled by the
1292 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001293 // C++ 3.3.2p4:
1294 // Names declared in the for-init-statement, and in the condition of if,
1295 // while, for, and switch statements are local to the if, while, for, or
1296 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001297 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001298 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001299 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001300 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1301 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001302 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001303 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1304 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001305
1306 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001307 ExprResult Cond;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001308 Decl *CondVar = nullptr;
Douglas Gregor586596f2010-05-06 17:25:47 +00001309 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001310 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001311
David Blaikiedef07622012-05-16 04:20:04 +00001312 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Stephen Hines651f13c2014-04-23 16:59:28 -07001314 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001315 // there is no compound stmt. C90 does not have this clause. We only do this
1316 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001317 //
1318 // C++ 6.5p2:
1319 // The substatement in an iteration-statement implicitly defines a local scope
1320 // which is entered and exited each time through the loop.
1321 //
1322 // See comments in ParseIfStatement for why we create a scope for the
1323 // condition and a new scope for substatement in C++.
1324 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001325 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001326
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001328 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001329
Chris Lattner0ecea032007-08-22 05:28:50 +00001330 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001331 InnerScope.Exit();
1332 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001333
John McCalld226f652010-08-21 09:40:31 +00001334 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001335 return StmtError();
1336
John McCall9ae2f072010-08-23 23:25:46 +00001337 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001338}
1339
1340/// ParseDoStatement
1341/// do-statement: [C99 6.8.5.2]
1342/// 'do' statement 'while' '(' expression ')' ';'
1343/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001344StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001345 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001347
Chris Lattner22153252007-08-26 23:08:06 +00001348 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1349 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001350 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001351 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001352 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001353 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001354 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001355
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001356 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001357
Stephen Hines651f13c2014-04-23 16:59:28 -07001358 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001359 // there is no compound stmt. C90 does not have this clause. We only do this
1360 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001361 //
1362 // C++ 6.5p2:
1363 // The substatement in an iteration-statement implicitly defines a local scope
1364 // which is entered and exited each time through the loop.
1365 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001366 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1367 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001370 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001371
Chris Lattner0ecea032007-08-22 05:28:50 +00001372 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001373 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001374
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001375 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001376 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001377 Diag(Tok, diag::err_expected_while);
Stephen Hines651f13c2014-04-23 16:59:28 -07001378 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataev8fe24752013-11-18 08:17:37 +00001379 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner19504402008-11-13 18:52:53 +00001380 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001381 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 }
1383 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001384
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001385 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001386 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataev8fe24752013-11-18 08:17:37 +00001387 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001388 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001390
Richard Smith5eed7e02013-10-15 01:34:54 +00001391 // Parse the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001392 BalancedDelimiterTracker T(*this, tok::l_paren);
1393 T.consumeOpen();
Chad Rosierb6604462012-07-10 21:35:27 +00001394
Richard Smith5eed7e02013-10-15 01:34:54 +00001395 // A do-while expression is not a condition, so can't have attributes.
1396 DiagnoseAndSkipCXX11Attributes();
Sean Hunt2edf0a22012-06-23 05:07:58 +00001397
John McCall60d7b3a2010-08-24 06:29:42 +00001398 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001399 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001400 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001401
Sebastian Redl9a920342008-12-11 19:48:14 +00001402 if (Cond.isInvalid() || Body.isInvalid())
1403 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001404
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001405 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1406 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001407}
1408
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001409bool Parser::isForRangeIdentifier() {
1410 assert(Tok.is(tok::identifier));
1411
1412 const Token &Next = NextToken();
1413 if (Next.is(tok::colon))
1414 return true;
1415
1416 if (Next.is(tok::l_square) || Next.is(tok::kw_alignas)) {
1417 TentativeParsingAction PA(*this);
1418 ConsumeToken();
1419 SkipCXX11Attributes();
1420 bool Result = Tok.is(tok::colon);
1421 PA.Revert();
1422 return Result;
1423 }
1424
1425 return false;
1426}
1427
Reid Spencer5f016e22007-07-11 17:01:13 +00001428/// ParseForStatement
1429/// for-statement: [C99 6.8.5.3]
1430/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1431/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001432/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1433/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001434/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001435/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1436/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001437///
1438/// [C++] for-init-statement:
1439/// [C++] expression-statement
1440/// [C++] simple-declaration
1441///
Richard Smithad762fc2011-04-14 22:09:26 +00001442/// [C++0x] for-range-declaration:
1443/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1444/// [C++0x] for-range-initializer:
1445/// [C++0x] expression
1446/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001447StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001448 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001450
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001451 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001452 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001454 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001456
Chad Rosierb6604462012-07-10 21:35:27 +00001457 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1458 getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001459
Chris Lattner22153252007-08-26 23:08:06 +00001460 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1461 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001462 //
1463 // C++ 6.4p3:
1464 // A name introduced by a declaration in a condition is in scope from its
1465 // point of declaration until the end of the substatements controlled by the
1466 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001467 // C++ 3.3.2p4:
1468 // Names declared in the for-init-statement, and in the condition of if,
1469 // while, for, and switch statements are local to the if, while, for, or
1470 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001471 // C++ 6.5.3p1:
1472 // Names declared in the for-init-statement are in the same declarative-region
1473 // as those declared in the condition.
1474 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001475 unsigned ScopeFlags = 0;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001476 if (C99orCXXorObjC)
Stephen Hines651f13c2014-04-23 16:59:28 -07001477 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001478
1479 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001480
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001481 BalancedDelimiterTracker T(*this, tok::l_paren);
1482 T.consumeOpen();
1483
John McCall60d7b3a2010-08-24 06:29:42 +00001484 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001485
Richard Smithad762fc2011-04-14 22:09:26 +00001486 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001487 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001488 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001489 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001490 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001491 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001492 FullExprArg ThirdPart(Actions);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001493 Decl *SecondVar = nullptr;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001494
Douglas Gregor791215b2009-09-21 20:51:25 +00001495 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001496 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001497 C99orCXXorObjC? Sema::PCC_ForInit
1498 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001499 cutOffParsing();
1500 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001501 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001502
Sean Hunt2edf0a22012-06-23 05:07:58 +00001503 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001504 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001505
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001507 if (Tok.is(tok::semi)) { // for (;
Sean Hunt2edf0a22012-06-23 05:07:58 +00001508 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // no first part, eat the ';'.
1510 ConsumeToken();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001511 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1512 isForRangeIdentifier()) {
1513 ProhibitAttributes(attrs);
1514 IdentifierInfo *Name = Tok.getIdentifierInfo();
1515 SourceLocation Loc = ConsumeToken();
1516 MaybeParseCXX11Attributes(attrs);
1517
1518 ForRangeInit.ColonLoc = ConsumeToken();
1519 if (Tok.is(tok::l_brace))
1520 ForRangeInit.RangeExpr = ParseBraceInitializer();
1521 else
1522 ForRangeInit.RangeExpr = ParseExpression();
1523
1524 Diag(Loc, getLangOpts().CPlusPlus1z
1525 ? diag::warn_cxx1y_compat_for_range_identifier
1526 : diag::ext_for_range_identifier)
1527 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1528 ? FixItHint::CreateInsertion(Loc, "auto &&")
1529 : FixItHint());
1530
1531 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1532 attrs, attrs.Range.getEnd());
1533 ForRange = true;
Eli Friedman9490ab42011-12-20 01:50:37 +00001534 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001536 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001538
Richard Smithad762fc2011-04-14 22:09:26 +00001539 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001540 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001541 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1542
Chris Lattner97144fc2009-04-02 04:16:50 +00001543 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001544 StmtVector Stmts;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001545 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1546 Stmts, Declarator::ForContext, DeclEnd, attrs, false,
1547 MightBeForRangeStmt ? &ForRangeInit : nullptr);
Chris Lattnercd147752009-03-29 17:27:48 +00001548 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Richard Smithad762fc2011-04-14 22:09:26 +00001549 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001550 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001551 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001552
Richard Smithad762fc2011-04-14 22:09:26 +00001553 ForRange = true;
1554 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001555 ConsumeToken();
1556 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001557 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001558 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001559 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001560
Douglas Gregorfb629412010-08-23 21:17:50 +00001561 if (Tok.is(tok::code_completion)) {
1562 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001563 cutOffParsing();
1564 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001565 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001566 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001567 } else {
1568 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001569 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 } else {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001571 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 Value = ParseExpression();
1573
John McCallf6a16482010-12-04 03:47:34 +00001574 ForEach = isTokIdentifier_in();
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001577 if (!Value.isInvalid()) {
1578 if (ForEach)
1579 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1580 else
Richard Smith41956372013-01-14 22:39:08 +00001581 FirstPart = Actions.ActOnExprStmt(Value);
John McCallf6a16482010-12-04 03:47:34 +00001582 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001583
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001584 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001586 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001587 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001588
Douglas Gregorfb629412010-08-23 21:17:50 +00001589 if (Tok.is(tok::code_completion)) {
1590 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001591 cutOffParsing();
1592 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001593 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001594 Collection = ParseExpression();
Richard Smith80ad52f2013-01-02 11:42:31 +00001595 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001596 // User tried to write the reasonable, but ill-formed, for-range-statement
1597 // for (expr : expr) { ... }
1598 Diag(Tok, diag::err_for_range_expected_decl)
1599 << FirstPart.get()->getSourceRange();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001600 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smitha44854a2011-12-20 22:56:20 +00001601 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001602 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001603 if (!Value.isInvalid()) {
1604 Diag(Tok, diag::err_expected_semi_for);
1605 } else {
1606 // Skip until semicolon or rparen, don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001607 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregorb72c7782011-02-17 03:38:46 +00001608 if (Tok.is(tok::semi))
1609 ConsumeToken();
1610 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 }
1612 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001613
1614 // Parse the second part of the for specifier.
1615 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smithad762fc2011-04-14 22:09:26 +00001616 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001617 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001618 // Parse the second part of the for specifier.
1619 if (Tok.is(tok::semi)) { // for (...;;
1620 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001621 } else if (Tok.is(tok::r_paren)) {
1622 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001623 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001624 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001625 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001626 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1627 else {
1628 Second = ParseExpression();
1629 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001630 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001631 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001632 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001633 SecondPartIsInvalid = Second.isInvalid();
David Blaikiedef07622012-05-16 04:20:04 +00001634 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001635 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001636
Douglas Gregorb72c7782011-02-17 03:38:46 +00001637 if (Tok.isNot(tok::semi)) {
1638 if (!SecondPartIsInvalid || SecondVar)
1639 Diag(Tok, diag::err_expected_semi_for);
1640 else
1641 // Skip until semicolon or rparen, don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001642 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregorb72c7782011-02-17 03:38:46 +00001643 }
1644
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001645 if (Tok.is(tok::semi)) {
1646 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001647 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001648
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001649 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001650 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001651 ExprResult Third = ParseExpression();
Richard Smith41956372013-01-14 22:39:08 +00001652 // FIXME: The C++11 standard doesn't actually say that this is a
1653 // discarded-value expression, but it clearly should be.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001654 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001655 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001658 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001659
Richard Smithad762fc2011-04-14 22:09:26 +00001660 // We need to perform most of the semantic analysis for a C++0x for-range
1661 // statememt before parsing the body, in order to be able to deduce the type
1662 // of an auto-typed loop variable.
1663 StmtResult ForRangeStmt;
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001664 StmtResult ForEachStmt;
Chad Rosierb6604462012-07-10 21:35:27 +00001665
John McCall990567c2011-07-27 01:07:15 +00001666 if (ForRange) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001667 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001668 ForRangeInit.ColonLoc,
1669 ForRangeInit.RangeExpr.get(),
Richard Smith8b533d92012-09-20 21:52:32 +00001670 T.getCloseLocation(),
1671 Sema::BFRK_Build);
Richard Smithad762fc2011-04-14 22:09:26 +00001672
John McCall990567c2011-07-27 01:07:15 +00001673
1674 // Similarly, we need to do the semantic analysis for a for-range
1675 // statement immediately in order to close over temporaries correctly.
1676 } else if (ForEach) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001677 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001678 FirstPart.get(),
1679 Collection.get(),
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001680 T.getCloseLocation());
John McCall990567c2011-07-27 01:07:15 +00001681 }
1682
Stephen Hines651f13c2014-04-23 16:59:28 -07001683 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001684 // there is no compound stmt. C90 does not have this clause. We only do this
1685 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001686 //
1687 // C++ 6.5p2:
1688 // The substatement in an iteration-statement implicitly defines a local scope
1689 // which is entered and exited each time through the loop.
1690 //
1691 // See comments in ParseIfStatement for why we create a scope for
1692 // for-init-statement/condition and a new scope for substatement in C++.
1693 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001694 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1695 Tok.is(tok::l_brace));
1696
1697 // The body of the for loop has the same local mangling number as the
1698 // for-init-statement.
1699 // It will only be incremented if the body contains other things that would
1700 // normally increment the mangling number (like a compound statement).
1701 if (C99orCXXorObjC)
1702 getCurScope()->decrementMSLocalManglingNumber();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001703
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001705 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001706
Chris Lattner0ecea032007-08-22 05:28:50 +00001707 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001708 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001709
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001711 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001712
1713 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001714 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001715
Richard Smithad762fc2011-04-14 22:09:26 +00001716 if (ForEach)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001717 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1718 Body.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Richard Smithad762fc2011-04-14 22:09:26 +00001720 if (ForRange)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001721 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001722
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001723 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001724 SecondPart, SecondVar, ThirdPart,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001725 T.getCloseLocation(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001726}
1727
1728/// ParseGotoStatement
1729/// jump-statement:
1730/// 'goto' identifier ';'
1731/// [GNU] 'goto' '*' expression ';'
1732///
1733/// Note: this lets the caller parse the end ';'.
1734///
Richard Smith534986f2012-04-14 00:33:13 +00001735StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001736 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001738
John McCall60d7b3a2010-08-24 06:29:42 +00001739 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001740 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001741 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1742 Tok.getLocation());
1743 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001745 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 // GNU indirect goto extension.
1747 Diag(Tok, diag::ext_gnu_indirect_goto);
1748 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001749 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001750 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001751 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001752 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001754 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
Chris Lattner95cfb852007-07-22 04:13:33 +00001755 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07001756 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redl9a920342008-12-11 19:48:14 +00001757 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001759
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001760 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +00001761}
1762
1763/// ParseContinueStatement
1764/// jump-statement:
1765/// 'continue' ';'
1766///
1767/// Note: this lets the caller parse the end ';'.
1768///
Richard Smith534986f2012-04-14 00:33:13 +00001769StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001771 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001772}
1773
1774/// ParseBreakStatement
1775/// jump-statement:
1776/// 'break' ';'
1777///
1778/// Note: this lets the caller parse the end ';'.
1779///
Richard Smith534986f2012-04-14 00:33:13 +00001780StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001782 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001783}
1784
1785/// ParseReturnStatement
1786/// jump-statement:
1787/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001788StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001789 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001791
John McCall60d7b3a2010-08-24 06:29:42 +00001792 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001793 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001794 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001795 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001796 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001797 return StmtError();
1798 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001799
David Blaikie4e4d0842012-03-11 07:00:24 +00001800 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001801 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001802 if (R.isUsable())
Richard Smith80ad52f2013-01-02 11:42:31 +00001803 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001804 diag::warn_cxx98_compat_generalized_initializer_lists :
1805 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001806 << R.get()->getSourceRange();
1807 } else
1808 R = ParseExpression();
Stephen Hines651f13c2014-04-23 16:59:28 -07001809 if (R.isInvalid()) {
1810 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001811 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001812 }
1813 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001814 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001815}
1816
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001817StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts, bool OnlyStatement,
1818 SourceLocation *TrailingElseLoc,
1819 ParsedAttributesWithRange &Attrs) {
1820 // Create temporary attribute list.
1821 ParsedAttributesWithRange TempAttrs(AttrFactory);
John McCallaeeacf72013-05-03 00:10:13 +00001822
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001823 // Get vectorize hints and consume annotated token.
1824 while (Tok.is(tok::annot_pragma_loop_hint)) {
1825 LoopHint Hint = HandlePragmaLoopHint();
Chris Lattner64cb4752009-12-20 23:00:41 +00001826 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001827
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001828 if (!Hint.LoopLoc || !Hint.OptionLoc || !Hint.ValueLoc)
1829 continue;
1830
1831 ArgsUnion ArgHints[] = {Hint.OptionLoc, Hint.ValueLoc,
1832 ArgsUnion(Hint.ValueExpr)};
1833 TempAttrs.addNew(Hint.LoopLoc->Ident, Hint.Range, nullptr,
1834 Hint.LoopLoc->Loc, ArgHints, 3, AttributeList::AS_Pragma);
Chris Lattner64cb4752009-12-20 23:00:41 +00001835 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001836
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001837 // Get the next statement.
1838 MaybeParseCXX11Attributes(Attrs);
Chris Lattner64cb4752009-12-20 23:00:41 +00001839
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001840 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1841 Stmts, OnlyStatement, TrailingElseLoc, Attrs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001842
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001843 Attrs.takeAllFrom(TempAttrs);
1844 return S;
Reid Spencer5f016e22007-07-11 17:01:13 +00001845}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001846
Douglas Gregorc9977d02011-03-16 17:05:57 +00001847Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00001848 assert(Tok.is(tok::l_brace));
1849 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001850
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00001851 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1a5bd5d2012-11-19 21:13:18 +00001852 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001853 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00001854 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001855 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001856
John McCallf312b1e2010-08-26 23:41:50 +00001857 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1858 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001860 // Do not enter a scope for the brace, as the arguments are in the same scope
1861 // (the function body) as the body itself. Instead, just read the statement
1862 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00001863 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00001864
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001865 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001866 if (FnBody.isInvalid()) {
1867 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00001868 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001869 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001870
Douglas Gregorc9977d02011-03-16 17:05:57 +00001871 BodyScope.Exit();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001872 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00001873}
Sebastian Redla0fd8652008-12-21 16:41:36 +00001874
Sebastian Redld3a413d2009-04-26 20:35:05 +00001875/// ParseFunctionTryBlock - Parse a C++ function-try-block.
1876///
1877/// function-try-block:
1878/// 'try' ctor-initializer[opt] compound-statement handler-seq
1879///
Douglas Gregorc9977d02011-03-16 17:05:57 +00001880Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00001881 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1882 SourceLocation TryLoc = ConsumeToken();
1883
John McCallf312b1e2010-08-26 23:41:50 +00001884 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1885 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00001886
1887 // Constructor initializer list?
1888 if (Tok.is(tok::colon))
1889 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00001890 else
1891 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001892
Richard Smith1a5bd5d2012-11-19 21:13:18 +00001893 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
1894 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001895 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00001896 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001897 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001898
Sebastian Redlde1b60a2009-04-26 21:08:36 +00001899 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikiec4027c82012-11-10 01:04:23 +00001900 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redld3a413d2009-04-26 20:35:05 +00001901 // If we failed to parse the try-catch, we just give the function an empty
1902 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001903 if (FnBody.isInvalid()) {
1904 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00001905 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001906 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00001907
Douglas Gregorc9977d02011-03-16 17:05:57 +00001908 BodyScope.Exit();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001909 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Sebastian Redld3a413d2009-04-26 20:35:05 +00001910}
1911
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001912bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001913 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001914 assert(SkipFunctionBodies &&
1915 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001916
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00001917 if (!PP.isCodeCompletionEnabled()) {
1918 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001919 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00001920 return true;
1921 }
1922
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001923 // We're in code-completion mode. Skip parsing for all function bodies unless
1924 // the body contains the code-completion point.
1925 TentativeParsingAction PA(*this);
1926 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001927 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001928 PA.Commit();
1929 return true;
1930 }
1931
1932 PA.Revert();
1933 return false;
1934}
1935
Sebastian Redla0fd8652008-12-21 16:41:36 +00001936/// ParseCXXTryBlock - Parse a C++ try-block.
1937///
1938/// try-block:
1939/// 'try' compound-statement handler-seq
1940///
Richard Smith534986f2012-04-14 00:33:13 +00001941StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00001942 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1943
1944 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001945 return ParseCXXTryBlockCommon(TryLoc);
1946}
1947
1948/// ParseCXXTryBlockCommon - Parse the common part of try-block and
1949/// function-try-block.
1950///
1951/// try-block:
1952/// 'try' compound-statement handler-seq
1953///
1954/// function-try-block:
1955/// 'try' ctor-initializer[opt] compound-statement handler-seq
1956///
1957/// handler-seq:
1958/// handler handler-seq[opt]
1959///
John Wiegley28bbe4b2011-04-28 01:08:34 +00001960/// [Borland] try-block:
1961/// 'try' compound-statement seh-except-block
Stephen Hines651f13c2014-04-23 16:59:28 -07001962/// 'try' compound-statement seh-finally-block
John Wiegley28bbe4b2011-04-28 01:08:34 +00001963///
David Blaikiec4027c82012-11-10 01:04:23 +00001964StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00001965 if (Tok.isNot(tok::l_brace))
Stephen Hines651f13c2014-04-23 16:59:28 -07001966 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sean Huntbbd37c62009-11-21 08:43:09 +00001967 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00001968
1969 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikiee5afdcf2012-11-13 18:51:45 +00001970 Scope::DeclScope | Scope::TryScope |
1971 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redla0fd8652008-12-21 16:41:36 +00001972 if (TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001973 return TryBlock;
Sebastian Redla0fd8652008-12-21 16:41:36 +00001974
John Wiegley28bbe4b2011-04-28 01:08:34 +00001975 // Borland allows SEH-handlers with 'try'
Chad Rosierb6604462012-07-10 21:35:27 +00001976
Richard Smith534986f2012-04-14 00:33:13 +00001977 if ((Tok.is(tok::identifier) &&
1978 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
1979 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00001980 // TODO: Factor into common return ParseSEHHandlerCommon(...)
1981 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00001982 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00001983 SourceLocation Loc = ConsumeToken();
1984 Handler = ParseSEHExceptBlock(Loc);
1985 }
1986 else {
1987 SourceLocation Loc = ConsumeToken();
1988 Handler = ParseSEHFinallyBlock(Loc);
1989 }
1990 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001991 return Handler;
John McCall7f040a92010-12-24 02:08:15 +00001992
John Wiegley28bbe4b2011-04-28 01:08:34 +00001993 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
1994 TryLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001995 TryBlock.get(),
1996 Handler.get());
Sebastian Redla0fd8652008-12-21 16:41:36 +00001997 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00001998 else {
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001999 StmtVector Handlers;
Richard Smith5eed7e02013-10-15 01:34:54 +00002000
2001 // C++11 attributes can't appear here, despite this context seeming
2002 // statement-like.
2003 DiagnoseAndSkipCXX11Attributes();
Sebastian Redla0fd8652008-12-21 16:41:36 +00002004
John Wiegley28bbe4b2011-04-28 01:08:34 +00002005 if (Tok.isNot(tok::kw_catch))
2006 return StmtError(Diag(Tok, diag::err_expected_catch));
2007 while (Tok.is(tok::kw_catch)) {
David Blaikiec4027c82012-11-10 01:04:23 +00002008 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley28bbe4b2011-04-28 01:08:34 +00002009 if (!Handler.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002010 Handlers.push_back(Handler.get());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002011 }
2012 // Don't bother creating the full statement if we don't have any usable
2013 // handlers.
2014 if (Handlers.empty())
2015 return StmtError();
2016
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002017 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002018 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002019}
2020
2021/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2022///
Richard Smith4cd81c52013-01-29 09:02:09 +00002023/// handler:
2024/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +00002025///
Richard Smith4cd81c52013-01-29 09:02:09 +00002026/// exception-declaration:
2027/// attribute-specifier-seq[opt] type-specifier-seq declarator
2028/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2029/// '...'
Sebastian Redla0fd8652008-12-21 16:41:36 +00002030///
David Blaikiec4027c82012-11-10 01:04:23 +00002031StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002032 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2033
2034 SourceLocation CatchLoc = ConsumeToken();
2035
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002036 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002037 if (T.expectAndConsume())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002038 return StmtError();
2039
2040 // C++ 3.3.2p3:
2041 // The name in a catch exception-declaration is local to the handler and
2042 // shall not be redeclared in the outermost block of the handler.
David Blaikiec4027c82012-11-10 01:04:23 +00002043 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikiee5afdcf2012-11-13 18:51:45 +00002044 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002045
2046 // exception-declaration is equivalent to '...' or a parameter-declaration
2047 // without default arguments.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002048 Decl *ExceptionDecl = nullptr;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002049 if (Tok.isNot(tok::ellipsis)) {
Richard Smith4cd81c52013-01-29 09:02:09 +00002050 ParsedAttributesWithRange Attributes(AttrFactory);
2051 MaybeParseCXX11Attributes(Attributes);
2052
John McCall0b7e6782011-03-24 11:26:52 +00002053 DeclSpec DS(AttrFactory);
Richard Smith4cd81c52013-01-29 09:02:09 +00002054 DS.takeAttributesFrom(Attributes);
2055
Sebastian Redl4b07b292008-12-22 19:15:10 +00002056 if (ParseCXXTypeSpecifierSeq(DS))
2057 return StmtError();
Richard Smith4cd81c52013-01-29 09:02:09 +00002058
Sebastian Redla0fd8652008-12-21 16:41:36 +00002059 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2060 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002061 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002062 } else
2063 ConsumeToken();
2064
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002065 T.consumeClose();
2066 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002067 return StmtError();
2068
2069 if (Tok.isNot(tok::l_brace))
Stephen Hines651f13c2014-04-23 16:59:28 -07002070 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002071
Sean Huntbbd37c62009-11-21 08:43:09 +00002072 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002073 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002074 if (Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002075 return Block;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002076
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002077 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002078}
Francois Pichet1e862692011-05-06 20:48:22 +00002079
2080void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002081 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002082 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002083 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002084
Douglas Gregor3896fc52011-10-24 22:31:10 +00002085 // Handle dependent statements by parsing the braces as a compound statement.
2086 // This is not the same behavior as Visual C++, which don't treat this as a
2087 // compound statement, but for Clang's type checking we can't have anything
2088 // inside these braces escaping to the surrounding code.
2089 if (Result.Behavior == IEB_Dependent) {
2090 if (!Tok.is(tok::l_brace)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002091 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smith534986f2012-04-14 00:33:13 +00002092 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002093 }
Richard Smith534986f2012-04-14 00:33:13 +00002094
2095 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002096 if (Compound.isInvalid())
2097 return;
Richard Smith534986f2012-04-14 00:33:13 +00002098
Douglas Gregorba0513d2011-10-25 01:33:02 +00002099 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2100 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002101 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002102 Result.Name,
2103 Compound.get());
2104 if (DepResult.isUsable())
2105 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002106 return;
2107 }
Richard Smith534986f2012-04-14 00:33:13 +00002108
Douglas Gregor3896fc52011-10-24 22:31:10 +00002109 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2110 if (Braces.consumeOpen()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002111 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet1e862692011-05-06 20:48:22 +00002112 return;
2113 }
Francois Pichet1e862692011-05-06 20:48:22 +00002114
Douglas Gregor3896fc52011-10-24 22:31:10 +00002115 switch (Result.Behavior) {
2116 case IEB_Parse:
2117 // Parse the statements below.
2118 break;
Chad Rosierb6604462012-07-10 21:35:27 +00002119
Douglas Gregor3896fc52011-10-24 22:31:10 +00002120 case IEB_Dependent:
2121 llvm_unreachable("Dependent case handled above");
Chad Rosierb6604462012-07-10 21:35:27 +00002122
Douglas Gregor3896fc52011-10-24 22:31:10 +00002123 case IEB_Skip:
2124 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002125 return;
2126 }
2127
2128 // Condition is true, parse the statements.
2129 while (Tok.isNot(tok::r_brace)) {
2130 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2131 if (R.isUsable())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002132 Stmts.push_back(R.get());
Francois Pichet1e862692011-05-06 20:48:22 +00002133 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002134 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002135}