blob: 9796ea69bacd6cf2329d846dfb9526fb78b4d117 [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"
Chris Lattnerae50fa02009-03-05 00:00:31 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/PrettyStackTrace.h"
22#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// C99 6.8: Statements and Blocks.
27//===----------------------------------------------------------------------===//
28
29/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
30/// StatementOrDeclaration:
31/// statement
32/// declaration
33///
34/// statement:
35/// labeled-statement
36/// compound-statement
37/// expression-statement
38/// selection-statement
39/// iteration-statement
40/// jump-statement
Argyrios Kyrtzidisdcdd55f2008-09-07 18:58:01 +000041/// [C++] declaration-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +000042/// [C++] try-block
John Wiegley28bbe4b2011-04-28 01:08:34 +000043/// [MS] seh-try-block
Fariborz Jahanianb384d322007-10-04 20:19:06 +000044/// [OBC] objc-throw-statement
45/// [OBC] objc-try-catch-statement
Fariborz Jahanianc385c902008-01-29 18:21:32 +000046/// [OBC] objc-synchronized-statement
Reid Spencer5f016e22007-07-11 17:01:13 +000047/// [GNU] asm-statement
48/// [OMP] openmp-construct [TODO]
49///
50/// labeled-statement:
51/// identifier ':' statement
52/// 'case' constant-expression ':' statement
53/// 'default' ':' statement
54///
55/// selection-statement:
56/// if-statement
57/// switch-statement
58///
59/// iteration-statement:
60/// while-statement
61/// do-statement
62/// for-statement
63///
64/// expression-statement:
65/// expression[opt] ';'
66///
67/// jump-statement:
68/// 'goto' identifier ';'
69/// 'continue' ';'
70/// 'break' ';'
71/// 'return' expression[opt] ';'
72/// [GNU] 'goto' '*' expression ';'
73///
Fariborz Jahanianb384d322007-10-04 20:19:06 +000074/// [OBC] objc-throw-statement:
75/// [OBC] '@' 'throw' expression ';'
Mike Stump1eb44332009-09-09 15:08:12 +000076/// [OBC] '@' 'throw' ';'
77///
John McCall60d7b3a2010-08-24 06:29:42 +000078StmtResult
Nico Weber5cb94a72011-12-22 23:26:17 +000079Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
80 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000081
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +000082 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +000083
Richard Smith534986f2012-04-14 00:33:13 +000084 ParsedAttributesWithRange Attrs(AttrFactory);
85 MaybeParseCXX0XAttributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
86
87 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
88 OnlyStatement, TrailingElseLoc, Attrs);
89
90 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
91 "attributes on empty statement");
92
93 if (Attrs.empty() || Res.isInvalid())
94 return Res;
95
96 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
97}
98
99StmtResult
100Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
101 bool OnlyStatement, SourceLocation *TrailingElseLoc,
102 ParsedAttributesWithRange &Attrs) {
103 const char *SemiError = 0;
104 StmtResult Res;
Sean Huntbbd37c62009-11-21 08:43:09 +0000105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 // Cases in this switch statement should fall through if the parser expects
107 // the token to end in a semicolon (in which case SemiError should be set),
108 // or they directly 'return;' if not.
Douglas Gregor312eadb2011-04-24 05:37:28 +0000109Retry:
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000110 tok::TokenKind Kind = Tok.getKind();
111 SourceLocation AtLoc;
112 switch (Kind) {
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000113 case tok::at: // May be a @try or @throw statement
114 {
Richard Smith534986f2012-04-14 00:33:13 +0000115 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000116 AtLoc = ConsumeToken(); // consume @
Sebastian Redl43bc2a02008-12-11 20:12:42 +0000117 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000118 }
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000119
Douglas Gregor791215b2009-09-21 20:51:25 +0000120 case tok::code_completion:
John McCallf312b1e2010-08-26 23:41:50 +0000121 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000122 cutOffParsing();
123 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000124
Douglas Gregor312eadb2011-04-24 05:37:28 +0000125 case tok::identifier: {
126 Token Next = NextToken();
127 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000128 // identifier ':' statement
Richard Smith534986f2012-04-14 00:33:13 +0000129 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000130 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000131
Douglas Gregor3b887352011-04-27 04:48:22 +0000132 if (Next.isNot(tok::coloncolon)) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000133 CXXScopeSpec SS;
134 IdentifierInfo *Name = Tok.getIdentifierInfo();
135 SourceLocation NameLoc = Tok.getLocation();
Richard Trieu950be712011-09-19 19:01:00 +0000136
David Blaikie4e4d0842012-03-11 07:00:24 +0000137 if (getLangOpts().CPlusPlus)
Richard Trieu950be712011-09-19 19:01:00 +0000138 CheckForTemplateAndDigraph(Next, ParsedType(),
139 /*EnteringContext=*/false, *Name, SS);
140
Douglas Gregor312eadb2011-04-24 05:37:28 +0000141 Sema::NameClassification Classification
142 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next);
143 switch (Classification.getKind()) {
144 case Sema::NC_Keyword:
145 // The identifier was corrected to a keyword. Update the token
146 // to this keyword, and try again.
147 if (Name->getTokenID() != tok::identifier) {
148 Tok.setIdentifierInfo(Name);
149 Tok.setKind(Name->getTokenID());
150 goto Retry;
151 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000152
Douglas Gregor312eadb2011-04-24 05:37:28 +0000153 // Fall through via the normal error path.
154 // FIXME: This seems like it could only happen for context-sensitive
155 // keywords.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000156
Douglas Gregor312eadb2011-04-24 05:37:28 +0000157 case Sema::NC_Error:
158 // Handle errors here by skipping up to the next semicolon or '}', and
159 // eat the semicolon if that's what stopped us.
160 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
161 if (Tok.is(tok::semi))
162 ConsumeToken();
163 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000164
Douglas Gregor312eadb2011-04-24 05:37:28 +0000165 case Sema::NC_Unknown:
166 // Either we don't know anything about this identifier, or we know that
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000167 // we're in a syntactic context we haven't handled yet.
168 break;
169
Douglas Gregord9d75e52011-04-27 05:41:15 +0000170 case Sema::NC_Type:
Douglas Gregor3b887352011-04-27 04:48:22 +0000171 Tok.setKind(tok::annot_typename);
172 setTypeAnnotation(Tok, Classification.getType());
173 Tok.setAnnotationEndLoc(NameLoc);
Douglas Gregor3b887352011-04-27 04:48:22 +0000174 PP.AnnotateCachedTokens(Tok);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000175 break;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000176
Douglas Gregor312eadb2011-04-24 05:37:28 +0000177 case Sema::NC_Expression:
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000178 Tok.setKind(tok::annot_primary_expr);
179 setExprAnnotation(Tok, Classification.getExpression());
180 Tok.setAnnotationEndLoc(NameLoc);
181 PP.AnnotateCachedTokens(Tok);
182 break;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000183
Douglas Gregor312eadb2011-04-24 05:37:28 +0000184 case Sema::NC_TypeTemplate:
185 case Sema::NC_FunctionTemplate: {
186 ConsumeToken(); // the identifier
187 UnqualifiedId Id;
188 Id.setIdentifier(Name, NameLoc);
189 if (AnnotateTemplateIdToken(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000190 TemplateTy::make(Classification.getTemplateName()),
Douglas Gregor312eadb2011-04-24 05:37:28 +0000191 Classification.getTemplateNameKind(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000192 SS, SourceLocation(), Id,
Douglas Gregor3b887352011-04-27 04:48:22 +0000193 /*AllowTypeAnnotation=*/false)) {
194 // Handle errors here by skipping up to the next semicolon or '}', and
195 // eat the semicolon if that's what stopped us.
196 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
197 if (Tok.is(tok::semi))
198 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000199 return StmtError();
Douglas Gregor3b887352011-04-27 04:48:22 +0000200 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000201
202 // If the next token is '::', jump right into parsing a
Douglas Gregor3b887352011-04-27 04:48:22 +0000203 // nested-name-specifier. We don't want to leave the template-id
204 // hanging.
205 if (NextToken().is(tok::coloncolon) && TryAnnotateCXXScopeToken(false)){
Douglas Gregor312eadb2011-04-24 05:37:28 +0000206 // Handle errors here by skipping up to the next semicolon or '}', and
207 // eat the semicolon if that's what stopped us.
208 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
209 if (Tok.is(tok::semi))
210 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000211 return StmtError();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000212 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000213
Douglas Gregor312eadb2011-04-24 05:37:28 +0000214 // We've annotated a template-id, so try again now.
215 goto Retry;
216 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000217
Douglas Gregor312eadb2011-04-24 05:37:28 +0000218 case Sema::NC_NestedNameSpecifier:
219 // FIXME: Implement this!
220 break;
221 }
222 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000223
Douglas Gregor312eadb2011-04-24 05:37:28 +0000224 // Fall through
225 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000226
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000227 default: {
David Blaikie4e4d0842012-03-11 07:00:24 +0000228 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner97144fc2009-04-02 04:16:50 +0000229 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek8113ecf2010-11-10 05:59:39 +0000230 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smith534986f2012-04-14 00:33:13 +0000231 DeclEnd, Attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000232 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000233 }
234
235 if (Tok.is(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 Diag(Tok, diag::err_expected_statement);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000237 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 }
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Richard Smith534986f2012-04-14 00:33:13 +0000240 return ParseExprStatement();
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000241 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000242
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000244 return ParseCaseStatement();
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000246 return ParseDefaultStatement();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000247
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smith534986f2012-04-14 00:33:13 +0000249 return ParseCompoundStatement();
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000250 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +0000251 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
252 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000253 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000254
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smith534986f2012-04-14 00:33:13 +0000256 return ParseIfStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smith534986f2012-04-14 00:33:13 +0000258 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000259
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smith534986f2012-04-14 00:33:13 +0000261 return ParseWhileStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000262 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smith534986f2012-04-14 00:33:13 +0000263 Res = ParseDoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000264 SemiError = "do/while";
Reid Spencer5f016e22007-07-11 17:01:13 +0000265 break;
266 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smith534986f2012-04-14 00:33:13 +0000267 return ParseForStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000268
269 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smith534986f2012-04-14 00:33:13 +0000270 Res = ParseGotoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000271 SemiError = "goto";
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 break;
273 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smith534986f2012-04-14 00:33:13 +0000274 Res = ParseContinueStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000275 SemiError = "continue";
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 break;
277 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smith534986f2012-04-14 00:33:13 +0000278 Res = ParseBreakStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000279 SemiError = "break";
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 break;
281 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smith534986f2012-04-14 00:33:13 +0000282 Res = ParseReturnStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000283 SemiError = "return";
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 break;
Sebastian Redl61364dd2008-12-11 19:30:53 +0000285
Sebastian Redla0fd8652008-12-21 16:41:36 +0000286 case tok::kw_asm: {
Richard Smith534986f2012-04-14 00:33:13 +0000287 ProhibitAttributes(Attrs);
Steve Naroffd62701b2008-02-07 03:50:06 +0000288 bool msAsm = false;
289 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +0000290 Res = Actions.ActOnFinishFullStmt(Res.get());
Sebastian Redl61364dd2008-12-11 19:30:53 +0000291 if (msAsm) return move(Res);
Chris Lattner6869d8e2009-06-14 00:07:48 +0000292 SemiError = "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 break;
294 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000295
Sebastian Redla0fd8652008-12-21 16:41:36 +0000296 case tok::kw_try: // C++ 15: try-block
Richard Smith534986f2012-04-14 00:33:13 +0000297 return ParseCXXTryBlock();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000298
299 case tok::kw___try:
Richard Smith534986f2012-04-14 00:33:13 +0000300 ProhibitAttributes(Attrs); // TODO: is it correct?
301 return ParseSEHTryBlock();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000302
303 case tok::annot_pragma_vis:
Richard Smith534986f2012-04-14 00:33:13 +0000304 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000305 HandlePragmaVisibility();
306 return StmtEmpty();
307
308 case tok::annot_pragma_pack:
Richard Smith534986f2012-04-14 00:33:13 +0000309 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000310 HandlePragmaPack();
311 return StmtEmpty();
Sebastian Redla0fd8652008-12-21 16:41:36 +0000312 }
313
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 // If we reached this code, the statement must end in a semicolon.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000315 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 ConsumeToken();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000317 } else if (!Res.isInvalid()) {
Chris Lattner7b3684a2009-06-14 00:23:56 +0000318 // If the result was valid, then we do want to diagnose this. Use
319 // ExpectAndConsume to emit the diagnostic, even though we know it won't
320 // succeed.
321 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner19504402008-11-13 18:52:53 +0000322 // Skip until we see a } or ;, but don't eat it.
323 SkipUntil(tok::r_brace, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Sebastian Redl61364dd2008-12-11 19:30:53 +0000326 return move(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +0000327}
328
Douglas Gregor312eadb2011-04-24 05:37:28 +0000329/// \brief Parse an expression statement.
Richard Smith534986f2012-04-14 00:33:13 +0000330StmtResult Parser::ParseExprStatement() {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000331 // If a case keyword is missing, this is where it should be inserted.
332 Token OldToken = Tok;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000333
Douglas Gregor312eadb2011-04-24 05:37:28 +0000334 // expression[opt] ';'
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000335 ExprResult Expr(ParseExpression());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000336 if (Expr.isInvalid()) {
337 // If the expression is invalid, skip ahead to the next semicolon or '}'.
338 // Not doing this opens us up to the possibility of infinite loops if
339 // ParseExpression does not consume any tokens.
340 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
341 if (Tok.is(tok::semi))
342 ConsumeToken();
343 return StmtError();
344 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000345
Douglas Gregor312eadb2011-04-24 05:37:28 +0000346 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
347 Actions.CheckCaseExpression(Expr.get())) {
348 // If a constant expression is followed by a colon inside a switch block,
349 // suggest a missing case keyword.
350 Diag(OldToken, diag::err_expected_case_before_expression)
351 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000352
Douglas Gregor312eadb2011-04-24 05:37:28 +0000353 // Recover parsing as a case statement.
Richard Smith534986f2012-04-14 00:33:13 +0000354 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000355 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000356
Douglas Gregor312eadb2011-04-24 05:37:28 +0000357 // Otherwise, eat the semicolon.
358 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
359 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
John Wiegley28bbe4b2011-04-28 01:08:34 +0000360}
Douglas Gregor312eadb2011-04-24 05:37:28 +0000361
Richard Smith534986f2012-04-14 00:33:13 +0000362StmtResult Parser::ParseSEHTryBlock() {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000363 assert(Tok.is(tok::kw___try) && "Expected '__try'");
364 SourceLocation Loc = ConsumeToken();
365 return ParseSEHTryBlockCommon(Loc);
366}
367
368/// ParseSEHTryBlockCommon
369///
370/// seh-try-block:
371/// '__try' compound-statement seh-handler
372///
373/// seh-handler:
374/// seh-except-block
375/// seh-finally-block
376///
377StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
378 if(Tok.isNot(tok::l_brace))
379 return StmtError(Diag(Tok,diag::err_expected_lbrace));
380
Richard Smith534986f2012-04-14 00:33:13 +0000381 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000382 if(TryBlock.isInvalid())
383 return move(TryBlock);
384
385 StmtResult Handler;
Richard Smith534986f2012-04-14 00:33:13 +0000386 if (Tok.is(tok::identifier) &&
Douglas Gregorb57791e2011-10-21 03:57:52 +0000387 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000388 SourceLocation Loc = ConsumeToken();
389 Handler = ParseSEHExceptBlock(Loc);
390 } else if (Tok.is(tok::kw___finally)) {
391 SourceLocation Loc = ConsumeToken();
392 Handler = ParseSEHFinallyBlock(Loc);
393 } else {
394 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
395 }
396
397 if(Handler.isInvalid())
398 return move(Handler);
399
400 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
401 TryLoc,
402 TryBlock.take(),
403 Handler.take());
404}
405
406/// ParseSEHExceptBlock - Handle __except
407///
408/// seh-except-block:
409/// '__except' '(' seh-filter-expression ')' compound-statement
410///
411StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
412 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
413 raii2(Ident___exception_code, false),
414 raii3(Ident_GetExceptionCode, false);
415
416 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
417 return StmtError();
418
419 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
420
David Blaikie4e4d0842012-03-11 07:00:24 +0000421 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000422 Ident__exception_info->setIsPoisoned(false);
423 Ident___exception_info->setIsPoisoned(false);
424 Ident_GetExceptionInfo->setIsPoisoned(false);
425 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000426 ExprResult FilterExpr(ParseExpression());
Francois Pichetd7f02df2011-04-28 03:14:31 +0000427
David Blaikie4e4d0842012-03-11 07:00:24 +0000428 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000429 Ident__exception_info->setIsPoisoned(true);
430 Ident___exception_info->setIsPoisoned(true);
431 Ident_GetExceptionInfo->setIsPoisoned(true);
432 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000433
434 if(FilterExpr.isInvalid())
435 return StmtError();
436
437 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
438 return StmtError();
439
Richard Smith534986f2012-04-14 00:33:13 +0000440 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000441
442 if(Block.isInvalid())
443 return move(Block);
444
445 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
446}
447
448/// ParseSEHFinallyBlock - Handle __finally
449///
450/// seh-finally-block:
451/// '__finally' compound-statement
452///
453StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
454 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
455 raii2(Ident___abnormal_termination, false),
456 raii3(Ident_AbnormalTermination, false);
457
Richard Smith534986f2012-04-14 00:33:13 +0000458 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000459 if(Block.isInvalid())
460 return move(Block);
461
462 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000463}
464
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000465/// ParseLabeledStatement - We have an identifier and a ':' after it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000466///
467/// labeled-statement:
468/// identifier ':' statement
469/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000470///
Richard Smith534986f2012-04-14 00:33:13 +0000471StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000472 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
473 "Not an identifier!");
474
475 Token IdentTok = Tok; // Save the whole token.
476 ConsumeToken(); // eat the identifier.
477
478 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000479
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000480 // identifier ':' statement
481 SourceLocation ColonLoc = ConsumeToken();
482
Richard Smith534986f2012-04-14 00:33:13 +0000483 // Read label attributes, if present. attrs will contain both C++11 and GNU
484 // attributes (if present) after this point.
John McCall7f040a92010-12-24 02:08:15 +0000485 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000486
John McCall60d7b3a2010-08-24 06:29:42 +0000487 StmtResult SubStmt(ParseStatement());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000488
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000489 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000490 if (SubStmt.isInvalid())
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000491 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000492
Chris Lattner337e5502011-02-18 01:27:55 +0000493 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
494 IdentTok.getLocation());
Richard Smith534986f2012-04-14 00:33:13 +0000495 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattner337e5502011-02-18 01:27:55 +0000496 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smith534986f2012-04-14 00:33:13 +0000497 attrs.clear();
498 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000499
Chris Lattner337e5502011-02-18 01:27:55 +0000500 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
501 SubStmt.get());
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000502}
Reid Spencer5f016e22007-07-11 17:01:13 +0000503
504/// ParseCaseStatement
505/// labeled-statement:
506/// 'case' constant-expression ':' statement
507/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
508///
Richard Smith534986f2012-04-14 00:33:13 +0000509StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smith46f11102011-04-21 22:48:40 +0000510 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattner24e1e702009-03-04 04:23:07 +0000512 // It is very very common for code to contain many case statements recursively
513 // nested, as in (but usually without indentation):
514 // case 1:
515 // case 2:
516 // case 3:
517 // case 4:
518 // case 5: etc.
519 //
520 // Parsing this naively works, but is both inefficient and can cause us to run
521 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner26140c62009-03-04 18:24:58 +0000522 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner24e1e702009-03-04 04:23:07 +0000523 // but all the grossness is constrained to ParseCaseStatement (and some
524 // wierdness in the actions), so this is just local grossness :).
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner24e1e702009-03-04 04:23:07 +0000526 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
527 // example above.
John McCall60d7b3a2010-08-24 06:29:42 +0000528 StmtResult TopLevelCase(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner24e1e702009-03-04 04:23:07 +0000530 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
531 // gets updated each time a new case is parsed, and whose body is unset so
532 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieub2fc6902011-09-09 02:16:15 +0000533 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Chris Lattner24e1e702009-03-04 04:23:07 +0000535 // While we have case statements, eat and stack them.
David Majnemer0e1e69c2011-06-13 05:50:12 +0000536 SourceLocation ColonLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000537 do {
Richard Trieubb9b80c2011-04-21 21:44:26 +0000538 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
539 ConsumeToken(); // eat the 'case'.
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000541 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000542 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000543 cutOffParsing();
544 return StmtError();
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000545 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000546
Chris Lattner6fb09c82009-12-10 00:38:54 +0000547 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
548 /// Disable this form of error recovery while we're parsing the case
549 /// expression.
550 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000551
Richard Trieubb9b80c2011-04-21 21:44:26 +0000552 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
553 MissingCase = false;
Chris Lattner24e1e702009-03-04 04:23:07 +0000554 if (LHS.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 SkipUntil(tok::colon);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000556 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000558
Chris Lattner24e1e702009-03-04 04:23:07 +0000559 // GNU case range extension.
560 SourceLocation DotDotDotLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000561 ExprResult RHS;
Chris Lattner24e1e702009-03-04 04:23:07 +0000562 if (Tok.is(tok::ellipsis)) {
563 Diag(Tok, diag::ext_gnu_case_range);
564 DotDotDotLoc = ConsumeToken();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000565
Chris Lattner24e1e702009-03-04 04:23:07 +0000566 RHS = ParseConstantExpression();
567 if (RHS.isInvalid()) {
568 SkipUntil(tok::colon);
569 return StmtError();
570 }
571 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000572
Chris Lattner6fb09c82009-12-10 00:38:54 +0000573 ColonProtection.restore();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000574
John McCallf6a3ab02011-01-22 09:28:32 +0000575 if (Tok.is(tok::colon)) {
576 ColonLoc = ConsumeToken();
577
578 // Treat "case blah;" as a typo for "case blah:".
579 } else if (Tok.is(tok::semi)) {
580 ColonLoc = ConsumeToken();
581 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
582 << FixItHint::CreateReplacement(ColonLoc, ":");
583 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000584 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
585 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
586 << FixItHint::CreateInsertion(ExpectedLoc, ":");
587 ColonLoc = ExpectedLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000588 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000589
John McCall60d7b3a2010-08-24 06:29:42 +0000590 StmtResult Case =
John McCall9ae2f072010-08-23 23:25:46 +0000591 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
592 RHS.get(), ColonLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattner24e1e702009-03-04 04:23:07 +0000594 // If we had a sema error parsing this case, then just ignore it and
595 // continue parsing the sub-stmt.
596 if (Case.isInvalid()) {
597 if (TopLevelCase.isInvalid()) // No parsed case stmts.
598 return ParseStatement();
599 // Otherwise, just don't add it as a nested case.
600 } else {
601 // If this is the first case statement we parsed, it becomes TopLevelCase.
602 // Otherwise we link it into the current chain.
John McCallca0408f2010-08-23 06:44:23 +0000603 Stmt *NextDeepest = Case.get();
Chris Lattner24e1e702009-03-04 04:23:07 +0000604 if (TopLevelCase.isInvalid())
605 TopLevelCase = move(Case);
606 else
John McCall9ae2f072010-08-23 23:25:46 +0000607 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner24e1e702009-03-04 04:23:07 +0000608 DeepestParsedCaseStmt = NextDeepest;
609 }
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Chris Lattner24e1e702009-03-04 04:23:07 +0000611 // Handle all case statements.
612 } while (Tok.is(tok::kw_case));
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner24e1e702009-03-04 04:23:07 +0000614 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Chris Lattner24e1e702009-03-04 04:23:07 +0000616 // If we found a non-case statement, start by parsing it.
John McCall60d7b3a2010-08-24 06:29:42 +0000617 StmtResult SubStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattner24e1e702009-03-04 04:23:07 +0000619 if (Tok.isNot(tok::r_brace)) {
620 SubStmt = ParseStatement();
621 } else {
622 // Nicely diagnose the common error "switch (X) { case 4: }", which is
623 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000624 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000625 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
626 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner24e1e702009-03-04 04:23:07 +0000627 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000628 }
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Chris Lattner24e1e702009-03-04 04:23:07 +0000630 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000631 if (SubStmt.isInvalid())
Chris Lattner24e1e702009-03-04 04:23:07 +0000632 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattner24e1e702009-03-04 04:23:07 +0000634 // Install the body into the most deeply-nested case.
John McCall9ae2f072010-08-23 23:25:46 +0000635 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl61364dd2008-12-11 19:30:53 +0000636
Chris Lattner24e1e702009-03-04 04:23:07 +0000637 // Return the top level parsed statement tree.
Chris Lattner26140c62009-03-04 18:24:58 +0000638 return move(TopLevelCase);
Reid Spencer5f016e22007-07-11 17:01:13 +0000639}
640
641/// ParseDefaultStatement
642/// labeled-statement:
643/// 'default' ':' statement
644/// Note that this does not parse the 'statement' at the end.
645///
Richard Smith534986f2012-04-14 00:33:13 +0000646StmtResult Parser::ParseDefaultStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000647 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
649
Douglas Gregor662a4822010-12-23 22:56:40 +0000650 SourceLocation ColonLoc;
John McCallf6a3ab02011-01-22 09:28:32 +0000651 if (Tok.is(tok::colon)) {
652 ColonLoc = ConsumeToken();
653
654 // Treat "default;" as a typo for "default:".
655 } else if (Tok.is(tok::semi)) {
656 ColonLoc = ConsumeToken();
657 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
658 << FixItHint::CreateReplacement(ColonLoc, ":");
659 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000660 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
661 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
662 << FixItHint::CreateInsertion(ExpectedLoc, ":");
663 ColonLoc = ExpectedLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000665
Richard Smith85b29a42012-02-17 01:35:32 +0000666 StmtResult SubStmt;
667
668 if (Tok.isNot(tok::r_brace)) {
669 SubStmt = ParseStatement();
670 } else {
671 // Diagnose the common error "switch (X) {... default: }", which is
672 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000673 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000674 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
675 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
676 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 }
678
Richard Smith85b29a42012-02-17 01:35:32 +0000679 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000680 if (SubStmt.isInvalid())
Richard Smith85b29a42012-02-17 01:35:32 +0000681 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000682
Sebastian Redl117054a2008-12-28 16:13:43 +0000683 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000684 SubStmt.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +0000685}
686
Richard Smith534986f2012-04-14 00:33:13 +0000687StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
688 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregorbca01b42011-07-06 22:04:06 +0000689}
Reid Spencer5f016e22007-07-11 17:01:13 +0000690
691/// ParseCompoundStatement - Parse a "{}" block.
692///
693/// compound-statement: [C99 6.8.2]
694/// { block-item-list[opt] }
695/// [GNU] { label-declarations block-item-list } [TODO]
696///
697/// block-item-list:
698/// block-item
699/// block-item-list block-item
700///
701/// block-item:
702/// declaration
Chris Lattner45a566c2007-08-27 01:01:57 +0000703/// [GNU] '__extension__' declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000704/// statement
705/// [OMP] openmp-directive [TODO]
706///
707/// [GNU] label-declarations:
708/// [GNU] label-declaration
709/// [GNU] label-declarations label-declaration
710///
711/// [GNU] label-declaration:
712/// [GNU] '__label__' identifier-list ';'
713///
714/// [OMP] openmp-directive: [TODO]
715/// [OMP] barrier-directive
716/// [OMP] flush-directive
717///
Richard Smith534986f2012-04-14 00:33:13 +0000718StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000719 unsigned ScopeFlags) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000720 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000721
Chris Lattner31e05722007-08-26 06:24:45 +0000722 // Enter a scope to hold everything within the compound stmt. Compound
723 // statements can always hold declarations.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000724 ParseScope CompoundScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000725
726 // Parse the statements in the body.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000727 return ParseCompoundStatementBody(isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000728}
729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff1b273c42007-09-16 14:56:35 +0000731/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Reid Spencer5f016e22007-07-11 17:01:13 +0000732/// consume the '}' at the end of the block. It does not manipulate the scope
733/// stack.
John McCall60d7b3a2010-08-24 06:29:42 +0000734StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump1eb44332009-09-09 15:08:12 +0000735 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerae50fa02009-03-05 00:00:31 +0000736 Tok.getLocation(),
737 "in compound statement ('{}')");
Douglas Gregor0fbda682010-09-15 14:51:05 +0000738 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000739 BalancedDelimiterTracker T(*this, tok::l_brace);
740 if (T.consumeOpen())
741 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000742
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000743 Sema::CompoundScopeRAII CompoundScope(Actions);
744
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000745 StmtVector Stmts(Actions);
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000746
Chris Lattner4ae493c2011-02-18 02:08:43 +0000747 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
748 // only allowed at the start of a compound stmt regardless of the language.
749 while (Tok.is(tok::kw___label__)) {
750 SourceLocation LabelLoc = ConsumeToken();
751 Diag(LabelLoc, diag::ext_gnu_local_label);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000752
Chris Lattner5f9e2722011-07-23 10:55:15 +0000753 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000754 while (1) {
755 if (Tok.isNot(tok::identifier)) {
756 Diag(Tok, diag::err_expected_ident);
757 break;
758 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000759
Chris Lattner4ae493c2011-02-18 02:08:43 +0000760 IdentifierInfo *II = Tok.getIdentifierInfo();
761 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara67843042011-03-05 18:21:20 +0000762 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000763
Chris Lattner4ae493c2011-02-18 02:08:43 +0000764 if (!Tok.is(tok::comma))
765 break;
766 ConsumeToken();
767 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000768
John McCall0b7e6782011-03-24 11:26:52 +0000769 DeclSpec DS(AttrFactory);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000770 DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
771 DeclsInGroup.data(), DeclsInGroup.size());
772 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000773
Chris Lattner8bb21d32012-04-28 16:12:17 +0000774 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000775 if (R.isUsable())
776 Stmts.push_back(R.release());
777 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000778
Chris Lattner4ae493c2011-02-18 02:08:43 +0000779 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000780 if (Tok.is(tok::annot_pragma_unused)) {
781 HandlePragmaUnused();
782 continue;
783 }
784
David Blaikie4e4d0842012-03-11 07:00:24 +0000785 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet1e862692011-05-06 20:48:22 +0000786 Tok.is(tok::kw___if_not_exists))) {
787 ParseMicrosoftIfExistsStatement(Stmts);
788 continue;
789 }
790
John McCall60d7b3a2010-08-24 06:29:42 +0000791 StmtResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000792 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000793 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattner45a566c2007-08-27 01:01:57 +0000794 } else {
795 // __extension__ can start declarations and it can also be a unary
796 // operator for expressions. Consume multiple __extension__ markers here
797 // until we can determine which is which.
Eli Friedmanadf077f2009-01-27 08:43:38 +0000798 // FIXME: This loses extension expressions in the AST!
Chris Lattner45a566c2007-08-27 01:01:57 +0000799 SourceLocation ExtLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000800 while (Tok.is(tok::kw___extension__))
Chris Lattner45a566c2007-08-27 01:01:57 +0000801 ConsumeToken();
Chris Lattner39146d62008-10-20 06:51:33 +0000802
John McCall0b7e6782011-03-24 11:26:52 +0000803 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith6ee326a2012-04-10 01:32:12 +0000804 MaybeParseCXX0XAttributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000805
Chris Lattner45a566c2007-08-27 01:01:57 +0000806 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis5404a152008-10-05 00:06:24 +0000807 if (isDeclarationStatement()) {
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000808 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner97144fc2009-04-02 04:16:50 +0000809 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000810 ExtensionRAIIObject O(Diags);
811
Chris Lattner97144fc2009-04-02 04:16:50 +0000812 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000813 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
814 Declarator::BlockContext, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000815 attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000816 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattner45a566c2007-08-27 01:01:57 +0000817 } else {
Eli Friedmanadf077f2009-01-27 08:43:38 +0000818 // Otherwise this was a unary __extension__ marker.
John McCall60d7b3a2010-08-24 06:29:42 +0000819 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattner043a0b52008-03-13 06:32:11 +0000820
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000821 if (Res.isInvalid()) {
Chris Lattner45a566c2007-08-27 01:01:57 +0000822 SkipUntil(tok::semi);
823 continue;
824 }
Sebastian Redlf512e822009-01-18 18:03:53 +0000825
Sean Huntbbd37c62009-11-21 08:43:09 +0000826 // FIXME: Use attributes?
Chris Lattner39146d62008-10-20 06:51:33 +0000827 // Eat the semicolon at the end of stmt and convert the expr into a
828 // statement.
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000829 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
John McCall9ae2f072010-08-23 23:25:46 +0000830 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
Chris Lattner45a566c2007-08-27 01:01:57 +0000831 }
832 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000833
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000834 if (R.isUsable())
Sebastian Redleffa8d12008-12-10 00:02:53 +0000835 Stmts.push_back(R.release());
Reid Spencer5f016e22007-07-11 17:01:13 +0000836 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000837
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000838 SourceLocation CloseLoc = Tok.getLocation();
839
Reid Spencer5f016e22007-07-11 17:01:13 +0000840 // We broke out of the while loop because we found a '}' or EOF.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000841 if (Tok.isNot(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 Diag(Tok, diag::err_expected_rbrace);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000843 Diag(T.getOpenLocation(), diag::note_matching) << "{";
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000844 // Recover by creating a compound statement with what we parsed so far,
845 // instead of dropping everything and returning StmtError();
846 } else {
847 if (!T.consumeClose())
848 CloseLoc = T.getCloseLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000849 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000850
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000851 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000852 move_arg(Stmts), isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000853}
854
Chris Lattner15ff1112008-12-12 06:31:07 +0000855/// ParseParenExprOrCondition:
856/// [C ] '(' expression ')'
Chris Lattnerff871fb2008-12-12 06:35:28 +0000857/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattner15ff1112008-12-12 06:31:07 +0000858///
859/// This function parses and performs error recovery on the specified condition
860/// or expression (depending on whether we're in C++ or C mode). This function
861/// goes out of its way to recover well. It returns true if there was a parser
862/// error (the right paren couldn't be found), which indicates that the caller
863/// should try to recover harder. It returns false if the condition is
864/// successfully parsed. Note that a successful parse can still have semantic
865/// errors in the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000866bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCalld226f652010-08-21 09:40:31 +0000867 Decl *&DeclResult,
Douglas Gregor586596f2010-05-06 17:25:47 +0000868 SourceLocation Loc,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000869 bool ConvertToBoolean) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000870 BalancedDelimiterTracker T(*this, tok::l_paren);
871 T.consumeOpen();
872
David Blaikie4e4d0842012-03-11 07:00:24 +0000873 if (getLangOpts().CPlusPlus)
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000874 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000875 else {
876 ExprResult = ParseExpression();
John McCalld226f652010-08-21 09:40:31 +0000877 DeclResult = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000878
Douglas Gregor586596f2010-05-06 17:25:47 +0000879 // If required, convert to a boolean value.
880 if (!ExprResult.isInvalid() && ConvertToBoolean)
881 ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000882 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000883 }
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Chris Lattner15ff1112008-12-12 06:31:07 +0000885 // If the parser was confused by the condition and we don't have a ')', try to
886 // recover by skipping ahead to a semi and bailing out. If condexp is
887 // semantically invalid but we have well formed code, keep going.
John McCalld226f652010-08-21 09:40:31 +0000888 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattner15ff1112008-12-12 06:31:07 +0000889 SkipUntil(tok::semi);
890 // Skipping may have stopped if it found the containing ')'. If so, we can
891 // continue parsing the if statement.
892 if (Tok.isNot(tok::r_paren))
893 return true;
894 }
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner15ff1112008-12-12 06:31:07 +0000896 // Otherwise the condition is valid or the rparen is present.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000897 T.consumeClose();
Chris Lattnerbddc7e52012-04-28 16:24:20 +0000898
899 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
900 // that all callers are looking for a statement after the condition, so ")"
901 // isn't valid.
902 while (Tok.is(tok::r_paren)) {
903 Diag(Tok, diag::err_extraneous_rparen_in_condition)
904 << FixItHint::CreateRemoval(Tok.getLocation());
905 ConsumeParen();
906 }
907
Chris Lattner15ff1112008-12-12 06:31:07 +0000908 return false;
909}
910
911
Reid Spencer5f016e22007-07-11 17:01:13 +0000912/// ParseIfStatement
913/// if-statement: [C99 6.8.4.1]
914/// 'if' '(' expression ')' statement
915/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000916/// [C++] 'if' '(' condition ')' statement
917/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +0000918///
Richard Smith534986f2012-04-14 00:33:13 +0000919StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000920 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
922
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000923 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000924 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000926 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000928
David Blaikie4e4d0842012-03-11 07:00:24 +0000929 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000930
Chris Lattner22153252007-08-26 23:08:06 +0000931 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
932 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000933 //
934 // C++ 6.4p3:
935 // A name introduced by a declaration in a condition is in scope from its
936 // point of declaration until the end of the substatements controlled by the
937 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +0000938 // C++ 3.3.2p4:
939 // Names declared in the for-init-statement, and in the condition of if,
940 // while, for, and switch statements are local to the if, while, for, or
941 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000942 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000943 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +0000944
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000946 ExprResult CondExp;
John McCalld226f652010-08-21 09:40:31 +0000947 Decl *CondVar = 0;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000948 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +0000949 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +0000950
John McCall9ae2f072010-08-23 23:25:46 +0000951 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Chris Lattner0ecea032007-08-22 05:28:50 +0000953 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000954 // there is no compound stmt. C90 does not have this clause. We only do this
955 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000956 //
957 // C++ 6.4p1:
958 // The substatement in a selection-statement (each substatement, in the else
959 // form of the if statement) implicitly defines a local scope.
960 //
961 // For C++ we create a scope for the condition and a new scope for
962 // substatements because:
963 // -When the 'then' scope exits, we want the condition declaration to still be
964 // active for the 'else' scope too.
965 // -Sema will detect name clashes by considering declarations of a
966 // 'ControlScope' as part of its direct subscope.
967 // -If we wanted the condition and substatement to be in the same scope, we
968 // would have to notify ParseStatement not to create a new scope. It's
969 // simpler to let it create a new scope.
970 //
Mike Stump1eb44332009-09-09 15:08:12 +0000971 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000972 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000973
Chris Lattnerb96728d2007-10-29 05:08:52 +0000974 // Read the 'then' stmt.
975 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +0000976
977 SourceLocation InnerStatementTrailingElseLoc;
978 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000979
Chris Lattnera36ce712007-08-22 05:16:28 +0000980 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000981 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000982
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 // If it has an else, parse it.
984 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +0000985 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000986 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000987
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000988 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +0000989 if (TrailingElseLoc)
990 *TrailingElseLoc = Tok.getLocation();
991
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +0000993 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000994
Chris Lattner0ecea032007-08-22 05:28:50 +0000995 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000996 // there is no compound stmt. C90 does not have this clause. We only do
997 // this if the body isn't a compound statement to avoid push/pop in common
998 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000999 //
1000 // C++ 6.4p1:
1001 // The substatement in a selection-statement (each substatement, in the else
1002 // form of the if statement) implicitly defines a local scope.
1003 //
Sebastian Redl61364dd2008-12-11 19:30:53 +00001004 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001005 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001006
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001008
Chris Lattnera36ce712007-08-22 05:16:28 +00001009 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001010 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +00001011 } else if (Tok.is(tok::code_completion)) {
1012 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001013 cutOffParsing();
1014 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +00001015 } else if (InnerStatementTrailingElseLoc.isValid()) {
1016 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001018
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001019 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Chris Lattner18914bc2008-12-12 06:19:11 +00001021 // If the condition was invalid, discard the if statement. We could recover
1022 // better by replacing it with a valid expr, but don't do that yet.
John McCalld226f652010-08-21 09:40:31 +00001023 if (CondExp.isInvalid() && !CondVar)
Chris Lattner18914bc2008-12-12 06:19:11 +00001024 return StmtError();
Chris Lattner22153252007-08-26 23:08:06 +00001025
Chris Lattnerb96728d2007-10-29 05:08:52 +00001026 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +00001027 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +00001028 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001029 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1030 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1031 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +00001032 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +00001033 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +00001034 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001035
Chris Lattnerb96728d2007-10-29 05:08:52 +00001036 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001037 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001038 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001039 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001040 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001041
John McCall9ae2f072010-08-23 23:25:46 +00001042 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001043 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001044}
1045
1046/// ParseSwitchStatement
1047/// switch-statement:
1048/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001049/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001050StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001051 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1053
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001054 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001055 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001057 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001058 }
Chris Lattner22153252007-08-26 23:08:06 +00001059
David Blaikie4e4d0842012-03-11 07:00:24 +00001060 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001061
Chris Lattner22153252007-08-26 23:08:06 +00001062 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1063 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001064 //
1065 // C++ 6.4p3:
1066 // A name introduced by a declaration in a condition is in scope from its
1067 // point of declaration until the end of the substatements controlled by the
1068 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001069 // C++ 3.3.2p4:
1070 // Names declared in the for-init-statement, and in the condition of if,
1071 // while, for, and switch statements are local to the if, while, for, or
1072 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001073 //
Richard Trieubb9b80c2011-04-21 21:44:26 +00001074 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001075 if (C99orCXX)
1076 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001077 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001078
1079 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001080 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001081 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001082 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001083 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001084
John McCall60d7b3a2010-08-24 06:29:42 +00001085 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001086 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001087
Douglas Gregor586596f2010-05-06 17:25:47 +00001088 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001089 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001090 // FIXME: This is not optimal recovery, but parsing the body is more
1091 // dangerous due to the presence of case and default statements, which
1092 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001093 if (Tok.is(tok::l_brace)) {
1094 ConsumeBrace();
1095 SkipUntil(tok::r_brace, false, false);
1096 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001097 SkipUntil(tok::semi);
1098 return move(Switch);
1099 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001100
Chris Lattner0ecea032007-08-22 05:28:50 +00001101 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001102 // there is no compound stmt. C90 does not have this clause. We only do this
1103 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001104 //
1105 // C++ 6.4p1:
1106 // The substatement in a selection-statement (each substatement, in the else
1107 // form of the if statement) implicitly defines a local scope.
1108 //
1109 // See comments in ParseIfStatement for why we create a scope for the
1110 // condition and a new scope for substatement in C++.
1111 //
Mike Stump1eb44332009-09-09 15:08:12 +00001112 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001113 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001114
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001116 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001117
Chris Lattner7e52de42010-01-24 01:50:29 +00001118 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001119 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001120 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001121
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001122 if (Body.isInvalid()) {
Chris Lattner7e52de42010-01-24 01:50:29 +00001123 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001124
1125 // Put the synthesized null statement on the same line as the end of switch
1126 // condition.
1127 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1128 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1129 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001130
John McCall9ae2f072010-08-23 23:25:46 +00001131 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001132}
1133
1134/// ParseWhileStatement
1135/// while-statement: [C99 6.8.5.1]
1136/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001137/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001138StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001139 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 SourceLocation WhileLoc = Tok.getLocation();
1141 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001142
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001143 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001144 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001146 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001148
David Blaikie4e4d0842012-03-11 07:00:24 +00001149 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001150
Chris Lattner22153252007-08-26 23:08:06 +00001151 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1152 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001153 //
1154 // C++ 6.4p3:
1155 // A name introduced by a declaration in a condition is in scope from its
1156 // point of declaration until the end of the substatements controlled by the
1157 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001158 // C++ 3.3.2p4:
1159 // Names declared in the for-init-statement, and in the condition of if,
1160 // while, for, and switch statements are local to the if, while, for, or
1161 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001162 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001163 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001164 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001165 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1166 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001167 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001168 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1169 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001170
1171 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001172 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001173 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001174 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001175 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001176
John McCall9ae2f072010-08-23 23:25:46 +00001177 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Chris Lattner0ecea032007-08-22 05:28:50 +00001179 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001180 // there is no compound stmt. C90 does not have this clause. We only do this
1181 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001182 //
1183 // C++ 6.5p2:
1184 // The substatement in an iteration-statement implicitly defines a local scope
1185 // which is entered and exited each time through the loop.
1186 //
1187 // See comments in ParseIfStatement for why we create a scope for the
1188 // condition and a new scope for substatement in C++.
1189 //
Mike Stump1eb44332009-09-09 15:08:12 +00001190 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001191 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001192
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001194 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001195
Chris Lattner0ecea032007-08-22 05:28:50 +00001196 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001197 InnerScope.Exit();
1198 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001199
John McCalld226f652010-08-21 09:40:31 +00001200 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001201 return StmtError();
1202
John McCall9ae2f072010-08-23 23:25:46 +00001203 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001204}
1205
1206/// ParseDoStatement
1207/// do-statement: [C99 6.8.5.2]
1208/// 'do' statement 'while' '(' expression ')' ';'
1209/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001210StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001211 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001213
Chris Lattner22153252007-08-26 23:08:06 +00001214 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1215 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001216 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001217 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001218 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001219 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001220 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001221
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001222 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223
Chris Lattner0ecea032007-08-22 05:28:50 +00001224 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001225 // there is no compound stmt. C90 does not have this clause. We only do this
1226 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001227 //
1228 // C++ 6.5p2:
1229 // The substatement in an iteration-statement implicitly defines a local scope
1230 // which is entered and exited each time through the loop.
1231 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001232 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikie4e4d0842012-03-11 07:00:24 +00001233 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001234 Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001235
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001237 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001238
Chris Lattner0ecea032007-08-22 05:28:50 +00001239 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001240 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001241
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001242 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001243 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001244 Diag(Tok, diag::err_expected_while);
Chris Lattner28eb7e92008-11-23 23:17:07 +00001245 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner19504402008-11-13 18:52:53 +00001246 SkipUntil(tok::semi, false, true);
1247 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001248 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 }
1250 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001251
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001252 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001253 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner19504402008-11-13 18:52:53 +00001254 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001255 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001257
Chris Lattnerff871fb2008-12-12 06:35:28 +00001258 // Parse the parenthesized condition.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001259 BalancedDelimiterTracker T(*this, tok::l_paren);
1260 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00001261 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001262 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001263 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001264
Sebastian Redl9a920342008-12-11 19:48:14 +00001265 if (Cond.isInvalid() || Body.isInvalid())
1266 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001267
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001268 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1269 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001270}
1271
1272/// ParseForStatement
1273/// for-statement: [C99 6.8.5.3]
1274/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1275/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001276/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1277/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001278/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001279/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1280/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001281///
1282/// [C++] for-init-statement:
1283/// [C++] expression-statement
1284/// [C++] simple-declaration
1285///
Richard Smithad762fc2011-04-14 22:09:26 +00001286/// [C++0x] for-range-declaration:
1287/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1288/// [C++0x] for-range-initializer:
1289/// [C++0x] expression
1290/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001291StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001292 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001294
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001295 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001296 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001298 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001300
David Blaikie4e4d0842012-03-11 07:00:24 +00001301 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus || getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001302
Chris Lattner22153252007-08-26 23:08:06 +00001303 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1304 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001305 //
1306 // C++ 6.4p3:
1307 // A name introduced by a declaration in a condition is in scope from its
1308 // point of declaration until the end of the substatements controlled by the
1309 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001310 // C++ 3.3.2p4:
1311 // Names declared in the for-init-statement, and in the condition of if,
1312 // while, for, and switch statements are local to the if, while, for, or
1313 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001314 // C++ 6.5.3p1:
1315 // Names declared in the for-init-statement are in the same declarative-region
1316 // as those declared in the condition.
1317 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001318 unsigned ScopeFlags;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001319 if (C99orCXXorObjC)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001320 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1321 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001322 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001323 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1324
1325 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001327 BalancedDelimiterTracker T(*this, tok::l_paren);
1328 T.consumeOpen();
1329
John McCall60d7b3a2010-08-24 06:29:42 +00001330 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001331
Richard Smithad762fc2011-04-14 22:09:26 +00001332 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001333 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001334 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001335 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001336 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001337 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001338 FullExprArg ThirdPart(Actions);
John McCalld226f652010-08-21 09:40:31 +00001339 Decl *SecondVar = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001340
Douglas Gregor791215b2009-09-21 20:51:25 +00001341 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001342 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001343 C99orCXXorObjC? Sema::PCC_ForInit
1344 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001345 cutOffParsing();
1346 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001347 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001348
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001350 if (Tok.is(tok::semi)) { // for (;
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // no first part, eat the ';'.
1352 ConsumeToken();
Eli Friedman9490ab42011-12-20 01:50:37 +00001353 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001355 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001357
John McCall0b7e6782011-03-24 11:26:52 +00001358 ParsedAttributesWithRange attrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +00001359 MaybeParseCXX0XAttributes(attrs);
Sean Huntbbd37c62009-11-21 08:43:09 +00001360
Richard Smithad762fc2011-04-14 22:09:26 +00001361 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001362 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001363 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1364
Chris Lattner97144fc2009-04-02 04:16:50 +00001365 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +00001366 StmtVector Stmts(Actions);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001367 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smithad762fc2011-04-14 22:09:26 +00001368 DeclEnd, attrs, false,
1369 MightBeForRangeStmt ?
1370 &ForRangeInit : 0);
Chris Lattnercd147752009-03-29 17:27:48 +00001371 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Richard Smithad762fc2011-04-14 22:09:26 +00001373 if (ForRangeInit.ParsedForRangeDecl()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001374 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001375 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001376
Richard Smithad762fc2011-04-14 22:09:26 +00001377 ForRange = true;
1378 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001379 ConsumeToken();
1380 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001381 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001382 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001383 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001384
Douglas Gregorfb629412010-08-23 21:17:50 +00001385 if (Tok.is(tok::code_completion)) {
1386 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001387 cutOffParsing();
1388 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001389 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001390 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001391 } else {
1392 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001393 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 } else {
1395 Value = ParseExpression();
1396
John McCallf6a16482010-12-04 03:47:34 +00001397 ForEach = isTokIdentifier_in();
1398
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001400 if (!Value.isInvalid()) {
1401 if (ForEach)
1402 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1403 else
1404 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1405 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001406
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001407 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001409 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001410 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001411
Douglas Gregorfb629412010-08-23 21:17:50 +00001412 if (Tok.is(tok::code_completion)) {
1413 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001414 cutOffParsing();
1415 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001416 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001417 Collection = ParseExpression();
David Blaikie4e4d0842012-03-11 07:00:24 +00001418 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001419 // User tried to write the reasonable, but ill-formed, for-range-statement
1420 // for (expr : expr) { ... }
1421 Diag(Tok, diag::err_for_range_expected_decl)
1422 << FirstPart.get()->getSourceRange();
1423 SkipUntil(tok::r_paren, false, true);
1424 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001425 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001426 if (!Value.isInvalid()) {
1427 Diag(Tok, diag::err_expected_semi_for);
1428 } else {
1429 // Skip until semicolon or rparen, don't consume it.
1430 SkipUntil(tok::r_paren, true, true);
1431 if (Tok.is(tok::semi))
1432 ConsumeToken();
1433 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 }
1435 }
Richard Smithad762fc2011-04-14 22:09:26 +00001436 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001437 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001438 // Parse the second part of the for specifier.
1439 if (Tok.is(tok::semi)) { // for (...;;
1440 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001441 } else if (Tok.is(tok::r_paren)) {
1442 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001443 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001444 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001445 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001446 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1447 else {
1448 Second = ParseExpression();
1449 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001450 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001451 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001452 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001453 SecondPartIsInvalid = Second.isInvalid();
John McCall9ae2f072010-08-23 23:25:46 +00001454 SecondPart = Actions.MakeFullExpr(Second.get());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001455 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001456
Douglas Gregorb72c7782011-02-17 03:38:46 +00001457 if (Tok.isNot(tok::semi)) {
1458 if (!SecondPartIsInvalid || SecondVar)
1459 Diag(Tok, diag::err_expected_semi_for);
1460 else
1461 // Skip until semicolon or rparen, don't consume it.
1462 SkipUntil(tok::r_paren, true, true);
1463 }
1464
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001465 if (Tok.is(tok::semi)) {
1466 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001467 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001468
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001469 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001470 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001471 ExprResult Third = ParseExpression();
John McCall9ae2f072010-08-23 23:25:46 +00001472 ThirdPart = Actions.MakeFullExpr(Third.take());
Douglas Gregor586596f2010-05-06 17:25:47 +00001473 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001476 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001477
Richard Smithad762fc2011-04-14 22:09:26 +00001478 // We need to perform most of the semantic analysis for a C++0x for-range
1479 // statememt before parsing the body, in order to be able to deduce the type
1480 // of an auto-typed loop variable.
1481 StmtResult ForRangeStmt;
John McCall990567c2011-07-27 01:07:15 +00001482 if (ForRange) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001483 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, T.getOpenLocation(),
Richard Smithad762fc2011-04-14 22:09:26 +00001484 FirstPart.take(),
1485 ForRangeInit.ColonLoc,
1486 ForRangeInit.RangeExpr.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001487 T.getCloseLocation());
Richard Smithad762fc2011-04-14 22:09:26 +00001488
John McCall990567c2011-07-27 01:07:15 +00001489
1490 // Similarly, we need to do the semantic analysis for a for-range
1491 // statement immediately in order to close over temporaries correctly.
1492 } else if (ForEach) {
1493 if (!Collection.isInvalid())
1494 Collection =
1495 Actions.ActOnObjCForCollectionOperand(ForLoc, Collection.take());
1496 }
1497
Chris Lattner0ecea032007-08-22 05:28:50 +00001498 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001499 // there is no compound stmt. C90 does not have this clause. We only do this
1500 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001501 //
1502 // C++ 6.5p2:
1503 // The substatement in an iteration-statement implicitly defines a local scope
1504 // which is entered and exited each time through the loop.
1505 //
1506 // See comments in ParseIfStatement for why we create a scope for
1507 // for-init-statement/condition and a new scope for substatement in C++.
1508 //
Mike Stump1eb44332009-09-09 15:08:12 +00001509 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001510 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001511
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001513 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001514
Chris Lattner0ecea032007-08-22 05:28:50 +00001515 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001516 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001517
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001519 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001520
1521 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001522 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001523
Richard Smithad762fc2011-04-14 22:09:26 +00001524 if (ForEach)
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001525 return Actions.ActOnObjCForCollectionStmt(ForLoc, T.getOpenLocation(),
1526 FirstPart.take(),
1527 Collection.take(),
1528 T.getCloseLocation(),
1529 Body.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Richard Smithad762fc2011-04-14 22:09:26 +00001531 if (ForRange)
1532 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1533
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001534 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1535 SecondPart, SecondVar, ThirdPart,
1536 T.getCloseLocation(), Body.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001537}
1538
1539/// ParseGotoStatement
1540/// jump-statement:
1541/// 'goto' identifier ';'
1542/// [GNU] 'goto' '*' expression ';'
1543///
1544/// Note: this lets the caller parse the end ';'.
1545///
Richard Smith534986f2012-04-14 00:33:13 +00001546StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001547 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001549
John McCall60d7b3a2010-08-24 06:29:42 +00001550 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001551 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001552 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1553 Tok.getLocation());
1554 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001556 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 // GNU indirect goto extension.
1558 Diag(Tok, diag::ext_gnu_indirect_goto);
1559 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001560 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001561 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001563 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 }
John McCall9ae2f072010-08-23 23:25:46 +00001565 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattner95cfb852007-07-22 04:13:33 +00001566 } else {
1567 Diag(Tok, diag::err_expected_ident);
Sebastian Redl9a920342008-12-11 19:48:14 +00001568 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001570
Sebastian Redl9a920342008-12-11 19:48:14 +00001571 return move(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572}
1573
1574/// ParseContinueStatement
1575/// jump-statement:
1576/// 'continue' ';'
1577///
1578/// Note: this lets the caller parse the end ';'.
1579///
Richard Smith534986f2012-04-14 00:33:13 +00001580StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001582 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001583}
1584
1585/// ParseBreakStatement
1586/// jump-statement:
1587/// 'break' ';'
1588///
1589/// Note: this lets the caller parse the end ';'.
1590///
Richard Smith534986f2012-04-14 00:33:13 +00001591StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001593 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001594}
1595
1596/// ParseReturnStatement
1597/// jump-statement:
1598/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001599StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001600 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001602
John McCall60d7b3a2010-08-24 06:29:42 +00001603 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001604 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001605 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001606 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001607 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001608 return StmtError();
1609 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001610
David Blaikie4e4d0842012-03-11 07:00:24 +00001611 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001612 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001613 if (R.isUsable())
David Blaikie4e4d0842012-03-11 07:00:24 +00001614 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001615 diag::warn_cxx98_compat_generalized_initializer_lists :
1616 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001617 << R.get()->getSourceRange();
1618 } else
1619 R = ParseExpression();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001620 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001622 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 }
1624 }
John McCall9ae2f072010-08-23 23:25:46 +00001625 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001626}
1627
Eli Friedman3fedbe12011-09-30 01:13:51 +00001628/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1629/// this routine is called to collect the tokens for an MS asm statement.
1630StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1631 SourceManager &SrcMgr = PP.getSourceManager();
1632 SourceLocation EndLoc = AsmLoc;
1633 do {
1634 bool InBraces = false;
NAKAMURA Takumi96e21712011-10-08 11:31:53 +00001635 unsigned short savedBraceCount = 0;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001636 bool InAsmComment = false;
1637 FileID FID;
NAKAMURA Takumi96e21712011-10-08 11:31:53 +00001638 unsigned LineNo = 0;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001639 unsigned NumTokensRead = 0;
1640 SourceLocation LBraceLoc;
1641
1642 if (Tok.is(tok::l_brace)) {
1643 // Braced inline asm: consume the opening brace.
1644 InBraces = true;
1645 savedBraceCount = BraceCount;
1646 EndLoc = LBraceLoc = ConsumeBrace();
1647 ++NumTokensRead;
1648 } else {
1649 // Single-line inline asm; compute which line it is on.
1650 std::pair<FileID, unsigned> ExpAsmLoc =
1651 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1652 FID = ExpAsmLoc.first;
1653 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1654 }
1655
Steve Naroff03d6bc62008-02-08 03:36:19 +00001656 SourceLocation TokLoc = Tok.getLocation();
Steve Naroff36280972008-02-08 18:01:27 +00001657 do {
Eli Friedman3fedbe12011-09-30 01:13:51 +00001658 // If we hit EOF, we're done, period.
1659 if (Tok.is(tok::eof))
1660 break;
1661 // When we consume the closing brace, we're done.
1662 if (InBraces && BraceCount == savedBraceCount)
1663 break;
1664
1665 if (!InAsmComment && Tok.is(tok::semi)) {
1666 // A semicolon in an asm is the start of a comment.
1667 InAsmComment = true;
1668 if (InBraces) {
1669 // Compute which line the comment is on.
1670 std::pair<FileID, unsigned> ExpSemiLoc =
1671 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1672 FID = ExpSemiLoc.first;
1673 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
1674 }
1675 } else if (!InBraces || InAsmComment) {
1676 // If end-of-line is significant, check whether this token is on a
1677 // new line.
1678 std::pair<FileID, unsigned> ExpLoc =
1679 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1680 if (ExpLoc.first != FID ||
1681 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
1682 // If this is a single-line __asm, we're done.
1683 if (!InBraces)
1684 break;
1685 // We're no longer in a comment.
1686 InAsmComment = false;
1687 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
1688 // Single-line asm always ends when a closing brace is seen.
1689 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
1690 // does MSVC do here?
1691 break;
1692 }
1693 }
1694
1695 // Consume the next token; make sure we don't modify the brace count etc.
1696 // if we are in a comment.
Abramo Bagnaraa44724d2010-12-02 18:34:55 +00001697 EndLoc = TokLoc;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001698 if (InAsmComment)
1699 PP.Lex(Tok);
1700 else
1701 ConsumeAnyToken();
Steve Naroff36280972008-02-08 18:01:27 +00001702 TokLoc = Tok.getLocation();
Eli Friedman3fedbe12011-09-30 01:13:51 +00001703 ++NumTokensRead;
1704 } while (1);
1705
1706 if (InBraces && BraceCount != savedBraceCount) {
1707 // __asm without closing brace (this can happen at EOF).
1708 Diag(Tok, diag::err_expected_rbrace);
1709 Diag(LBraceLoc, diag::note_matching) << "{";
1710 return StmtError();
1711 } else if (NumTokensRead == 0) {
1712 // Empty __asm.
1713 Diag(Tok, diag::err_expected_lbrace);
1714 return StmtError();
1715 }
1716 // Multiple adjacent asm's form together into a single asm statement
1717 // in the AST.
1718 if (!Tok.is(tok::kw_asm))
1719 break;
1720 EndLoc = ConsumeToken();
1721 } while (1);
1722 // FIXME: Need to actually grab the data and pass it on to Sema. Ideally,
1723 // what Sema wants is a string of the entire inline asm, with one instruction
1724 // per line and all the __asm keywords stripped out, and a way of mapping
1725 // from any character of that string to its location in the original source
1726 // code. I'm not entirely sure how to go about that, though.
Mike Stump95059b52009-12-11 00:04:56 +00001727 Token t;
1728 t.setKind(tok::string_literal);
Chris Lattnere7896852010-08-17 16:00:12 +00001729 t.setLiteralData("\"/*FIXME: not done*/\"");
Mike Stump95059b52009-12-11 00:04:56 +00001730 t.clearFlag(Token::NeedsCleaning);
Chris Lattnere7896852010-08-17 16:00:12 +00001731 t.setLength(21);
Sean Hunt6cf75022010-08-30 17:47:05 +00001732 ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
Mike Stump95059b52009-12-11 00:04:56 +00001733 ExprVector Constraints(Actions);
1734 ExprVector Exprs(Actions);
1735 ExprVector Clobbers(Actions);
Abramo Bagnaraa44724d2010-12-02 18:34:55 +00001736 return Actions.ActOnAsmStmt(AsmLoc, true, true, 0, 0, 0,
Mike Stump95059b52009-12-11 00:04:56 +00001737 move_arg(Constraints), move_arg(Exprs),
John McCall9ae2f072010-08-23 23:25:46 +00001738 AsmString.take(), move_arg(Clobbers),
Abramo Bagnaraa44724d2010-12-02 18:34:55 +00001739 EndLoc, true);
Steve Naroffd62701b2008-02-07 03:50:06 +00001740}
1741
Reid Spencer5f016e22007-07-11 17:01:13 +00001742/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff5f8aa692008-02-11 23:15:56 +00001743/// asm-statement:
1744/// gnu-asm-statement
1745/// ms-asm-statement
1746///
1747/// [GNU] gnu-asm-statement:
Reid Spencer5f016e22007-07-11 17:01:13 +00001748/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1749///
1750/// [GNU] asm-argument:
1751/// asm-string-literal
1752/// asm-string-literal ':' asm-operands[opt]
1753/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1754/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1755/// ':' asm-clobbers
1756///
1757/// [GNU] asm-clobbers:
1758/// asm-string-literal
1759/// asm-clobbers ',' asm-string-literal
1760///
Steve Naroff5f8aa692008-02-11 23:15:56 +00001761/// [MS] ms-asm-statement:
Eli Friedman3fedbe12011-09-30 01:13:51 +00001762/// ms-asm-block
1763/// ms-asm-block ms-asm-statement
Steve Naroff5f8aa692008-02-11 23:15:56 +00001764///
Eli Friedman3fedbe12011-09-30 01:13:51 +00001765/// [MS] ms-asm-block:
1766/// '__asm' ms-asm-line '\n'
1767/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1768///
1769/// [MS] ms-asm-instruction-block
1770/// ms-asm-line
1771/// ms-asm-line '\n' ms-asm-instruction-block
Steve Naroff5f8aa692008-02-11 23:15:56 +00001772///
John McCall60d7b3a2010-08-24 06:29:42 +00001773StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001774 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattnerfe795952007-10-29 04:04:16 +00001775 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001776
David Blaikie4e4d0842012-03-11 07:00:24 +00001777 if (getLangOpts().MicrosoftExt && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
Steve Naroffd62701b2008-02-07 03:50:06 +00001778 msAsm = true;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001779 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00001780 }
John McCall0b7e6782011-03-24 11:26:52 +00001781 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 SourceLocation Loc = Tok.getLocation();
Sean Huntbbd37c62009-11-21 08:43:09 +00001783 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redl9a920342008-12-11 19:48:14 +00001784
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1786 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner1ab3b962008-11-18 07:48:38 +00001787 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner1ab3b962008-11-18 07:48:38 +00001789 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Sebastian Redl9a920342008-12-11 19:48:14 +00001790
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 // Remember if this was a volatile asm.
Anders Carlsson39c47b52007-11-23 23:12:25 +00001792 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001793 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001794 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 SkipUntil(tok::r_paren);
Sebastian Redl9a920342008-12-11 19:48:14 +00001796 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001798 BalancedDelimiterTracker T(*this, tok::l_paren);
1799 T.consumeOpen();
Sebastian Redl9a920342008-12-11 19:48:14 +00001800
John McCall60d7b3a2010-08-24 06:29:42 +00001801 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenek320fa4b2011-12-02 01:30:14 +00001802 if (AsmString.isInvalid()) {
Richard Smith99831e42012-03-06 03:21:47 +00001803 // Consume up to and including the closing paren.
1804 T.skipToEnd();
Sebastian Redl9a920342008-12-11 19:48:14 +00001805 return StmtError();
Ted Kremenek320fa4b2011-12-02 01:30:14 +00001806 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001807
Chris Lattner5f9e2722011-07-23 10:55:15 +00001808 SmallVector<IdentifierInfo *, 4> Names;
Sebastian Redla55e52c2008-11-25 22:21:31 +00001809 ExprVector Constraints(Actions);
1810 ExprVector Exprs(Actions);
1811 ExprVector Clobbers(Actions);
Reid Spencer5f016e22007-07-11 17:01:13 +00001812
Anders Carlssondfab34a2008-02-05 23:03:50 +00001813 if (Tok.is(tok::r_paren)) {
Chris Lattner64cb4752009-12-20 23:00:41 +00001814 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001815 T.consumeClose();
Chris Lattner64cb4752009-12-20 23:00:41 +00001816 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001817 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
Chris Lattner64cb4752009-12-20 23:00:41 +00001818 move_arg(Constraints), move_arg(Exprs),
John McCall9ae2f072010-08-23 23:25:46 +00001819 AsmString.take(), move_arg(Clobbers),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001820 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001822
Chris Lattner64cb4752009-12-20 23:00:41 +00001823 // Parse Outputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001824 bool AteExtraColon = false;
1825 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1826 // In C++ mode, parse "::" like ": :".
1827 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattner64cb4752009-12-20 23:00:41 +00001828 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001829
Chris Lattner64056462009-12-20 23:08:04 +00001830 if (!AteExtraColon &&
1831 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00001832 return StmtError();
1833 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001834
Chris Lattner64cb4752009-12-20 23:00:41 +00001835 unsigned NumOutputs = Names.size();
1836
1837 // Parse Inputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001838 if (AteExtraColon ||
1839 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1840 // In C++ mode, parse "::" like ": :".
1841 if (AteExtraColon)
1842 AteExtraColon = false;
1843 else {
1844 AteExtraColon = Tok.is(tok::coloncolon);
1845 ConsumeToken();
1846 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001847
Chris Lattner64056462009-12-20 23:08:04 +00001848 if (!AteExtraColon &&
1849 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00001850 return StmtError();
1851 }
1852
1853 assert(Names.size() == Constraints.size() &&
1854 Constraints.size() == Exprs.size() &&
1855 "Input operand size mismatch!");
1856
1857 unsigned NumInputs = Names.size() - NumOutputs;
1858
1859 // Parse the clobbers, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001860 if (AteExtraColon || Tok.is(tok::colon)) {
1861 if (!AteExtraColon)
1862 ConsumeToken();
Chris Lattner64cb4752009-12-20 23:00:41 +00001863
Chandler Carruth102e1b62010-07-22 07:11:21 +00001864 // Parse the asm-string list for clobbers if present.
1865 if (Tok.isNot(tok::r_paren)) {
1866 while (1) {
John McCall60d7b3a2010-08-24 06:29:42 +00001867 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattner64cb4752009-12-20 23:00:41 +00001868
Chandler Carruth102e1b62010-07-22 07:11:21 +00001869 if (Clobber.isInvalid())
1870 break;
Chris Lattner64cb4752009-12-20 23:00:41 +00001871
Chandler Carruth102e1b62010-07-22 07:11:21 +00001872 Clobbers.push_back(Clobber.release());
Chris Lattner64cb4752009-12-20 23:00:41 +00001873
Chandler Carruth102e1b62010-07-22 07:11:21 +00001874 if (Tok.isNot(tok::comma)) break;
1875 ConsumeToken();
1876 }
Chris Lattner64cb4752009-12-20 23:00:41 +00001877 }
1878 }
1879
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001880 T.consumeClose();
Chris Lattner64cb4752009-12-20 23:00:41 +00001881 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001882 NumOutputs, NumInputs, Names.data(),
Sebastian Redlf512e822009-01-18 18:03:53 +00001883 move_arg(Constraints), move_arg(Exprs),
John McCall9ae2f072010-08-23 23:25:46 +00001884 AsmString.take(), move_arg(Clobbers),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001885 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001886}
1887
1888/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattner64cb4752009-12-20 23:00:41 +00001889/// asm-statement, assuming the leading ':' token was eaten.
Reid Spencer5f016e22007-07-11 17:01:13 +00001890///
1891/// [GNU] asm-operands:
1892/// asm-operand
1893/// asm-operands ',' asm-operand
1894///
1895/// [GNU] asm-operand:
1896/// asm-string-literal '(' expression ')'
1897/// '[' identifier ']' asm-string-literal '(' expression ')'
1898///
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00001899//
1900// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001901bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001902 SmallVectorImpl<Expr *> &Constraints,
1903 SmallVectorImpl<Expr *> &Exprs) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 // 'asm-operands' isn't present?
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001905 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001906 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001907
1908 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 // Read the [id] if present.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001910 if (Tok.is(tok::l_square)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001911 BalancedDelimiterTracker T(*this, tok::l_square);
1912 T.consumeOpen();
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001914 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 Diag(Tok, diag::err_expected_ident);
1916 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001917 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 }
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Anders Carlssonb235fc22007-11-22 01:36:19 +00001920 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner69efba72007-10-29 04:06:22 +00001921 ConsumeToken();
Anders Carlssonb235fc22007-11-22 01:36:19 +00001922
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001923 Names.push_back(II);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001924 T.consumeClose();
Anders Carlssonb235fc22007-11-22 01:36:19 +00001925 } else
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001926 Names.push_back(0);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001927
John McCall60d7b3a2010-08-24 06:29:42 +00001928 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001929 if (Constraint.isInvalid()) {
Anders Carlssonb235fc22007-11-22 01:36:19 +00001930 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001931 return true;
Anders Carlssonb235fc22007-11-22 01:36:19 +00001932 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001933 Constraints.push_back(Constraint.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00001934
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001935 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001936 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001938 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001940
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 // Read the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001942 BalancedDelimiterTracker T(*this, tok::l_paren);
1943 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00001944 ExprResult Res(ParseExpression());
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001945 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001946 if (Res.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001948 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001950 Exprs.push_back(Res.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 // Eat the comma and continue parsing if it exists.
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001952 if (Tok.isNot(tok::comma)) return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001953 ConsumeToken();
1954 }
1955}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001956
Douglas Gregorc9977d02011-03-16 17:05:57 +00001957Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00001958 assert(Tok.is(tok::l_brace));
1959 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001960
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001961 if (SkipFunctionBodies && trySkippingFunctionBody()) {
1962 BodyScope.Exit();
1963 return Actions.ActOnFinishFunctionBody(Decl, 0);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001964 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001965
John McCallf312b1e2010-08-26 23:41:50 +00001966 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1967 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001969 // Do not enter a scope for the brace, as the arguments are in the same scope
1970 // (the function body) as the body itself. Instead, just read the statement
1971 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00001972 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00001973
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001974 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001975 if (FnBody.isInvalid()) {
1976 Sema::CompoundScopeRAII CompoundScope(Actions);
Mike Stump1eb44332009-09-09 15:08:12 +00001977 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Chris Lattner40e9bc82009-03-05 00:49:17 +00001978 MultiStmtArg(Actions), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001979 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001980
Douglas Gregorc9977d02011-03-16 17:05:57 +00001981 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00001982 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00001983}
Sebastian Redla0fd8652008-12-21 16:41:36 +00001984
Sebastian Redld3a413d2009-04-26 20:35:05 +00001985/// ParseFunctionTryBlock - Parse a C++ function-try-block.
1986///
1987/// function-try-block:
1988/// 'try' ctor-initializer[opt] compound-statement handler-seq
1989///
Douglas Gregorc9977d02011-03-16 17:05:57 +00001990Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00001991 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1992 SourceLocation TryLoc = ConsumeToken();
1993
John McCallf312b1e2010-08-26 23:41:50 +00001994 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1995 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00001996
1997 // Constructor initializer list?
1998 if (Tok.is(tok::colon))
1999 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00002000 else
2001 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002002
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002003 if (SkipFunctionBodies && trySkippingFunctionBody()) {
2004 BodyScope.Exit();
2005 return Actions.ActOnFinishFunctionBody(Decl, 0);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002006 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002007
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002008 SourceLocation LBraceLoc = Tok.getLocation();
John McCall60d7b3a2010-08-24 06:29:42 +00002009 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
Sebastian Redld3a413d2009-04-26 20:35:05 +00002010 // If we failed to parse the try-catch, we just give the function an empty
2011 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002012 if (FnBody.isInvalid()) {
2013 Sema::CompoundScopeRAII CompoundScope(Actions);
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002014 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Sebastian Redld3a413d2009-04-26 20:35:05 +00002015 MultiStmtArg(Actions), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002016 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00002017
Douglas Gregorc9977d02011-03-16 17:05:57 +00002018 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002019 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redld3a413d2009-04-26 20:35:05 +00002020}
2021
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002022bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002023 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002024 assert(SkipFunctionBodies &&
2025 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002026
2027 // We're in code-completion mode. Skip parsing for all function bodies unless
2028 // the body contains the code-completion point.
2029 TentativeParsingAction PA(*this);
2030 ConsumeBrace();
2031 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002032 /*StopAtCodeCompletion=*/PP.isCodeCompletionEnabled())) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002033 PA.Commit();
2034 return true;
2035 }
2036
2037 PA.Revert();
2038 return false;
2039}
2040
Sebastian Redla0fd8652008-12-21 16:41:36 +00002041/// ParseCXXTryBlock - Parse a C++ try-block.
2042///
2043/// try-block:
2044/// 'try' compound-statement handler-seq
2045///
Richard Smith534986f2012-04-14 00:33:13 +00002046StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002047 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2048
2049 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002050 return ParseCXXTryBlockCommon(TryLoc);
2051}
2052
2053/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2054/// function-try-block.
2055///
2056/// try-block:
2057/// 'try' compound-statement handler-seq
2058///
2059/// function-try-block:
2060/// 'try' ctor-initializer[opt] compound-statement handler-seq
2061///
2062/// handler-seq:
2063/// handler handler-seq[opt]
2064///
John Wiegley28bbe4b2011-04-28 01:08:34 +00002065/// [Borland] try-block:
2066/// 'try' compound-statement seh-except-block
2067/// 'try' compound-statment seh-finally-block
2068///
John McCall60d7b3a2010-08-24 06:29:42 +00002069StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002070 if (Tok.isNot(tok::l_brace))
2071 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Sean Huntbbd37c62009-11-21 08:43:09 +00002072 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002073
2074 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002075 Scope::DeclScope|Scope::TryScope));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002076 if (TryBlock.isInvalid())
2077 return move(TryBlock);
2078
John Wiegley28bbe4b2011-04-28 01:08:34 +00002079 // Borland allows SEH-handlers with 'try'
Douglas Gregorb57791e2011-10-21 03:57:52 +00002080
Richard Smith534986f2012-04-14 00:33:13 +00002081 if ((Tok.is(tok::identifier) &&
2082 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2083 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002084 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2085 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00002086 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002087 SourceLocation Loc = ConsumeToken();
2088 Handler = ParseSEHExceptBlock(Loc);
2089 }
2090 else {
2091 SourceLocation Loc = ConsumeToken();
2092 Handler = ParseSEHFinallyBlock(Loc);
2093 }
2094 if(Handler.isInvalid())
2095 return move(Handler);
John McCall7f040a92010-12-24 02:08:15 +00002096
John Wiegley28bbe4b2011-04-28 01:08:34 +00002097 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2098 TryLoc,
2099 TryBlock.take(),
2100 Handler.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002101 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00002102 else {
2103 StmtVector Handlers(Actions);
Richard Smith534986f2012-04-14 00:33:13 +00002104 ParsedAttributesWithRange attrs(AttrFactory);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002105 MaybeParseCXX0XAttributes(attrs);
2106 ProhibitAttributes(attrs);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002107
John Wiegley28bbe4b2011-04-28 01:08:34 +00002108 if (Tok.isNot(tok::kw_catch))
2109 return StmtError(Diag(Tok, diag::err_expected_catch));
2110 while (Tok.is(tok::kw_catch)) {
2111 StmtResult Handler(ParseCXXCatchBlock());
2112 if (!Handler.isInvalid())
2113 Handlers.push_back(Handler.release());
2114 }
2115 // Don't bother creating the full statement if we don't have any usable
2116 // handlers.
2117 if (Handlers.empty())
2118 return StmtError();
2119
2120 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
2121 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002122}
2123
2124/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2125///
2126/// handler:
2127/// 'catch' '(' exception-declaration ')' compound-statement
2128///
2129/// exception-declaration:
2130/// type-specifier-seq declarator
2131/// type-specifier-seq abstract-declarator
2132/// type-specifier-seq
2133/// '...'
2134///
John McCall60d7b3a2010-08-24 06:29:42 +00002135StmtResult Parser::ParseCXXCatchBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002136 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2137
2138 SourceLocation CatchLoc = ConsumeToken();
2139
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002140 BalancedDelimiterTracker T(*this, tok::l_paren);
2141 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redla0fd8652008-12-21 16:41:36 +00002142 return StmtError();
2143
2144 // C++ 3.3.2p3:
2145 // The name in a catch exception-declaration is local to the handler and
2146 // shall not be redeclared in the outermost block of the handler.
2147 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
2148
2149 // exception-declaration is equivalent to '...' or a parameter-declaration
2150 // without default arguments.
John McCalld226f652010-08-21 09:40:31 +00002151 Decl *ExceptionDecl = 0;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002152 if (Tok.isNot(tok::ellipsis)) {
John McCall0b7e6782011-03-24 11:26:52 +00002153 DeclSpec DS(AttrFactory);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002154 if (ParseCXXTypeSpecifierSeq(DS))
2155 return StmtError();
Sebastian Redla0fd8652008-12-21 16:41:36 +00002156 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2157 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002158 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002159 } else
2160 ConsumeToken();
2161
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002162 T.consumeClose();
2163 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002164 return StmtError();
2165
2166 if (Tok.isNot(tok::l_brace))
2167 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2168
Sean Huntbbd37c62009-11-21 08:43:09 +00002169 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002170 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002171 if (Block.isInvalid())
2172 return move(Block);
2173
John McCall9ae2f072010-08-23 23:25:46 +00002174 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002175}
Francois Pichet1e862692011-05-06 20:48:22 +00002176
2177void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002178 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002179 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002180 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002181
Douglas Gregor3896fc52011-10-24 22:31:10 +00002182 // Handle dependent statements by parsing the braces as a compound statement.
2183 // This is not the same behavior as Visual C++, which don't treat this as a
2184 // compound statement, but for Clang's type checking we can't have anything
2185 // inside these braces escaping to the surrounding code.
2186 if (Result.Behavior == IEB_Dependent) {
2187 if (!Tok.is(tok::l_brace)) {
2188 Diag(Tok, diag::err_expected_lbrace);
Richard Smith534986f2012-04-14 00:33:13 +00002189 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002190 }
Richard Smith534986f2012-04-14 00:33:13 +00002191
2192 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002193 if (Compound.isInvalid())
2194 return;
Richard Smith534986f2012-04-14 00:33:13 +00002195
Douglas Gregorba0513d2011-10-25 01:33:02 +00002196 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2197 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002198 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002199 Result.Name,
2200 Compound.get());
2201 if (DepResult.isUsable())
2202 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002203 return;
2204 }
Richard Smith534986f2012-04-14 00:33:13 +00002205
Douglas Gregor3896fc52011-10-24 22:31:10 +00002206 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2207 if (Braces.consumeOpen()) {
Francois Pichet1e862692011-05-06 20:48:22 +00002208 Diag(Tok, diag::err_expected_lbrace);
2209 return;
2210 }
Francois Pichet1e862692011-05-06 20:48:22 +00002211
Douglas Gregor3896fc52011-10-24 22:31:10 +00002212 switch (Result.Behavior) {
2213 case IEB_Parse:
2214 // Parse the statements below.
2215 break;
2216
2217 case IEB_Dependent:
2218 llvm_unreachable("Dependent case handled above");
Douglas Gregor3896fc52011-10-24 22:31:10 +00002219
2220 case IEB_Skip:
2221 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002222 return;
2223 }
2224
2225 // Condition is true, parse the statements.
2226 while (Tok.isNot(tok::r_brace)) {
2227 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2228 if (R.isUsable())
2229 Stmts.push_back(R.release());
2230 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002231 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002232}