blob: 776423c28beb7b9a65554ecdcebee0ac9ccda64d [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 McCall19510852010-08-20 18:27:03 +000017#include "clang/Sema/DeclSpec.h"
John McCallf312b1e2010-08-26 23:41:50 +000018#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall19510852010-08-20 18:27:03 +000019#include "clang/Sema/Scope.h"
Richard Smith05766812012-08-18 00:55:03 +000020#include "clang/Sema/TypoCorrection.h"
Chris Lattnerae50fa02009-03-05 00:00:31 +000021#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/PrettyStackTrace.h"
23#include "clang/Basic/SourceManager.h"
Chad Rosier8cd64b42012-06-11 20:47:18 +000024#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
27//===----------------------------------------------------------------------===//
28// C99 6.8: Statements and Blocks.
29//===----------------------------------------------------------------------===//
30
31/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
32/// StatementOrDeclaration:
33/// statement
34/// declaration
35///
36/// statement:
37/// labeled-statement
38/// compound-statement
39/// expression-statement
40/// selection-statement
41/// iteration-statement
42/// jump-statement
Argyrios Kyrtzidisdcdd55f2008-09-07 18:58:01 +000043/// [C++] declaration-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +000044/// [C++] try-block
John Wiegley28bbe4b2011-04-28 01:08:34 +000045/// [MS] seh-try-block
Fariborz Jahanianb384d322007-10-04 20:19:06 +000046/// [OBC] objc-throw-statement
47/// [OBC] objc-try-catch-statement
Fariborz Jahanianc385c902008-01-29 18:21:32 +000048/// [OBC] objc-synchronized-statement
Reid Spencer5f016e22007-07-11 17:01:13 +000049/// [GNU] asm-statement
50/// [OMP] openmp-construct [TODO]
51///
52/// labeled-statement:
53/// identifier ':' statement
54/// 'case' constant-expression ':' statement
55/// 'default' ':' statement
56///
57/// selection-statement:
58/// if-statement
59/// switch-statement
60///
61/// iteration-statement:
62/// while-statement
63/// do-statement
64/// for-statement
65///
66/// expression-statement:
67/// expression[opt] ';'
68///
69/// jump-statement:
70/// 'goto' identifier ';'
71/// 'continue' ';'
72/// 'break' ';'
73/// 'return' expression[opt] ';'
74/// [GNU] 'goto' '*' expression ';'
75///
Fariborz Jahanianb384d322007-10-04 20:19:06 +000076/// [OBC] objc-throw-statement:
77/// [OBC] '@' 'throw' expression ';'
Mike Stump1eb44332009-09-09 15:08:12 +000078/// [OBC] '@' 'throw' ';'
79///
John McCall60d7b3a2010-08-24 06:29:42 +000080StmtResult
Nico Weber5cb94a72011-12-22 23:26:17 +000081Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
82 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000083
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +000084 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +000085
Richard Smith534986f2012-04-14 00:33:13 +000086 ParsedAttributesWithRange Attrs(AttrFactory);
87 MaybeParseCXX0XAttributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
88
89 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
90 OnlyStatement, TrailingElseLoc, Attrs);
91
92 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
93 "attributes on empty statement");
94
95 if (Attrs.empty() || Res.isInvalid())
96 return Res;
97
98 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
99}
100
101StmtResult
102Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
103 bool OnlyStatement, SourceLocation *TrailingElseLoc,
104 ParsedAttributesWithRange &Attrs) {
105 const char *SemiError = 0;
106 StmtResult Res;
Sean Huntbbd37c62009-11-21 08:43:09 +0000107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 // Cases in this switch statement should fall through if the parser expects
109 // the token to end in a semicolon (in which case SemiError should be set),
110 // or they directly 'return;' if not.
Douglas Gregor312eadb2011-04-24 05:37:28 +0000111Retry:
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000112 tok::TokenKind Kind = Tok.getKind();
113 SourceLocation AtLoc;
114 switch (Kind) {
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000115 case tok::at: // May be a @try or @throw statement
116 {
Richard Smith534986f2012-04-14 00:33:13 +0000117 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000118 AtLoc = ConsumeToken(); // consume @
Sebastian Redl43bc2a02008-12-11 20:12:42 +0000119 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000120 }
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000121
Douglas Gregor791215b2009-09-21 20:51:25 +0000122 case tok::code_completion:
John McCallf312b1e2010-08-26 23:41:50 +0000123 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000124 cutOffParsing();
125 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000126
Douglas Gregor312eadb2011-04-24 05:37:28 +0000127 case tok::identifier: {
128 Token Next = NextToken();
129 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000130 // identifier ':' statement
Richard Smith534986f2012-04-14 00:33:13 +0000131 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000132 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000133
Richard Smith05766812012-08-18 00:55:03 +0000134 // Look up the identifier, and typo-correct it to a keyword if it's not
135 // found.
Douglas Gregor3b887352011-04-27 04:48:22 +0000136 if (Next.isNot(tok::coloncolon)) {
Richard Smith05766812012-08-18 00:55:03 +0000137 // Try to limit which sets of keywords should be included in typo
138 // correction based on what the next token is.
139 // FIXME: Pass the next token into the CorrectionCandidateCallback and
140 // do this filtering in a more fine-grained manner.
141 CorrectionCandidateCallback DefaultValidator;
142 DefaultValidator.WantTypeSpecifiers =
143 Next.is(tok::l_paren) || Next.is(tok::less) ||
144 Next.is(tok::identifier) || Next.is(tok::star) ||
145 Next.is(tok::amp) || Next.is(tok::l_square);
146 DefaultValidator.WantExpressionKeywords =
147 Next.is(tok::l_paren) || Next.is(tok::identifier) ||
148 Next.is(tok::arrow) || Next.is(tok::period);
149 DefaultValidator.WantRemainingKeywords =
150 Next.is(tok::l_paren) || Next.is(tok::semi) ||
151 Next.is(tok::identifier) || Next.is(tok::l_brace);
152 DefaultValidator.WantCXXNamedCasts = false;
153 if (TryAnnotateName(/*IsAddressOfOperand*/false, &DefaultValidator)
154 == ANK_Error) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000155 // Handle errors here by skipping up to the next semicolon or '}', and
156 // eat the semicolon if that's what stopped us.
157 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
158 if (Tok.is(tok::semi))
159 ConsumeToken();
160 return StmtError();
Richard Smith05766812012-08-18 00:55:03 +0000161 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000162
Richard Smith05766812012-08-18 00:55:03 +0000163 // If the identifier was typo-corrected, try again.
164 if (Tok.isNot(tok::identifier))
Douglas Gregor312eadb2011-04-24 05:37:28 +0000165 goto Retry;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000166 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000167
Douglas Gregor312eadb2011-04-24 05:37:28 +0000168 // Fall through
169 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000170
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000171 default: {
David Blaikie4e4d0842012-03-11 07:00:24 +0000172 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner97144fc2009-04-02 04:16:50 +0000173 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek8113ecf2010-11-10 05:59:39 +0000174 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smith534986f2012-04-14 00:33:13 +0000175 DeclEnd, Attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000176 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000177 }
178
179 if (Tok.is(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 Diag(Tok, diag::err_expected_statement);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000181 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 }
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Richard Smith534986f2012-04-14 00:33:13 +0000184 return ParseExprStatement();
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000185 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000186
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000188 return ParseCaseStatement();
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000190 return ParseDefaultStatement();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smith534986f2012-04-14 00:33:13 +0000193 return ParseCompoundStatement();
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000194 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +0000195 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
196 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000197 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000198
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smith534986f2012-04-14 00:33:13 +0000200 return ParseIfStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smith534986f2012-04-14 00:33:13 +0000202 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000203
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smith534986f2012-04-14 00:33:13 +0000205 return ParseWhileStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smith534986f2012-04-14 00:33:13 +0000207 Res = ParseDoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000208 SemiError = "do/while";
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 break;
210 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smith534986f2012-04-14 00:33:13 +0000211 return ParseForStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000212
213 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smith534986f2012-04-14 00:33:13 +0000214 Res = ParseGotoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000215 SemiError = "goto";
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 break;
217 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smith534986f2012-04-14 00:33:13 +0000218 Res = ParseContinueStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000219 SemiError = "continue";
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 break;
221 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smith534986f2012-04-14 00:33:13 +0000222 Res = ParseBreakStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000223 SemiError = "break";
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 break;
225 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smith534986f2012-04-14 00:33:13 +0000226 Res = ParseReturnStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000227 SemiError = "return";
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 break;
Sebastian Redl61364dd2008-12-11 19:30:53 +0000229
Sebastian Redla0fd8652008-12-21 16:41:36 +0000230 case tok::kw_asm: {
Richard Smith534986f2012-04-14 00:33:13 +0000231 ProhibitAttributes(Attrs);
Steve Naroffd62701b2008-02-07 03:50:06 +0000232 bool msAsm = false;
233 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +0000234 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000235 if (msAsm) return Res;
Chris Lattner6869d8e2009-06-14 00:07:48 +0000236 SemiError = "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 break;
238 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000239
Sebastian Redla0fd8652008-12-21 16:41:36 +0000240 case tok::kw_try: // C++ 15: try-block
Richard Smith534986f2012-04-14 00:33:13 +0000241 return ParseCXXTryBlock();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000242
243 case tok::kw___try:
Richard Smith534986f2012-04-14 00:33:13 +0000244 ProhibitAttributes(Attrs); // TODO: is it correct?
245 return ParseSEHTryBlock();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000246
247 case tok::annot_pragma_vis:
Richard Smith534986f2012-04-14 00:33:13 +0000248 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000249 HandlePragmaVisibility();
250 return StmtEmpty();
251
252 case tok::annot_pragma_pack:
Richard Smith534986f2012-04-14 00:33:13 +0000253 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000254 HandlePragmaPack();
255 return StmtEmpty();
Eli Friedman9595c7e2012-10-04 02:36:51 +0000256
257 case tok::annot_pragma_fp_contract:
258 ProhibitAttributes(Attrs);
259 HandlePragmaFPContract();
260 return StmtEmpty();
261
262 case tok::annot_pragma_opencl_extension:
263 ProhibitAttributes(Attrs);
264 HandlePragmaOpenCLExtension();
265 return StmtEmpty();
Sebastian Redla0fd8652008-12-21 16:41:36 +0000266 }
267
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 // If we reached this code, the statement must end in a semicolon.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000269 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 ConsumeToken();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000271 } else if (!Res.isInvalid()) {
Chris Lattner7b3684a2009-06-14 00:23:56 +0000272 // If the result was valid, then we do want to diagnose this. Use
273 // ExpectAndConsume to emit the diagnostic, even though we know it won't
274 // succeed.
275 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner19504402008-11-13 18:52:53 +0000276 // Skip until we see a } or ;, but don't eat it.
277 SkipUntil(tok::r_brace, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 }
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000280 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000281}
282
Douglas Gregor312eadb2011-04-24 05:37:28 +0000283/// \brief Parse an expression statement.
Richard Smith534986f2012-04-14 00:33:13 +0000284StmtResult Parser::ParseExprStatement() {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000285 // If a case keyword is missing, this is where it should be inserted.
286 Token OldToken = Tok;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000287
Douglas Gregor312eadb2011-04-24 05:37:28 +0000288 // expression[opt] ';'
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000289 ExprResult Expr(ParseExpression());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000290 if (Expr.isInvalid()) {
291 // If the expression is invalid, skip ahead to the next semicolon or '}'.
292 // Not doing this opens us up to the possibility of infinite loops if
293 // ParseExpression does not consume any tokens.
294 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
295 if (Tok.is(tok::semi))
296 ConsumeToken();
297 return StmtError();
298 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000299
Douglas Gregor312eadb2011-04-24 05:37:28 +0000300 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
301 Actions.CheckCaseExpression(Expr.get())) {
302 // If a constant expression is followed by a colon inside a switch block,
303 // suggest a missing case keyword.
304 Diag(OldToken, diag::err_expected_case_before_expression)
305 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000306
Douglas Gregor312eadb2011-04-24 05:37:28 +0000307 // Recover parsing as a case statement.
Richard Smith534986f2012-04-14 00:33:13 +0000308 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000309 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000310
Douglas Gregor312eadb2011-04-24 05:37:28 +0000311 // Otherwise, eat the semicolon.
312 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
313 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
John Wiegley28bbe4b2011-04-28 01:08:34 +0000314}
Douglas Gregor312eadb2011-04-24 05:37:28 +0000315
Richard Smith534986f2012-04-14 00:33:13 +0000316StmtResult Parser::ParseSEHTryBlock() {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000317 assert(Tok.is(tok::kw___try) && "Expected '__try'");
318 SourceLocation Loc = ConsumeToken();
319 return ParseSEHTryBlockCommon(Loc);
320}
321
322/// ParseSEHTryBlockCommon
323///
324/// seh-try-block:
325/// '__try' compound-statement seh-handler
326///
327/// seh-handler:
328/// seh-except-block
329/// seh-finally-block
330///
331StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
332 if(Tok.isNot(tok::l_brace))
333 return StmtError(Diag(Tok,diag::err_expected_lbrace));
334
Joao Matos568ba872012-09-04 17:49:35 +0000335 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000336 if(TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000337 return TryBlock;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000338
339 StmtResult Handler;
Richard Smith534986f2012-04-14 00:33:13 +0000340 if (Tok.is(tok::identifier) &&
Douglas Gregorb57791e2011-10-21 03:57:52 +0000341 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000342 SourceLocation Loc = ConsumeToken();
343 Handler = ParseSEHExceptBlock(Loc);
344 } else if (Tok.is(tok::kw___finally)) {
345 SourceLocation Loc = ConsumeToken();
346 Handler = ParseSEHFinallyBlock(Loc);
347 } else {
348 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
349 }
350
351 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000352 return Handler;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000353
354 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
355 TryLoc,
356 TryBlock.take(),
357 Handler.take());
358}
359
360/// ParseSEHExceptBlock - Handle __except
361///
362/// seh-except-block:
363/// '__except' '(' seh-filter-expression ')' compound-statement
364///
365StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
366 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
367 raii2(Ident___exception_code, false),
368 raii3(Ident_GetExceptionCode, false);
369
370 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
371 return StmtError();
372
373 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
374
David Blaikie4e4d0842012-03-11 07:00:24 +0000375 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000376 Ident__exception_info->setIsPoisoned(false);
377 Ident___exception_info->setIsPoisoned(false);
378 Ident_GetExceptionInfo->setIsPoisoned(false);
379 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000380 ExprResult FilterExpr(ParseExpression());
Francois Pichetd7f02df2011-04-28 03:14:31 +0000381
David Blaikie4e4d0842012-03-11 07:00:24 +0000382 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000383 Ident__exception_info->setIsPoisoned(true);
384 Ident___exception_info->setIsPoisoned(true);
385 Ident_GetExceptionInfo->setIsPoisoned(true);
386 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000387
388 if(FilterExpr.isInvalid())
389 return StmtError();
390
391 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
392 return StmtError();
393
Richard Smith534986f2012-04-14 00:33:13 +0000394 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000395
396 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000397 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000398
399 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
400}
401
402/// ParseSEHFinallyBlock - Handle __finally
403///
404/// seh-finally-block:
405/// '__finally' compound-statement
406///
407StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
408 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
409 raii2(Ident___abnormal_termination, false),
410 raii3(Ident_AbnormalTermination, false);
411
Richard Smith534986f2012-04-14 00:33:13 +0000412 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000413 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000414 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000415
416 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000417}
418
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000419/// ParseLabeledStatement - We have an identifier and a ':' after it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000420///
421/// labeled-statement:
422/// identifier ':' statement
423/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000424///
Richard Smith534986f2012-04-14 00:33:13 +0000425StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000426 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
427 "Not an identifier!");
428
429 Token IdentTok = Tok; // Save the whole token.
430 ConsumeToken(); // eat the identifier.
431
432 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000433
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000434 // identifier ':' statement
435 SourceLocation ColonLoc = ConsumeToken();
436
Richard Smith534986f2012-04-14 00:33:13 +0000437 // Read label attributes, if present. attrs will contain both C++11 and GNU
438 // attributes (if present) after this point.
John McCall7f040a92010-12-24 02:08:15 +0000439 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000440
John McCall60d7b3a2010-08-24 06:29:42 +0000441 StmtResult SubStmt(ParseStatement());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000442
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000443 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000444 if (SubStmt.isInvalid())
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000445 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000446
Chris Lattner337e5502011-02-18 01:27:55 +0000447 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
448 IdentTok.getLocation());
Richard Smith534986f2012-04-14 00:33:13 +0000449 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattner337e5502011-02-18 01:27:55 +0000450 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smith534986f2012-04-14 00:33:13 +0000451 attrs.clear();
452 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000453
Chris Lattner337e5502011-02-18 01:27:55 +0000454 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
455 SubStmt.get());
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000456}
Reid Spencer5f016e22007-07-11 17:01:13 +0000457
458/// ParseCaseStatement
459/// labeled-statement:
460/// 'case' constant-expression ':' statement
461/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
462///
Richard Smith534986f2012-04-14 00:33:13 +0000463StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smith46f11102011-04-21 22:48:40 +0000464 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattner24e1e702009-03-04 04:23:07 +0000466 // It is very very common for code to contain many case statements recursively
467 // nested, as in (but usually without indentation):
468 // case 1:
469 // case 2:
470 // case 3:
471 // case 4:
472 // case 5: etc.
473 //
474 // Parsing this naively works, but is both inefficient and can cause us to run
475 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner26140c62009-03-04 18:24:58 +0000476 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner24e1e702009-03-04 04:23:07 +0000477 // but all the grossness is constrained to ParseCaseStatement (and some
478 // wierdness in the actions), so this is just local grossness :).
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner24e1e702009-03-04 04:23:07 +0000480 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
481 // example above.
John McCall60d7b3a2010-08-24 06:29:42 +0000482 StmtResult TopLevelCase(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Chris Lattner24e1e702009-03-04 04:23:07 +0000484 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
485 // gets updated each time a new case is parsed, and whose body is unset so
486 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieub2fc6902011-09-09 02:16:15 +0000487 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattner24e1e702009-03-04 04:23:07 +0000489 // While we have case statements, eat and stack them.
David Majnemer0e1e69c2011-06-13 05:50:12 +0000490 SourceLocation ColonLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000491 do {
Richard Trieubb9b80c2011-04-21 21:44:26 +0000492 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
493 ConsumeToken(); // eat the 'case'.
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000495 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000496 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000497 cutOffParsing();
498 return StmtError();
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000499 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000500
Chris Lattner6fb09c82009-12-10 00:38:54 +0000501 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
502 /// Disable this form of error recovery while we're parsing the case
503 /// expression.
504 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000505
Richard Trieubb9b80c2011-04-21 21:44:26 +0000506 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
507 MissingCase = false;
Chris Lattner24e1e702009-03-04 04:23:07 +0000508 if (LHS.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 SkipUntil(tok::colon);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000510 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000512
Chris Lattner24e1e702009-03-04 04:23:07 +0000513 // GNU case range extension.
514 SourceLocation DotDotDotLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000515 ExprResult RHS;
Chris Lattner24e1e702009-03-04 04:23:07 +0000516 if (Tok.is(tok::ellipsis)) {
517 Diag(Tok, diag::ext_gnu_case_range);
518 DotDotDotLoc = ConsumeToken();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000519
Chris Lattner24e1e702009-03-04 04:23:07 +0000520 RHS = ParseConstantExpression();
521 if (RHS.isInvalid()) {
522 SkipUntil(tok::colon);
523 return StmtError();
524 }
525 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000526
Chris Lattner6fb09c82009-12-10 00:38:54 +0000527 ColonProtection.restore();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000528
John McCallf6a3ab02011-01-22 09:28:32 +0000529 if (Tok.is(tok::colon)) {
530 ColonLoc = ConsumeToken();
531
532 // Treat "case blah;" as a typo for "case blah:".
533 } else if (Tok.is(tok::semi)) {
534 ColonLoc = ConsumeToken();
535 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
536 << FixItHint::CreateReplacement(ColonLoc, ":");
537 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000538 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
539 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
540 << FixItHint::CreateInsertion(ExpectedLoc, ":");
541 ColonLoc = ExpectedLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000542 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000543
John McCall60d7b3a2010-08-24 06:29:42 +0000544 StmtResult Case =
John McCall9ae2f072010-08-23 23:25:46 +0000545 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
546 RHS.get(), ColonLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Chris Lattner24e1e702009-03-04 04:23:07 +0000548 // If we had a sema error parsing this case, then just ignore it and
549 // continue parsing the sub-stmt.
550 if (Case.isInvalid()) {
551 if (TopLevelCase.isInvalid()) // No parsed case stmts.
552 return ParseStatement();
553 // Otherwise, just don't add it as a nested case.
554 } else {
555 // If this is the first case statement we parsed, it becomes TopLevelCase.
556 // Otherwise we link it into the current chain.
John McCallca0408f2010-08-23 06:44:23 +0000557 Stmt *NextDeepest = Case.get();
Chris Lattner24e1e702009-03-04 04:23:07 +0000558 if (TopLevelCase.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000559 TopLevelCase = Case;
Chris Lattner24e1e702009-03-04 04:23:07 +0000560 else
John McCall9ae2f072010-08-23 23:25:46 +0000561 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner24e1e702009-03-04 04:23:07 +0000562 DeepestParsedCaseStmt = NextDeepest;
563 }
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chris Lattner24e1e702009-03-04 04:23:07 +0000565 // Handle all case statements.
566 } while (Tok.is(tok::kw_case));
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Chris Lattner24e1e702009-03-04 04:23:07 +0000568 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattner24e1e702009-03-04 04:23:07 +0000570 // If we found a non-case statement, start by parsing it.
John McCall60d7b3a2010-08-24 06:29:42 +0000571 StmtResult SubStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Chris Lattner24e1e702009-03-04 04:23:07 +0000573 if (Tok.isNot(tok::r_brace)) {
574 SubStmt = ParseStatement();
575 } else {
576 // Nicely diagnose the common error "switch (X) { case 4: }", which is
577 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000578 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000579 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
580 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner24e1e702009-03-04 04:23:07 +0000581 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 }
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner24e1e702009-03-04 04:23:07 +0000584 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000585 if (SubStmt.isInvalid())
Chris Lattner24e1e702009-03-04 04:23:07 +0000586 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Chris Lattner24e1e702009-03-04 04:23:07 +0000588 // Install the body into the most deeply-nested case.
John McCall9ae2f072010-08-23 23:25:46 +0000589 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl61364dd2008-12-11 19:30:53 +0000590
Chris Lattner24e1e702009-03-04 04:23:07 +0000591 // Return the top level parsed statement tree.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000592 return TopLevelCase;
Reid Spencer5f016e22007-07-11 17:01:13 +0000593}
594
595/// ParseDefaultStatement
596/// labeled-statement:
597/// 'default' ':' statement
598/// Note that this does not parse the 'statement' at the end.
599///
Richard Smith534986f2012-04-14 00:33:13 +0000600StmtResult Parser::ParseDefaultStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000601 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
603
Douglas Gregor662a4822010-12-23 22:56:40 +0000604 SourceLocation ColonLoc;
John McCallf6a3ab02011-01-22 09:28:32 +0000605 if (Tok.is(tok::colon)) {
606 ColonLoc = ConsumeToken();
607
608 // Treat "default;" as a typo for "default:".
609 } else if (Tok.is(tok::semi)) {
610 ColonLoc = ConsumeToken();
611 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
612 << FixItHint::CreateReplacement(ColonLoc, ":");
613 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000614 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
615 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
616 << FixItHint::CreateInsertion(ExpectedLoc, ":");
617 ColonLoc = ExpectedLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000619
Richard Smith85b29a42012-02-17 01:35:32 +0000620 StmtResult SubStmt;
621
622 if (Tok.isNot(tok::r_brace)) {
623 SubStmt = ParseStatement();
624 } else {
625 // Diagnose the common error "switch (X) {... default: }", which is
626 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000627 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000628 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
629 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
630 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 }
632
Richard Smith85b29a42012-02-17 01:35:32 +0000633 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000634 if (SubStmt.isInvalid())
Richard Smith85b29a42012-02-17 01:35:32 +0000635 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000636
Sebastian Redl117054a2008-12-28 16:13:43 +0000637 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000638 SubStmt.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +0000639}
640
Richard Smith534986f2012-04-14 00:33:13 +0000641StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
642 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregorbca01b42011-07-06 22:04:06 +0000643}
Reid Spencer5f016e22007-07-11 17:01:13 +0000644
645/// ParseCompoundStatement - Parse a "{}" block.
646///
647/// compound-statement: [C99 6.8.2]
648/// { block-item-list[opt] }
649/// [GNU] { label-declarations block-item-list } [TODO]
650///
651/// block-item-list:
652/// block-item
653/// block-item-list block-item
654///
655/// block-item:
656/// declaration
Chris Lattner45a566c2007-08-27 01:01:57 +0000657/// [GNU] '__extension__' declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000658/// statement
659/// [OMP] openmp-directive [TODO]
660///
661/// [GNU] label-declarations:
662/// [GNU] label-declaration
663/// [GNU] label-declarations label-declaration
664///
665/// [GNU] label-declaration:
666/// [GNU] '__label__' identifier-list ';'
667///
668/// [OMP] openmp-directive: [TODO]
669/// [OMP] barrier-directive
670/// [OMP] flush-directive
671///
Richard Smith534986f2012-04-14 00:33:13 +0000672StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000673 unsigned ScopeFlags) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000674 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000675
Chris Lattner31e05722007-08-26 06:24:45 +0000676 // Enter a scope to hold everything within the compound stmt. Compound
677 // statements can always hold declarations.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000678 ParseScope CompoundScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000679
680 // Parse the statements in the body.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000681 return ParseCompoundStatementBody(isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000682}
683
Reid Spencer5f016e22007-07-11 17:01:13 +0000684/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff1b273c42007-09-16 14:56:35 +0000685/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Reid Spencer5f016e22007-07-11 17:01:13 +0000686/// consume the '}' at the end of the block. It does not manipulate the scope
687/// stack.
John McCall60d7b3a2010-08-24 06:29:42 +0000688StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump1eb44332009-09-09 15:08:12 +0000689 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerae50fa02009-03-05 00:00:31 +0000690 Tok.getLocation(),
691 "in compound statement ('{}')");
Lang Hamesbe9af122012-10-02 04:45:10 +0000692
693 // Record the state of the FP_CONTRACT pragma, restore on leaving the
694 // compound statement.
695 Sema::FPContractStateRAII SaveFPContractState(Actions);
696
Douglas Gregor0fbda682010-09-15 14:51:05 +0000697 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000698 BalancedDelimiterTracker T(*this, tok::l_brace);
699 if (T.consumeOpen())
700 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000701
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000702 Sema::CompoundScopeRAII CompoundScope(Actions);
703
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +0000704 StmtVector Stmts;
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000705
Chris Lattner4ae493c2011-02-18 02:08:43 +0000706 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
707 // only allowed at the start of a compound stmt regardless of the language.
708 while (Tok.is(tok::kw___label__)) {
709 SourceLocation LabelLoc = ConsumeToken();
710 Diag(LabelLoc, diag::ext_gnu_local_label);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000711
Chris Lattner5f9e2722011-07-23 10:55:15 +0000712 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000713 while (1) {
714 if (Tok.isNot(tok::identifier)) {
715 Diag(Tok, diag::err_expected_ident);
716 break;
717 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000718
Chris Lattner4ae493c2011-02-18 02:08:43 +0000719 IdentifierInfo *II = Tok.getIdentifierInfo();
720 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara67843042011-03-05 18:21:20 +0000721 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000722
Chris Lattner4ae493c2011-02-18 02:08:43 +0000723 if (!Tok.is(tok::comma))
724 break;
725 ConsumeToken();
726 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000727
John McCall0b7e6782011-03-24 11:26:52 +0000728 DeclSpec DS(AttrFactory);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000729 DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
730 DeclsInGroup.data(), DeclsInGroup.size());
731 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000732
Chris Lattner8bb21d32012-04-28 16:12:17 +0000733 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000734 if (R.isUsable())
735 Stmts.push_back(R.release());
736 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000737
Chris Lattner4ae493c2011-02-18 02:08:43 +0000738 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000739 if (Tok.is(tok::annot_pragma_unused)) {
740 HandlePragmaUnused();
741 continue;
742 }
743
David Blaikie4e4d0842012-03-11 07:00:24 +0000744 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet1e862692011-05-06 20:48:22 +0000745 Tok.is(tok::kw___if_not_exists))) {
746 ParseMicrosoftIfExistsStatement(Stmts);
747 continue;
748 }
749
John McCall60d7b3a2010-08-24 06:29:42 +0000750 StmtResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000751 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000752 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattner45a566c2007-08-27 01:01:57 +0000753 } else {
754 // __extension__ can start declarations and it can also be a unary
755 // operator for expressions. Consume multiple __extension__ markers here
756 // until we can determine which is which.
Eli Friedmanadf077f2009-01-27 08:43:38 +0000757 // FIXME: This loses extension expressions in the AST!
Chris Lattner45a566c2007-08-27 01:01:57 +0000758 SourceLocation ExtLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000759 while (Tok.is(tok::kw___extension__))
Chris Lattner45a566c2007-08-27 01:01:57 +0000760 ConsumeToken();
Chris Lattner39146d62008-10-20 06:51:33 +0000761
John McCall0b7e6782011-03-24 11:26:52 +0000762 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith6ee326a2012-04-10 01:32:12 +0000763 MaybeParseCXX0XAttributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000764
Chris Lattner45a566c2007-08-27 01:01:57 +0000765 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis5404a152008-10-05 00:06:24 +0000766 if (isDeclarationStatement()) {
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000767 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner97144fc2009-04-02 04:16:50 +0000768 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000769 ExtensionRAIIObject O(Diags);
770
Chris Lattner97144fc2009-04-02 04:16:50 +0000771 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000772 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
773 Declarator::BlockContext, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000774 attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000775 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattner45a566c2007-08-27 01:01:57 +0000776 } else {
Eli Friedmanadf077f2009-01-27 08:43:38 +0000777 // Otherwise this was a unary __extension__ marker.
John McCall60d7b3a2010-08-24 06:29:42 +0000778 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattner043a0b52008-03-13 06:32:11 +0000779
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000780 if (Res.isInvalid()) {
Chris Lattner45a566c2007-08-27 01:01:57 +0000781 SkipUntil(tok::semi);
782 continue;
783 }
Sebastian Redlf512e822009-01-18 18:03:53 +0000784
Sean Huntbbd37c62009-11-21 08:43:09 +0000785 // FIXME: Use attributes?
Chris Lattner39146d62008-10-20 06:51:33 +0000786 // Eat the semicolon at the end of stmt and convert the expr into a
787 // statement.
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000788 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
John McCall9ae2f072010-08-23 23:25:46 +0000789 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
Chris Lattner45a566c2007-08-27 01:01:57 +0000790 }
791 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000792
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000793 if (R.isUsable())
Sebastian Redleffa8d12008-12-10 00:02:53 +0000794 Stmts.push_back(R.release());
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000796
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000797 SourceLocation CloseLoc = Tok.getLocation();
798
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 // We broke out of the while loop because we found a '}' or EOF.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000800 if (Tok.isNot(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 Diag(Tok, diag::err_expected_rbrace);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000802 Diag(T.getOpenLocation(), diag::note_matching) << "{";
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000803 // Recover by creating a compound statement with what we parsed so far,
804 // instead of dropping everything and returning StmtError();
805 } else {
806 if (!T.consumeClose())
807 CloseLoc = T.getCloseLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000809
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000810 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000811 Stmts, isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000812}
813
Chris Lattner15ff1112008-12-12 06:31:07 +0000814/// ParseParenExprOrCondition:
815/// [C ] '(' expression ')'
Chris Lattnerff871fb2008-12-12 06:35:28 +0000816/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattner15ff1112008-12-12 06:31:07 +0000817///
818/// This function parses and performs error recovery on the specified condition
819/// or expression (depending on whether we're in C++ or C mode). This function
820/// goes out of its way to recover well. It returns true if there was a parser
821/// error (the right paren couldn't be found), which indicates that the caller
822/// should try to recover harder. It returns false if the condition is
823/// successfully parsed. Note that a successful parse can still have semantic
824/// errors in the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000825bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCalld226f652010-08-21 09:40:31 +0000826 Decl *&DeclResult,
Douglas Gregor586596f2010-05-06 17:25:47 +0000827 SourceLocation Loc,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000828 bool ConvertToBoolean) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000829 BalancedDelimiterTracker T(*this, tok::l_paren);
830 T.consumeOpen();
831
David Blaikie4e4d0842012-03-11 07:00:24 +0000832 if (getLangOpts().CPlusPlus)
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000833 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000834 else {
835 ExprResult = ParseExpression();
John McCalld226f652010-08-21 09:40:31 +0000836 DeclResult = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000837
Douglas Gregor586596f2010-05-06 17:25:47 +0000838 // If required, convert to a boolean value.
839 if (!ExprResult.isInvalid() && ConvertToBoolean)
840 ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000841 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000842 }
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Chris Lattner15ff1112008-12-12 06:31:07 +0000844 // If the parser was confused by the condition and we don't have a ')', try to
845 // recover by skipping ahead to a semi and bailing out. If condexp is
846 // semantically invalid but we have well formed code, keep going.
John McCalld226f652010-08-21 09:40:31 +0000847 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattner15ff1112008-12-12 06:31:07 +0000848 SkipUntil(tok::semi);
849 // Skipping may have stopped if it found the containing ')'. If so, we can
850 // continue parsing the if statement.
851 if (Tok.isNot(tok::r_paren))
852 return true;
853 }
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Chris Lattner15ff1112008-12-12 06:31:07 +0000855 // Otherwise the condition is valid or the rparen is present.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000856 T.consumeClose();
Chad Rosierb6604462012-07-10 21:35:27 +0000857
Chris Lattnerbddc7e52012-04-28 16:24:20 +0000858 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
859 // that all callers are looking for a statement after the condition, so ")"
860 // isn't valid.
861 while (Tok.is(tok::r_paren)) {
862 Diag(Tok, diag::err_extraneous_rparen_in_condition)
863 << FixItHint::CreateRemoval(Tok.getLocation());
864 ConsumeParen();
865 }
Chad Rosierb6604462012-07-10 21:35:27 +0000866
Chris Lattner15ff1112008-12-12 06:31:07 +0000867 return false;
868}
869
870
Reid Spencer5f016e22007-07-11 17:01:13 +0000871/// ParseIfStatement
872/// if-statement: [C99 6.8.4.1]
873/// 'if' '(' expression ')' statement
874/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000875/// [C++] 'if' '(' condition ')' statement
876/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +0000877///
Richard Smith534986f2012-04-14 00:33:13 +0000878StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000879 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
881
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000882 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000883 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000885 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000887
David Blaikie4e4d0842012-03-11 07:00:24 +0000888 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000889
Chris Lattner22153252007-08-26 23:08:06 +0000890 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
891 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000892 //
893 // C++ 6.4p3:
894 // A name introduced by a declaration in a condition is in scope from its
895 // point of declaration until the end of the substatements controlled by the
896 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +0000897 // C++ 3.3.2p4:
898 // Names declared in the for-init-statement, and in the condition of if,
899 // while, for, and switch statements are local to the if, while, for, or
900 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000901 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000902 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +0000903
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000905 ExprResult CondExp;
John McCalld226f652010-08-21 09:40:31 +0000906 Decl *CondVar = 0;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000907 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +0000908 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +0000909
David Blaikiedef07622012-05-16 04:20:04 +0000910 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Chris Lattner0ecea032007-08-22 05:28:50 +0000912 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000913 // there is no compound stmt. C90 does not have this clause. We only do this
914 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000915 //
916 // C++ 6.4p1:
917 // The substatement in a selection-statement (each substatement, in the else
918 // form of the if statement) implicitly defines a local scope.
919 //
920 // For C++ we create a scope for the condition and a new scope for
921 // substatements because:
922 // -When the 'then' scope exits, we want the condition declaration to still be
923 // active for the 'else' scope too.
924 // -Sema will detect name clashes by considering declarations of a
925 // 'ControlScope' as part of its direct subscope.
926 // -If we wanted the condition and substatement to be in the same scope, we
927 // would have to notify ParseStatement not to create a new scope. It's
928 // simpler to let it create a new scope.
929 //
Mike Stump1eb44332009-09-09 15:08:12 +0000930 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000931 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000932
Chris Lattnerb96728d2007-10-29 05:08:52 +0000933 // Read the 'then' stmt.
934 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +0000935
936 SourceLocation InnerStatementTrailingElseLoc;
937 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000938
Chris Lattnera36ce712007-08-22 05:16:28 +0000939 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000940 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000941
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 // If it has an else, parse it.
943 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +0000944 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000945 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000946
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000947 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +0000948 if (TrailingElseLoc)
949 *TrailingElseLoc = Tok.getLocation();
950
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +0000952 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000953
Chris Lattner0ecea032007-08-22 05:28:50 +0000954 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000955 // there is no compound stmt. C90 does not have this clause. We only do
956 // this if the body isn't a compound statement to avoid push/pop in common
957 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000958 //
959 // C++ 6.4p1:
960 // The substatement in a selection-statement (each substatement, in the else
961 // form of the if statement) implicitly defines a local scope.
962 //
Sebastian Redl61364dd2008-12-11 19:30:53 +0000963 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000964 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000965
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000967
Chris Lattnera36ce712007-08-22 05:16:28 +0000968 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000969 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +0000970 } else if (Tok.is(tok::code_completion)) {
971 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000972 cutOffParsing();
973 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +0000974 } else if (InnerStatementTrailingElseLoc.isValid()) {
975 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000977
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000978 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chris Lattner18914bc2008-12-12 06:19:11 +0000980 // If the condition was invalid, discard the if statement. We could recover
981 // better by replacing it with a valid expr, but don't do that yet.
John McCalld226f652010-08-21 09:40:31 +0000982 if (CondExp.isInvalid() && !CondVar)
Chris Lattner18914bc2008-12-12 06:19:11 +0000983 return StmtError();
Chris Lattner22153252007-08-26 23:08:06 +0000984
Chris Lattnerb96728d2007-10-29 05:08:52 +0000985 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +0000986 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +0000987 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000988 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
989 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
990 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +0000991 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000992 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +0000993 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000994
Chris Lattnerb96728d2007-10-29 05:08:52 +0000995 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000996 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +0000997 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000998 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +0000999 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001000
John McCall9ae2f072010-08-23 23:25:46 +00001001 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001002 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001003}
1004
1005/// ParseSwitchStatement
1006/// switch-statement:
1007/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001008/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001009StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001010 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1012
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001013 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001014 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001016 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 }
Chris Lattner22153252007-08-26 23:08:06 +00001018
David Blaikie4e4d0842012-03-11 07:00:24 +00001019 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001020
Chris Lattner22153252007-08-26 23:08:06 +00001021 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1022 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001023 //
1024 // C++ 6.4p3:
1025 // A name introduced by a declaration in a condition is in scope from its
1026 // point of declaration until the end of the substatements controlled by the
1027 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001028 // C++ 3.3.2p4:
1029 // Names declared in the for-init-statement, and in the condition of if,
1030 // while, for, and switch statements are local to the if, while, for, or
1031 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001032 //
Richard Trieubb9b80c2011-04-21 21:44:26 +00001033 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001034 if (C99orCXX)
1035 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001036 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001037
1038 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001039 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001040 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001041 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001042 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001043
John McCall60d7b3a2010-08-24 06:29:42 +00001044 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001045 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001046
Douglas Gregor586596f2010-05-06 17:25:47 +00001047 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001048 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001049 // FIXME: This is not optimal recovery, but parsing the body is more
1050 // dangerous due to the presence of case and default statements, which
1051 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001052 if (Tok.is(tok::l_brace)) {
1053 ConsumeBrace();
1054 SkipUntil(tok::r_brace, false, false);
1055 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001056 SkipUntil(tok::semi);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001057 return Switch;
Douglas Gregor586596f2010-05-06 17:25:47 +00001058 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001059
Chris Lattner0ecea032007-08-22 05:28:50 +00001060 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001061 // there is no compound stmt. C90 does not have this clause. We only do this
1062 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001063 //
1064 // C++ 6.4p1:
1065 // The substatement in a selection-statement (each substatement, in the else
1066 // form of the if statement) implicitly defines a local scope.
1067 //
1068 // See comments in ParseIfStatement for why we create a scope for the
1069 // condition and a new scope for substatement in C++.
1070 //
Mike Stump1eb44332009-09-09 15:08:12 +00001071 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001072 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001075 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001076
Chris Lattner7e52de42010-01-24 01:50:29 +00001077 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001078 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001079 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001080
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001081 if (Body.isInvalid()) {
Chris Lattner7e52de42010-01-24 01:50:29 +00001082 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001083
1084 // Put the synthesized null statement on the same line as the end of switch
1085 // condition.
1086 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1087 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1088 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001089
John McCall9ae2f072010-08-23 23:25:46 +00001090 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001091}
1092
1093/// ParseWhileStatement
1094/// while-statement: [C99 6.8.5.1]
1095/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001096/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001097StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001098 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 SourceLocation WhileLoc = Tok.getLocation();
1100 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001101
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001102 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001103 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001104 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001105 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001107
David Blaikie4e4d0842012-03-11 07:00:24 +00001108 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001109
Chris Lattner22153252007-08-26 23:08:06 +00001110 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1111 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001112 //
1113 // C++ 6.4p3:
1114 // A name introduced by a declaration in a condition is in scope from its
1115 // point of declaration until the end of the substatements controlled by the
1116 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001117 // C++ 3.3.2p4:
1118 // Names declared in the for-init-statement, and in the condition of if,
1119 // while, for, and switch statements are local to the if, while, for, or
1120 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001121 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001122 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001123 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001124 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1125 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001126 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001127 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1128 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001129
1130 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001131 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001132 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001133 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001134 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001135
David Blaikiedef07622012-05-16 04:20:04 +00001136 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Chris Lattner0ecea032007-08-22 05:28:50 +00001138 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001139 // there is no compound stmt. C90 does not have this clause. We only do this
1140 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001141 //
1142 // C++ 6.5p2:
1143 // The substatement in an iteration-statement implicitly defines a local scope
1144 // which is entered and exited each time through the loop.
1145 //
1146 // See comments in ParseIfStatement for why we create a scope for the
1147 // condition and a new scope for substatement in C++.
1148 //
Mike Stump1eb44332009-09-09 15:08:12 +00001149 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001150 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001151
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001153 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001154
Chris Lattner0ecea032007-08-22 05:28:50 +00001155 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001156 InnerScope.Exit();
1157 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001158
John McCalld226f652010-08-21 09:40:31 +00001159 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001160 return StmtError();
1161
John McCall9ae2f072010-08-23 23:25:46 +00001162 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001163}
1164
1165/// ParseDoStatement
1166/// do-statement: [C99 6.8.5.2]
1167/// 'do' statement 'while' '(' expression ')' ';'
1168/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001169StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001170 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001172
Chris Lattner22153252007-08-26 23:08:06 +00001173 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1174 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001175 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001176 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001177 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001178 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001179 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001180
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001181 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001182
Chris Lattner0ecea032007-08-22 05:28:50 +00001183 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001184 // there is no compound stmt. C90 does not have this clause. We only do this
1185 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001186 //
1187 // C++ 6.5p2:
1188 // The substatement in an iteration-statement implicitly defines a local scope
1189 // which is entered and exited each time through the loop.
1190 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001191 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikie4e4d0842012-03-11 07:00:24 +00001192 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001193 Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001196 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001197
Chris Lattner0ecea032007-08-22 05:28:50 +00001198 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001199 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001200
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001201 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001202 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001203 Diag(Tok, diag::err_expected_while);
Chris Lattner28eb7e92008-11-23 23:17:07 +00001204 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner19504402008-11-13 18:52:53 +00001205 SkipUntil(tok::semi, false, true);
1206 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001207 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 }
1209 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001210
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001211 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001212 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner19504402008-11-13 18:52:53 +00001213 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001214 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001216
Chris Lattnerff871fb2008-12-12 06:35:28 +00001217 // Parse the parenthesized condition.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001218 BalancedDelimiterTracker T(*this, tok::l_paren);
1219 T.consumeOpen();
Chad Rosierb6604462012-07-10 21:35:27 +00001220
Sean Hunt2edf0a22012-06-23 05:07:58 +00001221 // FIXME: Do not just parse the attribute contents and throw them away
1222 ParsedAttributesWithRange attrs(AttrFactory);
1223 MaybeParseCXX0XAttributes(attrs);
1224 ProhibitAttributes(attrs);
1225
John McCall60d7b3a2010-08-24 06:29:42 +00001226 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001227 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001228 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001229
Sebastian Redl9a920342008-12-11 19:48:14 +00001230 if (Cond.isInvalid() || Body.isInvalid())
1231 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001232
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001233 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1234 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001235}
1236
1237/// ParseForStatement
1238/// for-statement: [C99 6.8.5.3]
1239/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1240/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001241/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1242/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001243/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001244/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1245/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001246///
1247/// [C++] for-init-statement:
1248/// [C++] expression-statement
1249/// [C++] simple-declaration
1250///
Richard Smithad762fc2011-04-14 22:09:26 +00001251/// [C++0x] for-range-declaration:
1252/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1253/// [C++0x] for-range-initializer:
1254/// [C++0x] expression
1255/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001256StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001257 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001259
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001260 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001261 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001263 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001265
Chad Rosierb6604462012-07-10 21:35:27 +00001266 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1267 getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001268
Chris Lattner22153252007-08-26 23:08:06 +00001269 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1270 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001271 //
1272 // C++ 6.4p3:
1273 // A name introduced by a declaration in a condition is in scope from its
1274 // point of declaration until the end of the substatements controlled by the
1275 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001276 // C++ 3.3.2p4:
1277 // Names declared in the for-init-statement, and in the condition of if,
1278 // while, for, and switch statements are local to the if, while, for, or
1279 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001280 // C++ 6.5.3p1:
1281 // Names declared in the for-init-statement are in the same declarative-region
1282 // as those declared in the condition.
1283 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001284 unsigned ScopeFlags;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001285 if (C99orCXXorObjC)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001286 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1287 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001288 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001289 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1290
1291 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001292
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001293 BalancedDelimiterTracker T(*this, tok::l_paren);
1294 T.consumeOpen();
1295
John McCall60d7b3a2010-08-24 06:29:42 +00001296 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001297
Richard Smithad762fc2011-04-14 22:09:26 +00001298 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001299 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001300 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001301 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001302 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001303 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001304 FullExprArg ThirdPart(Actions);
John McCalld226f652010-08-21 09:40:31 +00001305 Decl *SecondVar = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001306
Douglas Gregor791215b2009-09-21 20:51:25 +00001307 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001308 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001309 C99orCXXorObjC? Sema::PCC_ForInit
1310 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001311 cutOffParsing();
1312 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001313 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001314
Sean Hunt2edf0a22012-06-23 05:07:58 +00001315 ParsedAttributesWithRange attrs(AttrFactory);
1316 MaybeParseCXX0XAttributes(attrs);
1317
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001319 if (Tok.is(tok::semi)) { // for (;
Sean Hunt2edf0a22012-06-23 05:07:58 +00001320 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 // no first part, eat the ';'.
1322 ConsumeToken();
Eli Friedman9490ab42011-12-20 01:50:37 +00001323 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001325 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001327
John McCall0b7e6782011-03-24 11:26:52 +00001328 ParsedAttributesWithRange attrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +00001329 MaybeParseCXX0XAttributes(attrs);
Sean Huntbbd37c62009-11-21 08:43:09 +00001330
Richard Smithad762fc2011-04-14 22:09:26 +00001331 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001332 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001333 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1334
Chris Lattner97144fc2009-04-02 04:16:50 +00001335 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001336 StmtVector Stmts;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001337 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smithad762fc2011-04-14 22:09:26 +00001338 DeclEnd, attrs, false,
1339 MightBeForRangeStmt ?
1340 &ForRangeInit : 0);
Chris Lattnercd147752009-03-29 17:27:48 +00001341 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Richard Smithad762fc2011-04-14 22:09:26 +00001343 if (ForRangeInit.ParsedForRangeDecl()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001344 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001345 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001346
Richard Smithad762fc2011-04-14 22:09:26 +00001347 ForRange = true;
1348 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001349 ConsumeToken();
1350 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001351 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001352 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001353 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001354
Douglas Gregorfb629412010-08-23 21:17:50 +00001355 if (Tok.is(tok::code_completion)) {
1356 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001357 cutOffParsing();
1358 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001359 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001360 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001361 } else {
1362 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001363 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 } else {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001365 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 Value = ParseExpression();
1367
John McCallf6a16482010-12-04 03:47:34 +00001368 ForEach = isTokIdentifier_in();
1369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001371 if (!Value.isInvalid()) {
1372 if (ForEach)
1373 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1374 else
1375 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1376 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001377
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001378 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001380 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001381 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001382
Douglas Gregorfb629412010-08-23 21:17:50 +00001383 if (Tok.is(tok::code_completion)) {
1384 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001385 cutOffParsing();
1386 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001387 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001388 Collection = ParseExpression();
David Blaikie4e4d0842012-03-11 07:00:24 +00001389 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001390 // User tried to write the reasonable, but ill-formed, for-range-statement
1391 // for (expr : expr) { ... }
1392 Diag(Tok, diag::err_for_range_expected_decl)
1393 << FirstPart.get()->getSourceRange();
1394 SkipUntil(tok::r_paren, false, true);
1395 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001396 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001397 if (!Value.isInvalid()) {
1398 Diag(Tok, diag::err_expected_semi_for);
1399 } else {
1400 // Skip until semicolon or rparen, don't consume it.
1401 SkipUntil(tok::r_paren, true, true);
1402 if (Tok.is(tok::semi))
1403 ConsumeToken();
1404 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 }
1406 }
Richard Smithad762fc2011-04-14 22:09:26 +00001407 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001408 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001409 // Parse the second part of the for specifier.
1410 if (Tok.is(tok::semi)) { // for (...;;
1411 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001412 } else if (Tok.is(tok::r_paren)) {
1413 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001414 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001415 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001416 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001417 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1418 else {
1419 Second = ParseExpression();
1420 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001421 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001422 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001423 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001424 SecondPartIsInvalid = Second.isInvalid();
David Blaikiedef07622012-05-16 04:20:04 +00001425 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001426 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001427
Douglas Gregorb72c7782011-02-17 03:38:46 +00001428 if (Tok.isNot(tok::semi)) {
1429 if (!SecondPartIsInvalid || SecondVar)
1430 Diag(Tok, diag::err_expected_semi_for);
1431 else
1432 // Skip until semicolon or rparen, don't consume it.
1433 SkipUntil(tok::r_paren, true, true);
1434 }
1435
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001436 if (Tok.is(tok::semi)) {
1437 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001438 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001439
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001440 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001441 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001442 ExprResult Third = ParseExpression();
John McCall9ae2f072010-08-23 23:25:46 +00001443 ThirdPart = Actions.MakeFullExpr(Third.take());
Douglas Gregor586596f2010-05-06 17:25:47 +00001444 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001446 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001447 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001448
Richard Smithad762fc2011-04-14 22:09:26 +00001449 // We need to perform most of the semantic analysis for a C++0x for-range
1450 // statememt before parsing the body, in order to be able to deduce the type
1451 // of an auto-typed loop variable.
1452 StmtResult ForRangeStmt;
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001453 StmtResult ForEachStmt;
Chad Rosierb6604462012-07-10 21:35:27 +00001454
John McCall990567c2011-07-27 01:07:15 +00001455 if (ForRange) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001456 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smithad762fc2011-04-14 22:09:26 +00001457 ForRangeInit.ColonLoc,
1458 ForRangeInit.RangeExpr.get(),
Richard Smith8b533d92012-09-20 21:52:32 +00001459 T.getCloseLocation(),
1460 Sema::BFRK_Build);
Richard Smithad762fc2011-04-14 22:09:26 +00001461
John McCall990567c2011-07-27 01:07:15 +00001462
1463 // Similarly, we need to do the semantic analysis for a for-range
1464 // statement immediately in order to close over temporaries correctly.
1465 } else if (ForEach) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001466 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001467 FirstPart.take(),
Chad Rosierb6604462012-07-10 21:35:27 +00001468 Collection.take(),
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001469 T.getCloseLocation());
John McCall990567c2011-07-27 01:07:15 +00001470 }
1471
Chris Lattner0ecea032007-08-22 05:28:50 +00001472 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001473 // there is no compound stmt. C90 does not have this clause. We only do this
1474 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001475 //
1476 // C++ 6.5p2:
1477 // The substatement in an iteration-statement implicitly defines a local scope
1478 // which is entered and exited each time through the loop.
1479 //
1480 // See comments in ParseIfStatement for why we create a scope for
1481 // for-init-statement/condition and a new scope for substatement in C++.
1482 //
Mike Stump1eb44332009-09-09 15:08:12 +00001483 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001484 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001487 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001488
Chris Lattner0ecea032007-08-22 05:28:50 +00001489 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001490 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001491
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001493 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001494
1495 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001496 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001497
Richard Smithad762fc2011-04-14 22:09:26 +00001498 if (ForEach)
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001499 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1500 Body.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Richard Smithad762fc2011-04-14 22:09:26 +00001502 if (ForRange)
1503 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1504
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001505 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1506 SecondPart, SecondVar, ThirdPart,
1507 T.getCloseLocation(), Body.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001508}
1509
1510/// ParseGotoStatement
1511/// jump-statement:
1512/// 'goto' identifier ';'
1513/// [GNU] 'goto' '*' expression ';'
1514///
1515/// Note: this lets the caller parse the end ';'.
1516///
Richard Smith534986f2012-04-14 00:33:13 +00001517StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001518 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001520
John McCall60d7b3a2010-08-24 06:29:42 +00001521 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001522 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001523 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1524 Tok.getLocation());
1525 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001527 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // GNU indirect goto extension.
1529 Diag(Tok, diag::ext_gnu_indirect_goto);
1530 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001531 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001532 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001534 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 }
John McCall9ae2f072010-08-23 23:25:46 +00001536 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattner95cfb852007-07-22 04:13:33 +00001537 } else {
1538 Diag(Tok, diag::err_expected_ident);
Sebastian Redl9a920342008-12-11 19:48:14 +00001539 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001541
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001542 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +00001543}
1544
1545/// ParseContinueStatement
1546/// jump-statement:
1547/// 'continue' ';'
1548///
1549/// Note: this lets the caller parse the end ';'.
1550///
Richard Smith534986f2012-04-14 00:33:13 +00001551StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001553 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001554}
1555
1556/// ParseBreakStatement
1557/// jump-statement:
1558/// 'break' ';'
1559///
1560/// Note: this lets the caller parse the end ';'.
1561///
Richard Smith534986f2012-04-14 00:33:13 +00001562StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001564 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001565}
1566
1567/// ParseReturnStatement
1568/// jump-statement:
1569/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001570StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001571 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001573
John McCall60d7b3a2010-08-24 06:29:42 +00001574 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001575 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001576 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001577 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001578 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001579 return StmtError();
1580 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001581
David Blaikie4e4d0842012-03-11 07:00:24 +00001582 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001583 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001584 if (R.isUsable())
David Blaikie4e4d0842012-03-11 07:00:24 +00001585 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001586 diag::warn_cxx98_compat_generalized_initializer_lists :
1587 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001588 << R.get()->getSourceRange();
1589 } else
1590 R = ParseExpression();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001591 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001593 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 }
1595 }
John McCall9ae2f072010-08-23 23:25:46 +00001596 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001597}
1598
Eli Friedman3fedbe12011-09-30 01:13:51 +00001599/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1600/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier8cd64b42012-06-11 20:47:18 +00001601///
1602/// [MS] ms-asm-statement:
1603/// ms-asm-block
1604/// ms-asm-block ms-asm-statement
1605///
1606/// [MS] ms-asm-block:
1607/// '__asm' ms-asm-line '\n'
1608/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1609///
1610/// [MS] ms-asm-instruction-block
1611/// ms-asm-line
1612/// ms-asm-line '\n' ms-asm-instruction-block
1613///
Eli Friedman3fedbe12011-09-30 01:13:51 +00001614StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
Chad Rosier56d7f232012-08-24 21:42:51 +00001615 // MS-style inline assembly is not fully supported, so emit a warning.
1616 Diag(AsmLoc, diag::warn_unsupported_msasm);
1617
Eli Friedman3fedbe12011-09-30 01:13:51 +00001618 SourceManager &SrcMgr = PP.getSourceManager();
1619 SourceLocation EndLoc = AsmLoc;
Chad Rosier8cd64b42012-06-11 20:47:18 +00001620 SmallVector<Token, 4> AsmToks;
Chad Rosier21ef7112012-08-14 19:22:06 +00001621
1622 bool InBraces = false;
1623 unsigned short savedBraceCount = 0;
1624 bool InAsmComment = false;
1625 FileID FID;
1626 unsigned LineNo = 0;
1627 unsigned NumTokensRead = 0;
1628 SourceLocation LBraceLoc;
1629
1630 if (Tok.is(tok::l_brace)) {
1631 // Braced inline asm: consume the opening brace.
1632 InBraces = true;
1633 savedBraceCount = BraceCount;
1634 EndLoc = LBraceLoc = ConsumeBrace();
1635 ++NumTokensRead;
1636 } else {
1637 // Single-line inline asm; compute which line it is on.
1638 std::pair<FileID, unsigned> ExpAsmLoc =
1639 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1640 FID = ExpAsmLoc.first;
1641 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1642 }
1643
1644 SourceLocation TokLoc = Tok.getLocation();
Eli Friedman3fedbe12011-09-30 01:13:51 +00001645 do {
Chad Rosier21ef7112012-08-14 19:22:06 +00001646 // If we hit EOF, we're done, period.
1647 if (Tok.is(tok::eof))
Eli Friedman3fedbe12011-09-30 01:13:51 +00001648 break;
Chad Rosier21ef7112012-08-14 19:22:06 +00001649
Chad Rosier21ef7112012-08-14 19:22:06 +00001650 if (!InAsmComment && Tok.is(tok::semi)) {
1651 // A semicolon in an asm is the start of a comment.
1652 InAsmComment = true;
1653 if (InBraces) {
1654 // Compute which line the comment is on.
1655 std::pair<FileID, unsigned> ExpSemiLoc =
1656 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1657 FID = ExpSemiLoc.first;
1658 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
1659 }
1660 } else if (!InBraces || InAsmComment) {
1661 // If end-of-line is significant, check whether this token is on a
1662 // new line.
1663 std::pair<FileID, unsigned> ExpLoc =
1664 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1665 if (ExpLoc.first != FID ||
1666 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
1667 // If this is a single-line __asm, we're done.
1668 if (!InBraces)
1669 break;
1670 // We're no longer in a comment.
1671 InAsmComment = false;
1672 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
1673 // Single-line asm always ends when a closing brace is seen.
1674 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
1675 // does MSVC do here?
1676 break;
1677 }
1678 }
1679 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
1680 BraceCount == (savedBraceCount + 1)) {
1681 // Consume the closing brace, and finish
1682 EndLoc = ConsumeBrace();
1683 break;
1684 }
1685
1686 // Consume the next token; make sure we don't modify the brace count etc.
1687 // if we are in a comment.
1688 EndLoc = TokLoc;
1689 if (InAsmComment)
1690 PP.Lex(Tok);
1691 else {
1692 AsmToks.push_back(Tok);
1693 ConsumeAnyToken();
1694 }
1695 TokLoc = Tok.getLocation();
1696 ++NumTokensRead;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001697 } while (1);
Chad Rosier8cd64b42012-06-11 20:47:18 +00001698
Chad Rosier21ef7112012-08-14 19:22:06 +00001699 if (InBraces && BraceCount != savedBraceCount) {
1700 // __asm without closing brace (this can happen at EOF).
1701 Diag(Tok, diag::err_expected_rbrace);
1702 Diag(LBraceLoc, diag::note_matching) << "{";
1703 return StmtError();
1704 } else if (NumTokensRead == 0) {
1705 // Empty __asm.
1706 Diag(Tok, diag::err_expected_lbrace);
1707 return StmtError();
1708 }
1709
Chad Rosier56d7f232012-08-24 21:42:51 +00001710 // If MS-style inline assembly is disabled, then build an empty asm.
1711 if (!getLangOpts().EmitMicrosoftInlineAsm) {
1712 Token t;
1713 t.setKind(tok::string_literal);
1714 t.setLiteralData("\"/*FIXME: not done*/\"");
1715 t.clearFlag(Token::NeedsCleaning);
1716 t.setLength(21);
1717 ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1718 ExprVector Constraints;
1719 ExprVector Exprs;
1720 ExprVector Clobbers;
Chad Rosierdf5faf52012-08-25 00:11:56 +00001721 return Actions.ActOnGCCAsmStmt(AsmLoc, true, true, 0, 0, 0, Constraints,
1722 Exprs, AsmString.take(), Clobbers, EndLoc);
Chad Rosier56d7f232012-08-24 21:42:51 +00001723 }
1724
Chad Rosier8f726de2012-08-06 20:03:45 +00001725 // FIXME: We should be passing source locations for better diagnostics.
Chad Rosier7bd092b2012-08-15 16:53:30 +00001726 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc,
1727 llvm::makeArrayRef(AsmToks), EndLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00001728}
1729
Reid Spencer5f016e22007-07-11 17:01:13 +00001730/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff5f8aa692008-02-11 23:15:56 +00001731/// asm-statement:
1732/// gnu-asm-statement
1733/// ms-asm-statement
1734///
1735/// [GNU] gnu-asm-statement:
Reid Spencer5f016e22007-07-11 17:01:13 +00001736/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1737///
1738/// [GNU] asm-argument:
1739/// asm-string-literal
1740/// asm-string-literal ':' asm-operands[opt]
1741/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1742/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1743/// ':' asm-clobbers
1744///
1745/// [GNU] asm-clobbers:
1746/// asm-string-literal
1747/// asm-clobbers ',' asm-string-literal
1748///
John McCall60d7b3a2010-08-24 06:29:42 +00001749StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001750 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattnerfe795952007-10-29 04:04:16 +00001751 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001752
Chad Rosierb6604462012-07-10 21:35:27 +00001753 if (getLangOpts().MicrosoftExt && Tok.isNot(tok::l_paren) &&
1754 !isTypeQualifier()) {
Steve Naroffd62701b2008-02-07 03:50:06 +00001755 msAsm = true;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001756 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00001757 }
John McCall0b7e6782011-03-24 11:26:52 +00001758 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 SourceLocation Loc = Tok.getLocation();
Sean Huntbbd37c62009-11-21 08:43:09 +00001760 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redl9a920342008-12-11 19:48:14 +00001761
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1763 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner1ab3b962008-11-18 07:48:38 +00001764 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner1ab3b962008-11-18 07:48:38 +00001766 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Sebastian Redl9a920342008-12-11 19:48:14 +00001767
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 // Remember if this was a volatile asm.
Anders Carlsson39c47b52007-11-23 23:12:25 +00001769 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001770 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001771 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 SkipUntil(tok::r_paren);
Sebastian Redl9a920342008-12-11 19:48:14 +00001773 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001775 BalancedDelimiterTracker T(*this, tok::l_paren);
1776 T.consumeOpen();
Sebastian Redl9a920342008-12-11 19:48:14 +00001777
John McCall60d7b3a2010-08-24 06:29:42 +00001778 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenek320fa4b2011-12-02 01:30:14 +00001779 if (AsmString.isInvalid()) {
Richard Smith99831e42012-03-06 03:21:47 +00001780 // Consume up to and including the closing paren.
1781 T.skipToEnd();
Sebastian Redl9a920342008-12-11 19:48:14 +00001782 return StmtError();
Ted Kremenek320fa4b2011-12-02 01:30:14 +00001783 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001784
Chris Lattner5f9e2722011-07-23 10:55:15 +00001785 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001786 ExprVector Constraints;
1787 ExprVector Exprs;
1788 ExprVector Clobbers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001789
Anders Carlssondfab34a2008-02-05 23:03:50 +00001790 if (Tok.is(tok::r_paren)) {
Chris Lattner64cb4752009-12-20 23:00:41 +00001791 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001792 T.consumeClose();
Chad Rosierdf5faf52012-08-25 00:11:56 +00001793 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1794 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1795 Constraints, Exprs, AsmString.take(),
1796 Clobbers, T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001798
Chris Lattner64cb4752009-12-20 23:00:41 +00001799 // Parse Outputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001800 bool AteExtraColon = false;
1801 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1802 // In C++ mode, parse "::" like ": :".
1803 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattner64cb4752009-12-20 23:00:41 +00001804 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001805
Chris Lattner64056462009-12-20 23:08:04 +00001806 if (!AteExtraColon &&
1807 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00001808 return StmtError();
1809 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001810
Chris Lattner64cb4752009-12-20 23:00:41 +00001811 unsigned NumOutputs = Names.size();
1812
1813 // Parse Inputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001814 if (AteExtraColon ||
1815 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1816 // In C++ mode, parse "::" like ": :".
1817 if (AteExtraColon)
1818 AteExtraColon = false;
1819 else {
1820 AteExtraColon = Tok.is(tok::coloncolon);
1821 ConsumeToken();
1822 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001823
Chris Lattner64056462009-12-20 23:08:04 +00001824 if (!AteExtraColon &&
1825 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00001826 return StmtError();
1827 }
1828
1829 assert(Names.size() == Constraints.size() &&
1830 Constraints.size() == Exprs.size() &&
1831 "Input operand size mismatch!");
1832
1833 unsigned NumInputs = Names.size() - NumOutputs;
1834
1835 // Parse the clobbers, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001836 if (AteExtraColon || Tok.is(tok::colon)) {
1837 if (!AteExtraColon)
1838 ConsumeToken();
Chris Lattner64cb4752009-12-20 23:00:41 +00001839
Chandler Carruth102e1b62010-07-22 07:11:21 +00001840 // Parse the asm-string list for clobbers if present.
1841 if (Tok.isNot(tok::r_paren)) {
1842 while (1) {
John McCall60d7b3a2010-08-24 06:29:42 +00001843 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattner64cb4752009-12-20 23:00:41 +00001844
Chandler Carruth102e1b62010-07-22 07:11:21 +00001845 if (Clobber.isInvalid())
1846 break;
Chris Lattner64cb4752009-12-20 23:00:41 +00001847
Chandler Carruth102e1b62010-07-22 07:11:21 +00001848 Clobbers.push_back(Clobber.release());
Chris Lattner64cb4752009-12-20 23:00:41 +00001849
Chandler Carruth102e1b62010-07-22 07:11:21 +00001850 if (Tok.isNot(tok::comma)) break;
1851 ConsumeToken();
1852 }
Chris Lattner64cb4752009-12-20 23:00:41 +00001853 }
1854 }
1855
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001856 T.consumeClose();
Chad Rosierdf5faf52012-08-25 00:11:56 +00001857 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
1858 NumInputs, Names.data(), Constraints, Exprs,
1859 AsmString.take(), Clobbers,
1860 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001861}
1862
1863/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattner64cb4752009-12-20 23:00:41 +00001864/// asm-statement, assuming the leading ':' token was eaten.
Reid Spencer5f016e22007-07-11 17:01:13 +00001865///
1866/// [GNU] asm-operands:
1867/// asm-operand
1868/// asm-operands ',' asm-operand
1869///
1870/// [GNU] asm-operand:
1871/// asm-string-literal '(' expression ')'
1872/// '[' identifier ']' asm-string-literal '(' expression ')'
1873///
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00001874//
1875// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001876bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001877 SmallVectorImpl<Expr *> &Constraints,
1878 SmallVectorImpl<Expr *> &Exprs) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 // 'asm-operands' isn't present?
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001880 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001881 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001882
1883 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 // Read the [id] if present.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001885 if (Tok.is(tok::l_square)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001886 BalancedDelimiterTracker T(*this, tok::l_square);
1887 T.consumeOpen();
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001889 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 Diag(Tok, diag::err_expected_ident);
1891 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001892 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 }
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Anders Carlssonb235fc22007-11-22 01:36:19 +00001895 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner69efba72007-10-29 04:06:22 +00001896 ConsumeToken();
Anders Carlssonb235fc22007-11-22 01:36:19 +00001897
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001898 Names.push_back(II);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001899 T.consumeClose();
Anders Carlssonb235fc22007-11-22 01:36:19 +00001900 } else
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001901 Names.push_back(0);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001902
John McCall60d7b3a2010-08-24 06:29:42 +00001903 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001904 if (Constraint.isInvalid()) {
Anders Carlssonb235fc22007-11-22 01:36:19 +00001905 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001906 return true;
Anders Carlssonb235fc22007-11-22 01:36:19 +00001907 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001908 Constraints.push_back(Constraint.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00001909
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001910 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001911 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001913 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001915
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 // Read the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001917 BalancedDelimiterTracker T(*this, tok::l_paren);
1918 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00001919 ExprResult Res(ParseExpression());
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001920 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001921 if (Res.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001923 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001925 Exprs.push_back(Res.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 // Eat the comma and continue parsing if it exists.
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001927 if (Tok.isNot(tok::comma)) return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001928 ConsumeToken();
1929 }
1930}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001931
Douglas Gregorc9977d02011-03-16 17:05:57 +00001932Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00001933 assert(Tok.is(tok::l_brace));
1934 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001935
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001936 if (SkipFunctionBodies && trySkippingFunctionBody()) {
1937 BodyScope.Exit();
1938 return Actions.ActOnFinishFunctionBody(Decl, 0);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001939 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001940
John McCallf312b1e2010-08-26 23:41:50 +00001941 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1942 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001944 // Do not enter a scope for the brace, as the arguments are in the same scope
1945 // (the function body) as the body itself. Instead, just read the statement
1946 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00001947 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00001948
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001949 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001950 if (FnBody.isInvalid()) {
1951 Sema::CompoundScopeRAII CompoundScope(Actions);
Mike Stump1eb44332009-09-09 15:08:12 +00001952 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Benjamin Kramer5354e772012-08-23 23:38:35 +00001953 MultiStmtArg(), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001954 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001955
Douglas Gregorc9977d02011-03-16 17:05:57 +00001956 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00001957 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00001958}
Sebastian Redla0fd8652008-12-21 16:41:36 +00001959
Sebastian Redld3a413d2009-04-26 20:35:05 +00001960/// ParseFunctionTryBlock - Parse a C++ function-try-block.
1961///
1962/// function-try-block:
1963/// 'try' ctor-initializer[opt] compound-statement handler-seq
1964///
Douglas Gregorc9977d02011-03-16 17:05:57 +00001965Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00001966 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1967 SourceLocation TryLoc = ConsumeToken();
1968
John McCallf312b1e2010-08-26 23:41:50 +00001969 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1970 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00001971
1972 // Constructor initializer list?
1973 if (Tok.is(tok::colon))
1974 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00001975 else
1976 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001977
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001978 if (SkipFunctionBodies && trySkippingFunctionBody()) {
1979 BodyScope.Exit();
1980 return Actions.ActOnFinishFunctionBody(Decl, 0);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001981 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001982
Sebastian Redlde1b60a2009-04-26 21:08:36 +00001983 SourceLocation LBraceLoc = Tok.getLocation();
John McCall60d7b3a2010-08-24 06:29:42 +00001984 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
Sebastian Redld3a413d2009-04-26 20:35:05 +00001985 // If we failed to parse the try-catch, we just give the function an empty
1986 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001987 if (FnBody.isInvalid()) {
1988 Sema::CompoundScopeRAII CompoundScope(Actions);
Sebastian Redlde1b60a2009-04-26 21:08:36 +00001989 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Benjamin Kramer5354e772012-08-23 23:38:35 +00001990 MultiStmtArg(), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001991 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00001992
Douglas Gregorc9977d02011-03-16 17:05:57 +00001993 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00001994 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redld3a413d2009-04-26 20:35:05 +00001995}
1996
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001997bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001998 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001999 assert(SkipFunctionBodies &&
2000 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002001
2002 // We're in code-completion mode. Skip parsing for all function bodies unless
2003 // the body contains the code-completion point.
2004 TentativeParsingAction PA(*this);
2005 ConsumeBrace();
2006 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002007 /*StopAtCodeCompletion=*/PP.isCodeCompletionEnabled())) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002008 PA.Commit();
2009 return true;
2010 }
2011
2012 PA.Revert();
2013 return false;
2014}
2015
Sebastian Redla0fd8652008-12-21 16:41:36 +00002016/// ParseCXXTryBlock - Parse a C++ try-block.
2017///
2018/// try-block:
2019/// 'try' compound-statement handler-seq
2020///
Richard Smith534986f2012-04-14 00:33:13 +00002021StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002022 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2023
2024 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002025 return ParseCXXTryBlockCommon(TryLoc);
2026}
2027
2028/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2029/// function-try-block.
2030///
2031/// try-block:
2032/// 'try' compound-statement handler-seq
2033///
2034/// function-try-block:
2035/// 'try' ctor-initializer[opt] compound-statement handler-seq
2036///
2037/// handler-seq:
2038/// handler handler-seq[opt]
2039///
John Wiegley28bbe4b2011-04-28 01:08:34 +00002040/// [Borland] try-block:
2041/// 'try' compound-statement seh-except-block
2042/// 'try' compound-statment seh-finally-block
2043///
John McCall60d7b3a2010-08-24 06:29:42 +00002044StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002045 if (Tok.isNot(tok::l_brace))
2046 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Sean Huntbbd37c62009-11-21 08:43:09 +00002047 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002048
2049 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002050 Scope::DeclScope|Scope::TryScope));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002051 if (TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002052 return TryBlock;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002053
John Wiegley28bbe4b2011-04-28 01:08:34 +00002054 // Borland allows SEH-handlers with 'try'
Chad Rosierb6604462012-07-10 21:35:27 +00002055
Richard Smith534986f2012-04-14 00:33:13 +00002056 if ((Tok.is(tok::identifier) &&
2057 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2058 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002059 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2060 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00002061 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002062 SourceLocation Loc = ConsumeToken();
2063 Handler = ParseSEHExceptBlock(Loc);
2064 }
2065 else {
2066 SourceLocation Loc = ConsumeToken();
2067 Handler = ParseSEHFinallyBlock(Loc);
2068 }
2069 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002070 return Handler;
John McCall7f040a92010-12-24 02:08:15 +00002071
John Wiegley28bbe4b2011-04-28 01:08:34 +00002072 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2073 TryLoc,
2074 TryBlock.take(),
2075 Handler.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002076 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00002077 else {
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002078 StmtVector Handlers;
Richard Smith534986f2012-04-14 00:33:13 +00002079 ParsedAttributesWithRange attrs(AttrFactory);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002080 MaybeParseCXX0XAttributes(attrs);
2081 ProhibitAttributes(attrs);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002082
John Wiegley28bbe4b2011-04-28 01:08:34 +00002083 if (Tok.isNot(tok::kw_catch))
2084 return StmtError(Diag(Tok, diag::err_expected_catch));
2085 while (Tok.is(tok::kw_catch)) {
2086 StmtResult Handler(ParseCXXCatchBlock());
2087 if (!Handler.isInvalid())
2088 Handlers.push_back(Handler.release());
2089 }
2090 // Don't bother creating the full statement if we don't have any usable
2091 // handlers.
2092 if (Handlers.empty())
2093 return StmtError();
2094
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002095 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(),Handlers);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002096 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002097}
2098
2099/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2100///
2101/// handler:
2102/// 'catch' '(' exception-declaration ')' compound-statement
2103///
2104/// exception-declaration:
2105/// type-specifier-seq declarator
2106/// type-specifier-seq abstract-declarator
2107/// type-specifier-seq
2108/// '...'
2109///
John McCall60d7b3a2010-08-24 06:29:42 +00002110StmtResult Parser::ParseCXXCatchBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002111 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2112
2113 SourceLocation CatchLoc = ConsumeToken();
2114
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002115 BalancedDelimiterTracker T(*this, tok::l_paren);
2116 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redla0fd8652008-12-21 16:41:36 +00002117 return StmtError();
2118
2119 // C++ 3.3.2p3:
2120 // The name in a catch exception-declaration is local to the handler and
2121 // shall not be redeclared in the outermost block of the handler.
2122 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
2123
2124 // exception-declaration is equivalent to '...' or a parameter-declaration
2125 // without default arguments.
John McCalld226f652010-08-21 09:40:31 +00002126 Decl *ExceptionDecl = 0;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002127 if (Tok.isNot(tok::ellipsis)) {
John McCall0b7e6782011-03-24 11:26:52 +00002128 DeclSpec DS(AttrFactory);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002129 if (ParseCXXTypeSpecifierSeq(DS))
2130 return StmtError();
Sebastian Redla0fd8652008-12-21 16:41:36 +00002131 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2132 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002133 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002134 } else
2135 ConsumeToken();
2136
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002137 T.consumeClose();
2138 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002139 return StmtError();
2140
2141 if (Tok.isNot(tok::l_brace))
2142 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2143
Sean Huntbbd37c62009-11-21 08:43:09 +00002144 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002145 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002146 if (Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002147 return Block;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002148
John McCall9ae2f072010-08-23 23:25:46 +00002149 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002150}
Francois Pichet1e862692011-05-06 20:48:22 +00002151
2152void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002153 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002154 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002155 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002156
Douglas Gregor3896fc52011-10-24 22:31:10 +00002157 // Handle dependent statements by parsing the braces as a compound statement.
2158 // This is not the same behavior as Visual C++, which don't treat this as a
2159 // compound statement, but for Clang's type checking we can't have anything
2160 // inside these braces escaping to the surrounding code.
2161 if (Result.Behavior == IEB_Dependent) {
2162 if (!Tok.is(tok::l_brace)) {
2163 Diag(Tok, diag::err_expected_lbrace);
Richard Smith534986f2012-04-14 00:33:13 +00002164 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002165 }
Richard Smith534986f2012-04-14 00:33:13 +00002166
2167 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002168 if (Compound.isInvalid())
2169 return;
Richard Smith534986f2012-04-14 00:33:13 +00002170
Douglas Gregorba0513d2011-10-25 01:33:02 +00002171 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2172 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002173 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002174 Result.Name,
2175 Compound.get());
2176 if (DepResult.isUsable())
2177 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002178 return;
2179 }
Richard Smith534986f2012-04-14 00:33:13 +00002180
Douglas Gregor3896fc52011-10-24 22:31:10 +00002181 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2182 if (Braces.consumeOpen()) {
Francois Pichet1e862692011-05-06 20:48:22 +00002183 Diag(Tok, diag::err_expected_lbrace);
2184 return;
2185 }
Francois Pichet1e862692011-05-06 20:48:22 +00002186
Douglas Gregor3896fc52011-10-24 22:31:10 +00002187 switch (Result.Behavior) {
2188 case IEB_Parse:
2189 // Parse the statements below.
2190 break;
Chad Rosierb6604462012-07-10 21:35:27 +00002191
Douglas Gregor3896fc52011-10-24 22:31:10 +00002192 case IEB_Dependent:
2193 llvm_unreachable("Dependent case handled above");
Chad Rosierb6604462012-07-10 21:35:27 +00002194
Douglas Gregor3896fc52011-10-24 22:31:10 +00002195 case IEB_Skip:
2196 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002197 return;
2198 }
2199
2200 // Condition is true, parse the statements.
2201 while (Tok.isNot(tok::r_brace)) {
2202 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2203 if (R.isUsable())
2204 Stmts.push_back(R.release());
2205 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002206 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002207}