blob: 44320dfcb3bf78a6df522d9fffc87d6dc52d6b31 [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 Lattner4ae493c2011-02-18 02:08:43 +0000774 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
775 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 Lattner15ff1112008-12-12 06:31:07 +0000898 return false;
899}
900
901
Reid Spencer5f016e22007-07-11 17:01:13 +0000902/// ParseIfStatement
903/// if-statement: [C99 6.8.4.1]
904/// 'if' '(' expression ')' statement
905/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000906/// [C++] 'if' '(' condition ')' statement
907/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +0000908///
Richard Smith534986f2012-04-14 00:33:13 +0000909StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000910 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
912
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000913 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000914 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +0000915 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000916 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000918
David Blaikie4e4d0842012-03-11 07:00:24 +0000919 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000920
Chris Lattner22153252007-08-26 23:08:06 +0000921 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
922 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000923 //
924 // C++ 6.4p3:
925 // A name introduced by a declaration in a condition is in scope from its
926 // point of declaration until the end of the substatements controlled by the
927 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +0000928 // C++ 3.3.2p4:
929 // Names declared in the for-init-statement, and in the condition of if,
930 // while, for, and switch statements are local to the if, while, for, or
931 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000932 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000933 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +0000934
Reid Spencer5f016e22007-07-11 17:01:13 +0000935 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000936 ExprResult CondExp;
John McCalld226f652010-08-21 09:40:31 +0000937 Decl *CondVar = 0;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000938 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +0000939 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +0000940
John McCall9ae2f072010-08-23 23:25:46 +0000941 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Chris Lattner0ecea032007-08-22 05:28:50 +0000943 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000944 // there is no compound stmt. C90 does not have this clause. We only do this
945 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000946 //
947 // C++ 6.4p1:
948 // The substatement in a selection-statement (each substatement, in the else
949 // form of the if statement) implicitly defines a local scope.
950 //
951 // For C++ we create a scope for the condition and a new scope for
952 // substatements because:
953 // -When the 'then' scope exits, we want the condition declaration to still be
954 // active for the 'else' scope too.
955 // -Sema will detect name clashes by considering declarations of a
956 // 'ControlScope' as part of its direct subscope.
957 // -If we wanted the condition and substatement to be in the same scope, we
958 // would have to notify ParseStatement not to create a new scope. It's
959 // simpler to let it create a new scope.
960 //
Mike Stump1eb44332009-09-09 15:08:12 +0000961 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000962 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000963
Chris Lattnerb96728d2007-10-29 05:08:52 +0000964 // Read the 'then' stmt.
965 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +0000966
967 SourceLocation InnerStatementTrailingElseLoc;
968 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000969
Chris Lattnera36ce712007-08-22 05:16:28 +0000970 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000971 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000972
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 // If it has an else, parse it.
974 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +0000975 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000976 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000977
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000978 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +0000979 if (TrailingElseLoc)
980 *TrailingElseLoc = Tok.getLocation();
981
Reid Spencer5f016e22007-07-11 17:01:13 +0000982 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +0000983 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000984
Chris Lattner0ecea032007-08-22 05:28:50 +0000985 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000986 // there is no compound stmt. C90 does not have this clause. We only do
987 // this if the body isn't a compound statement to avoid push/pop in common
988 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000989 //
990 // C++ 6.4p1:
991 // The substatement in a selection-statement (each substatement, in the else
992 // form of the if statement) implicitly defines a local scope.
993 //
Sebastian Redl61364dd2008-12-11 19:30:53 +0000994 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000995 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000996
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000998
Chris Lattnera36ce712007-08-22 05:16:28 +0000999 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001000 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +00001001 } else if (Tok.is(tok::code_completion)) {
1002 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001003 cutOffParsing();
1004 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +00001005 } else if (InnerStatementTrailingElseLoc.isValid()) {
1006 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001008
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001009 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Chris Lattner18914bc2008-12-12 06:19:11 +00001011 // If the condition was invalid, discard the if statement. We could recover
1012 // better by replacing it with a valid expr, but don't do that yet.
John McCalld226f652010-08-21 09:40:31 +00001013 if (CondExp.isInvalid() && !CondVar)
Chris Lattner18914bc2008-12-12 06:19:11 +00001014 return StmtError();
Chris Lattner22153252007-08-26 23:08:06 +00001015
Chris Lattnerb96728d2007-10-29 05:08:52 +00001016 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +00001017 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +00001018 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001019 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1020 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1021 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +00001022 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +00001023 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +00001024 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001025
Chris Lattnerb96728d2007-10-29 05:08:52 +00001026 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001027 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001028 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001029 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001030 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001031
John McCall9ae2f072010-08-23 23:25:46 +00001032 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001033 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001034}
1035
1036/// ParseSwitchStatement
1037/// switch-statement:
1038/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001039/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001040StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001041 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1043
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001044 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001045 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001046 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001047 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 }
Chris Lattner22153252007-08-26 23:08:06 +00001049
David Blaikie4e4d0842012-03-11 07:00:24 +00001050 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001051
Chris Lattner22153252007-08-26 23:08:06 +00001052 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1053 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001054 //
1055 // C++ 6.4p3:
1056 // A name introduced by a declaration in a condition is in scope from its
1057 // point of declaration until the end of the substatements controlled by the
1058 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001059 // C++ 3.3.2p4:
1060 // Names declared in the for-init-statement, and in the condition of if,
1061 // while, for, and switch statements are local to the if, while, for, or
1062 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001063 //
Richard Trieubb9b80c2011-04-21 21:44:26 +00001064 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001065 if (C99orCXX)
1066 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001067 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001068
1069 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001070 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001071 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001072 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001073 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001074
John McCall60d7b3a2010-08-24 06:29:42 +00001075 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001076 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001077
Douglas Gregor586596f2010-05-06 17:25:47 +00001078 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001079 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001080 // FIXME: This is not optimal recovery, but parsing the body is more
1081 // dangerous due to the presence of case and default statements, which
1082 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001083 if (Tok.is(tok::l_brace)) {
1084 ConsumeBrace();
1085 SkipUntil(tok::r_brace, false, false);
1086 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001087 SkipUntil(tok::semi);
1088 return move(Switch);
1089 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001090
Chris Lattner0ecea032007-08-22 05:28:50 +00001091 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001092 // there is no compound stmt. C90 does not have this clause. We only do this
1093 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001094 //
1095 // C++ 6.4p1:
1096 // The substatement in a selection-statement (each substatement, in the else
1097 // form of the if statement) implicitly defines a local scope.
1098 //
1099 // See comments in ParseIfStatement for why we create a scope for the
1100 // condition and a new scope for substatement in C++.
1101 //
Mike Stump1eb44332009-09-09 15:08:12 +00001102 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001103 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001104
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001106 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001107
Chris Lattner7e52de42010-01-24 01:50:29 +00001108 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001109 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001110 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001111
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001112 if (Body.isInvalid()) {
Chris Lattner7e52de42010-01-24 01:50:29 +00001113 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001114
1115 // Put the synthesized null statement on the same line as the end of switch
1116 // condition.
1117 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1118 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1119 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001120
John McCall9ae2f072010-08-23 23:25:46 +00001121 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001122}
1123
1124/// ParseWhileStatement
1125/// while-statement: [C99 6.8.5.1]
1126/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001127/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001128StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001129 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 SourceLocation WhileLoc = Tok.getLocation();
1131 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001132
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001133 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001134 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001136 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001138
David Blaikie4e4d0842012-03-11 07:00:24 +00001139 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001140
Chris Lattner22153252007-08-26 23:08:06 +00001141 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1142 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001143 //
1144 // C++ 6.4p3:
1145 // A name introduced by a declaration in a condition is in scope from its
1146 // point of declaration until the end of the substatements controlled by the
1147 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001148 // C++ 3.3.2p4:
1149 // Names declared in the for-init-statement, and in the condition of if,
1150 // while, for, and switch statements are local to the if, while, for, or
1151 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001152 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001153 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001154 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001155 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1156 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001157 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001158 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1159 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001160
1161 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001162 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001163 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001164 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001165 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001166
John McCall9ae2f072010-08-23 23:25:46 +00001167 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattner0ecea032007-08-22 05:28:50 +00001169 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001170 // there is no compound stmt. C90 does not have this clause. We only do this
1171 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001172 //
1173 // C++ 6.5p2:
1174 // The substatement in an iteration-statement implicitly defines a local scope
1175 // which is entered and exited each time through the loop.
1176 //
1177 // See comments in ParseIfStatement for why we create a scope for the
1178 // condition and a new scope for substatement in C++.
1179 //
Mike Stump1eb44332009-09-09 15:08:12 +00001180 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001181 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001184 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001185
Chris Lattner0ecea032007-08-22 05:28:50 +00001186 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001187 InnerScope.Exit();
1188 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001189
John McCalld226f652010-08-21 09:40:31 +00001190 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001191 return StmtError();
1192
John McCall9ae2f072010-08-23 23:25:46 +00001193 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001194}
1195
1196/// ParseDoStatement
1197/// do-statement: [C99 6.8.5.2]
1198/// 'do' statement 'while' '(' expression ')' ';'
1199/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001200StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001201 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001203
Chris Lattner22153252007-08-26 23:08:06 +00001204 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1205 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001206 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001207 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001208 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001209 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001210 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001211
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001212 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001213
Chris Lattner0ecea032007-08-22 05:28:50 +00001214 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001215 // there is no compound stmt. C90 does not have this clause. We only do this
1216 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001217 //
1218 // C++ 6.5p2:
1219 // The substatement in an iteration-statement implicitly defines a local scope
1220 // which is entered and exited each time through the loop.
1221 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001222 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikie4e4d0842012-03-11 07:00:24 +00001223 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001224 Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001225
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001227 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001228
Chris Lattner0ecea032007-08-22 05:28:50 +00001229 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001230 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001231
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001232 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001233 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001234 Diag(Tok, diag::err_expected_while);
Chris Lattner28eb7e92008-11-23 23:17:07 +00001235 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner19504402008-11-13 18:52:53 +00001236 SkipUntil(tok::semi, false, true);
1237 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001238 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 }
1240 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001241
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001242 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001243 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner19504402008-11-13 18:52:53 +00001244 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001245 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001247
Chris Lattnerff871fb2008-12-12 06:35:28 +00001248 // Parse the parenthesized condition.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001249 BalancedDelimiterTracker T(*this, tok::l_paren);
1250 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00001251 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001252 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001253 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001254
Sebastian Redl9a920342008-12-11 19:48:14 +00001255 if (Cond.isInvalid() || Body.isInvalid())
1256 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001257
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001258 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1259 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001260}
1261
1262/// ParseForStatement
1263/// for-statement: [C99 6.8.5.3]
1264/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1265/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001266/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1267/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001268/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001269/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1270/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001271///
1272/// [C++] for-init-statement:
1273/// [C++] expression-statement
1274/// [C++] simple-declaration
1275///
Richard Smithad762fc2011-04-14 22:09:26 +00001276/// [C++0x] for-range-declaration:
1277/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1278/// [C++0x] for-range-initializer:
1279/// [C++0x] expression
1280/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001281StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001282 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001284
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001285 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001286 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001288 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001290
David Blaikie4e4d0842012-03-11 07:00:24 +00001291 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus || getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001292
Chris Lattner22153252007-08-26 23:08:06 +00001293 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1294 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001295 //
1296 // C++ 6.4p3:
1297 // A name introduced by a declaration in a condition is in scope from its
1298 // point of declaration until the end of the substatements controlled by the
1299 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001300 // C++ 3.3.2p4:
1301 // Names declared in the for-init-statement, and in the condition of if,
1302 // while, for, and switch statements are local to the if, while, for, or
1303 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001304 // C++ 6.5.3p1:
1305 // Names declared in the for-init-statement are in the same declarative-region
1306 // as those declared in the condition.
1307 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001308 unsigned ScopeFlags;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001309 if (C99orCXXorObjC)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001310 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1311 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001312 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001313 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1314
1315 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001316
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001317 BalancedDelimiterTracker T(*this, tok::l_paren);
1318 T.consumeOpen();
1319
John McCall60d7b3a2010-08-24 06:29:42 +00001320 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001321
Richard Smithad762fc2011-04-14 22:09:26 +00001322 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001323 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001324 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001325 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001326 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001327 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001328 FullExprArg ThirdPart(Actions);
John McCalld226f652010-08-21 09:40:31 +00001329 Decl *SecondVar = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001330
Douglas Gregor791215b2009-09-21 20:51:25 +00001331 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001332 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001333 C99orCXXorObjC? Sema::PCC_ForInit
1334 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001335 cutOffParsing();
1336 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001337 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001338
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001340 if (Tok.is(tok::semi)) { // for (;
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 // no first part, eat the ';'.
1342 ConsumeToken();
Eli Friedman9490ab42011-12-20 01:50:37 +00001343 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001345 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001347
John McCall0b7e6782011-03-24 11:26:52 +00001348 ParsedAttributesWithRange attrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +00001349 MaybeParseCXX0XAttributes(attrs);
Sean Huntbbd37c62009-11-21 08:43:09 +00001350
Richard Smithad762fc2011-04-14 22:09:26 +00001351 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001352 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001353 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1354
Chris Lattner97144fc2009-04-02 04:16:50 +00001355 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +00001356 StmtVector Stmts(Actions);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001357 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smithad762fc2011-04-14 22:09:26 +00001358 DeclEnd, attrs, false,
1359 MightBeForRangeStmt ?
1360 &ForRangeInit : 0);
Chris Lattnercd147752009-03-29 17:27:48 +00001361 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Richard Smithad762fc2011-04-14 22:09:26 +00001363 if (ForRangeInit.ParsedForRangeDecl()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001364 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001365 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001366
Richard Smithad762fc2011-04-14 22:09:26 +00001367 ForRange = true;
1368 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001369 ConsumeToken();
1370 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001371 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001372 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001373 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001374
Douglas Gregorfb629412010-08-23 21:17:50 +00001375 if (Tok.is(tok::code_completion)) {
1376 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001377 cutOffParsing();
1378 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001379 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001380 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001381 } else {
1382 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001383 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 } else {
1385 Value = ParseExpression();
1386
John McCallf6a16482010-12-04 03:47:34 +00001387 ForEach = isTokIdentifier_in();
1388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001390 if (!Value.isInvalid()) {
1391 if (ForEach)
1392 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1393 else
1394 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1395 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001396
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001397 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001399 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001400 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001401
Douglas Gregorfb629412010-08-23 21:17:50 +00001402 if (Tok.is(tok::code_completion)) {
1403 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001404 cutOffParsing();
1405 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001406 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001407 Collection = ParseExpression();
David Blaikie4e4d0842012-03-11 07:00:24 +00001408 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001409 // User tried to write the reasonable, but ill-formed, for-range-statement
1410 // for (expr : expr) { ... }
1411 Diag(Tok, diag::err_for_range_expected_decl)
1412 << FirstPart.get()->getSourceRange();
1413 SkipUntil(tok::r_paren, false, true);
1414 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001415 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001416 if (!Value.isInvalid()) {
1417 Diag(Tok, diag::err_expected_semi_for);
1418 } else {
1419 // Skip until semicolon or rparen, don't consume it.
1420 SkipUntil(tok::r_paren, true, true);
1421 if (Tok.is(tok::semi))
1422 ConsumeToken();
1423 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 }
1425 }
Richard Smithad762fc2011-04-14 22:09:26 +00001426 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001427 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001428 // Parse the second part of the for specifier.
1429 if (Tok.is(tok::semi)) { // for (...;;
1430 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001431 } else if (Tok.is(tok::r_paren)) {
1432 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001433 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001434 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001435 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001436 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1437 else {
1438 Second = ParseExpression();
1439 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001440 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001441 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001442 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001443 SecondPartIsInvalid = Second.isInvalid();
John McCall9ae2f072010-08-23 23:25:46 +00001444 SecondPart = Actions.MakeFullExpr(Second.get());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001445 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001446
Douglas Gregorb72c7782011-02-17 03:38:46 +00001447 if (Tok.isNot(tok::semi)) {
1448 if (!SecondPartIsInvalid || SecondVar)
1449 Diag(Tok, diag::err_expected_semi_for);
1450 else
1451 // Skip until semicolon or rparen, don't consume it.
1452 SkipUntil(tok::r_paren, true, true);
1453 }
1454
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001455 if (Tok.is(tok::semi)) {
1456 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001457 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001458
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001459 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001460 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001461 ExprResult Third = ParseExpression();
John McCall9ae2f072010-08-23 23:25:46 +00001462 ThirdPart = Actions.MakeFullExpr(Third.take());
Douglas Gregor586596f2010-05-06 17:25:47 +00001463 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001466 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001467
Richard Smithad762fc2011-04-14 22:09:26 +00001468 // We need to perform most of the semantic analysis for a C++0x for-range
1469 // statememt before parsing the body, in order to be able to deduce the type
1470 // of an auto-typed loop variable.
1471 StmtResult ForRangeStmt;
John McCall990567c2011-07-27 01:07:15 +00001472 if (ForRange) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001473 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, T.getOpenLocation(),
Richard Smithad762fc2011-04-14 22:09:26 +00001474 FirstPart.take(),
1475 ForRangeInit.ColonLoc,
1476 ForRangeInit.RangeExpr.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001477 T.getCloseLocation());
Richard Smithad762fc2011-04-14 22:09:26 +00001478
John McCall990567c2011-07-27 01:07:15 +00001479
1480 // Similarly, we need to do the semantic analysis for a for-range
1481 // statement immediately in order to close over temporaries correctly.
1482 } else if (ForEach) {
1483 if (!Collection.isInvalid())
1484 Collection =
1485 Actions.ActOnObjCForCollectionOperand(ForLoc, Collection.take());
1486 }
1487
Chris Lattner0ecea032007-08-22 05:28:50 +00001488 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001489 // there is no compound stmt. C90 does not have this clause. We only do this
1490 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001491 //
1492 // C++ 6.5p2:
1493 // The substatement in an iteration-statement implicitly defines a local scope
1494 // which is entered and exited each time through the loop.
1495 //
1496 // See comments in ParseIfStatement for why we create a scope for
1497 // for-init-statement/condition and a new scope for substatement in C++.
1498 //
Mike Stump1eb44332009-09-09 15:08:12 +00001499 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001500 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001501
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001503 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001504
Chris Lattner0ecea032007-08-22 05:28:50 +00001505 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001506 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001507
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001509 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001510
1511 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001512 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001513
Richard Smithad762fc2011-04-14 22:09:26 +00001514 if (ForEach)
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001515 return Actions.ActOnObjCForCollectionStmt(ForLoc, T.getOpenLocation(),
1516 FirstPart.take(),
1517 Collection.take(),
1518 T.getCloseLocation(),
1519 Body.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Richard Smithad762fc2011-04-14 22:09:26 +00001521 if (ForRange)
1522 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1523
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001524 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1525 SecondPart, SecondVar, ThirdPart,
1526 T.getCloseLocation(), Body.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001527}
1528
1529/// ParseGotoStatement
1530/// jump-statement:
1531/// 'goto' identifier ';'
1532/// [GNU] 'goto' '*' expression ';'
1533///
1534/// Note: this lets the caller parse the end ';'.
1535///
Richard Smith534986f2012-04-14 00:33:13 +00001536StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001537 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001539
John McCall60d7b3a2010-08-24 06:29:42 +00001540 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001541 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001542 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1543 Tok.getLocation());
1544 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001546 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 // GNU indirect goto extension.
1548 Diag(Tok, diag::ext_gnu_indirect_goto);
1549 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001550 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001551 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001553 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 }
John McCall9ae2f072010-08-23 23:25:46 +00001555 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattner95cfb852007-07-22 04:13:33 +00001556 } else {
1557 Diag(Tok, diag::err_expected_ident);
Sebastian Redl9a920342008-12-11 19:48:14 +00001558 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001560
Sebastian Redl9a920342008-12-11 19:48:14 +00001561 return move(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001562}
1563
1564/// ParseContinueStatement
1565/// jump-statement:
1566/// 'continue' ';'
1567///
1568/// Note: this lets the caller parse the end ';'.
1569///
Richard Smith534986f2012-04-14 00:33:13 +00001570StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001572 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001573}
1574
1575/// ParseBreakStatement
1576/// jump-statement:
1577/// 'break' ';'
1578///
1579/// Note: this lets the caller parse the end ';'.
1580///
Richard Smith534986f2012-04-14 00:33:13 +00001581StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001583 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001584}
1585
1586/// ParseReturnStatement
1587/// jump-statement:
1588/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001589StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001590 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001592
John McCall60d7b3a2010-08-24 06:29:42 +00001593 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001594 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001595 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001596 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001597 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001598 return StmtError();
1599 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001600
David Blaikie4e4d0842012-03-11 07:00:24 +00001601 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001602 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001603 if (R.isUsable())
David Blaikie4e4d0842012-03-11 07:00:24 +00001604 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001605 diag::warn_cxx98_compat_generalized_initializer_lists :
1606 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001607 << R.get()->getSourceRange();
1608 } else
1609 R = ParseExpression();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001610 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001612 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 }
1614 }
John McCall9ae2f072010-08-23 23:25:46 +00001615 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001616}
1617
Eli Friedman3fedbe12011-09-30 01:13:51 +00001618/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1619/// this routine is called to collect the tokens for an MS asm statement.
1620StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1621 SourceManager &SrcMgr = PP.getSourceManager();
1622 SourceLocation EndLoc = AsmLoc;
1623 do {
1624 bool InBraces = false;
NAKAMURA Takumi96e21712011-10-08 11:31:53 +00001625 unsigned short savedBraceCount = 0;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001626 bool InAsmComment = false;
1627 FileID FID;
NAKAMURA Takumi96e21712011-10-08 11:31:53 +00001628 unsigned LineNo = 0;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001629 unsigned NumTokensRead = 0;
1630 SourceLocation LBraceLoc;
1631
1632 if (Tok.is(tok::l_brace)) {
1633 // Braced inline asm: consume the opening brace.
1634 InBraces = true;
1635 savedBraceCount = BraceCount;
1636 EndLoc = LBraceLoc = ConsumeBrace();
1637 ++NumTokensRead;
1638 } else {
1639 // Single-line inline asm; compute which line it is on.
1640 std::pair<FileID, unsigned> ExpAsmLoc =
1641 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1642 FID = ExpAsmLoc.first;
1643 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1644 }
1645
Steve Naroff03d6bc62008-02-08 03:36:19 +00001646 SourceLocation TokLoc = Tok.getLocation();
Steve Naroff36280972008-02-08 18:01:27 +00001647 do {
Eli Friedman3fedbe12011-09-30 01:13:51 +00001648 // If we hit EOF, we're done, period.
1649 if (Tok.is(tok::eof))
1650 break;
1651 // When we consume the closing brace, we're done.
1652 if (InBraces && BraceCount == savedBraceCount)
1653 break;
1654
1655 if (!InAsmComment && Tok.is(tok::semi)) {
1656 // A semicolon in an asm is the start of a comment.
1657 InAsmComment = true;
1658 if (InBraces) {
1659 // Compute which line the comment is on.
1660 std::pair<FileID, unsigned> ExpSemiLoc =
1661 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1662 FID = ExpSemiLoc.first;
1663 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
1664 }
1665 } else if (!InBraces || InAsmComment) {
1666 // If end-of-line is significant, check whether this token is on a
1667 // new line.
1668 std::pair<FileID, unsigned> ExpLoc =
1669 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1670 if (ExpLoc.first != FID ||
1671 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
1672 // If this is a single-line __asm, we're done.
1673 if (!InBraces)
1674 break;
1675 // We're no longer in a comment.
1676 InAsmComment = false;
1677 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
1678 // Single-line asm always ends when a closing brace is seen.
1679 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
1680 // does MSVC do here?
1681 break;
1682 }
1683 }
1684
1685 // Consume the next token; make sure we don't modify the brace count etc.
1686 // if we are in a comment.
Abramo Bagnaraa44724d2010-12-02 18:34:55 +00001687 EndLoc = TokLoc;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001688 if (InAsmComment)
1689 PP.Lex(Tok);
1690 else
1691 ConsumeAnyToken();
Steve Naroff36280972008-02-08 18:01:27 +00001692 TokLoc = Tok.getLocation();
Eli Friedman3fedbe12011-09-30 01:13:51 +00001693 ++NumTokensRead;
1694 } while (1);
1695
1696 if (InBraces && BraceCount != savedBraceCount) {
1697 // __asm without closing brace (this can happen at EOF).
1698 Diag(Tok, diag::err_expected_rbrace);
1699 Diag(LBraceLoc, diag::note_matching) << "{";
1700 return StmtError();
1701 } else if (NumTokensRead == 0) {
1702 // Empty __asm.
1703 Diag(Tok, diag::err_expected_lbrace);
1704 return StmtError();
1705 }
1706 // Multiple adjacent asm's form together into a single asm statement
1707 // in the AST.
1708 if (!Tok.is(tok::kw_asm))
1709 break;
1710 EndLoc = ConsumeToken();
1711 } while (1);
1712 // FIXME: Need to actually grab the data and pass it on to Sema. Ideally,
1713 // what Sema wants is a string of the entire inline asm, with one instruction
1714 // per line and all the __asm keywords stripped out, and a way of mapping
1715 // from any character of that string to its location in the original source
1716 // code. I'm not entirely sure how to go about that, though.
Mike Stump95059b52009-12-11 00:04:56 +00001717 Token t;
1718 t.setKind(tok::string_literal);
Chris Lattnere7896852010-08-17 16:00:12 +00001719 t.setLiteralData("\"/*FIXME: not done*/\"");
Mike Stump95059b52009-12-11 00:04:56 +00001720 t.clearFlag(Token::NeedsCleaning);
Chris Lattnere7896852010-08-17 16:00:12 +00001721 t.setLength(21);
Sean Hunt6cf75022010-08-30 17:47:05 +00001722 ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
Mike Stump95059b52009-12-11 00:04:56 +00001723 ExprVector Constraints(Actions);
1724 ExprVector Exprs(Actions);
1725 ExprVector Clobbers(Actions);
Abramo Bagnaraa44724d2010-12-02 18:34:55 +00001726 return Actions.ActOnAsmStmt(AsmLoc, true, true, 0, 0, 0,
Mike Stump95059b52009-12-11 00:04:56 +00001727 move_arg(Constraints), move_arg(Exprs),
John McCall9ae2f072010-08-23 23:25:46 +00001728 AsmString.take(), move_arg(Clobbers),
Abramo Bagnaraa44724d2010-12-02 18:34:55 +00001729 EndLoc, true);
Steve Naroffd62701b2008-02-07 03:50:06 +00001730}
1731
Reid Spencer5f016e22007-07-11 17:01:13 +00001732/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff5f8aa692008-02-11 23:15:56 +00001733/// asm-statement:
1734/// gnu-asm-statement
1735/// ms-asm-statement
1736///
1737/// [GNU] gnu-asm-statement:
Reid Spencer5f016e22007-07-11 17:01:13 +00001738/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1739///
1740/// [GNU] asm-argument:
1741/// asm-string-literal
1742/// asm-string-literal ':' asm-operands[opt]
1743/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1744/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1745/// ':' asm-clobbers
1746///
1747/// [GNU] asm-clobbers:
1748/// asm-string-literal
1749/// asm-clobbers ',' asm-string-literal
1750///
Steve Naroff5f8aa692008-02-11 23:15:56 +00001751/// [MS] ms-asm-statement:
Eli Friedman3fedbe12011-09-30 01:13:51 +00001752/// ms-asm-block
1753/// ms-asm-block ms-asm-statement
Steve Naroff5f8aa692008-02-11 23:15:56 +00001754///
Eli Friedman3fedbe12011-09-30 01:13:51 +00001755/// [MS] ms-asm-block:
1756/// '__asm' ms-asm-line '\n'
1757/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1758///
1759/// [MS] ms-asm-instruction-block
1760/// ms-asm-line
1761/// ms-asm-line '\n' ms-asm-instruction-block
Steve Naroff5f8aa692008-02-11 23:15:56 +00001762///
John McCall60d7b3a2010-08-24 06:29:42 +00001763StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001764 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattnerfe795952007-10-29 04:04:16 +00001765 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001766
David Blaikie4e4d0842012-03-11 07:00:24 +00001767 if (getLangOpts().MicrosoftExt && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
Steve Naroffd62701b2008-02-07 03:50:06 +00001768 msAsm = true;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001769 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00001770 }
John McCall0b7e6782011-03-24 11:26:52 +00001771 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 SourceLocation Loc = Tok.getLocation();
Sean Huntbbd37c62009-11-21 08:43:09 +00001773 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redl9a920342008-12-11 19:48:14 +00001774
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1776 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner1ab3b962008-11-18 07:48:38 +00001777 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner1ab3b962008-11-18 07:48:38 +00001779 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Sebastian Redl9a920342008-12-11 19:48:14 +00001780
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 // Remember if this was a volatile asm.
Anders Carlsson39c47b52007-11-23 23:12:25 +00001782 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001783 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001784 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 SkipUntil(tok::r_paren);
Sebastian Redl9a920342008-12-11 19:48:14 +00001786 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001788 BalancedDelimiterTracker T(*this, tok::l_paren);
1789 T.consumeOpen();
Sebastian Redl9a920342008-12-11 19:48:14 +00001790
John McCall60d7b3a2010-08-24 06:29:42 +00001791 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenek320fa4b2011-12-02 01:30:14 +00001792 if (AsmString.isInvalid()) {
Richard Smith99831e42012-03-06 03:21:47 +00001793 // Consume up to and including the closing paren.
1794 T.skipToEnd();
Sebastian Redl9a920342008-12-11 19:48:14 +00001795 return StmtError();
Ted Kremenek320fa4b2011-12-02 01:30:14 +00001796 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001797
Chris Lattner5f9e2722011-07-23 10:55:15 +00001798 SmallVector<IdentifierInfo *, 4> Names;
Sebastian Redla55e52c2008-11-25 22:21:31 +00001799 ExprVector Constraints(Actions);
1800 ExprVector Exprs(Actions);
1801 ExprVector Clobbers(Actions);
Reid Spencer5f016e22007-07-11 17:01:13 +00001802
Anders Carlssondfab34a2008-02-05 23:03:50 +00001803 if (Tok.is(tok::r_paren)) {
Chris Lattner64cb4752009-12-20 23:00:41 +00001804 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001805 T.consumeClose();
Chris Lattner64cb4752009-12-20 23:00:41 +00001806 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001807 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
Chris Lattner64cb4752009-12-20 23:00:41 +00001808 move_arg(Constraints), move_arg(Exprs),
John McCall9ae2f072010-08-23 23:25:46 +00001809 AsmString.take(), move_arg(Clobbers),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001810 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001812
Chris Lattner64cb4752009-12-20 23:00:41 +00001813 // Parse Outputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001814 bool AteExtraColon = false;
1815 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1816 // In C++ mode, parse "::" like ": :".
1817 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattner64cb4752009-12-20 23:00:41 +00001818 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001819
Chris Lattner64056462009-12-20 23:08:04 +00001820 if (!AteExtraColon &&
1821 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00001822 return StmtError();
1823 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001824
Chris Lattner64cb4752009-12-20 23:00:41 +00001825 unsigned NumOutputs = Names.size();
1826
1827 // Parse Inputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001828 if (AteExtraColon ||
1829 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1830 // In C++ mode, parse "::" like ": :".
1831 if (AteExtraColon)
1832 AteExtraColon = false;
1833 else {
1834 AteExtraColon = Tok.is(tok::coloncolon);
1835 ConsumeToken();
1836 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001837
Chris Lattner64056462009-12-20 23:08:04 +00001838 if (!AteExtraColon &&
1839 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00001840 return StmtError();
1841 }
1842
1843 assert(Names.size() == Constraints.size() &&
1844 Constraints.size() == Exprs.size() &&
1845 "Input operand size mismatch!");
1846
1847 unsigned NumInputs = Names.size() - NumOutputs;
1848
1849 // Parse the clobbers, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001850 if (AteExtraColon || Tok.is(tok::colon)) {
1851 if (!AteExtraColon)
1852 ConsumeToken();
Chris Lattner64cb4752009-12-20 23:00:41 +00001853
Chandler Carruth102e1b62010-07-22 07:11:21 +00001854 // Parse the asm-string list for clobbers if present.
1855 if (Tok.isNot(tok::r_paren)) {
1856 while (1) {
John McCall60d7b3a2010-08-24 06:29:42 +00001857 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattner64cb4752009-12-20 23:00:41 +00001858
Chandler Carruth102e1b62010-07-22 07:11:21 +00001859 if (Clobber.isInvalid())
1860 break;
Chris Lattner64cb4752009-12-20 23:00:41 +00001861
Chandler Carruth102e1b62010-07-22 07:11:21 +00001862 Clobbers.push_back(Clobber.release());
Chris Lattner64cb4752009-12-20 23:00:41 +00001863
Chandler Carruth102e1b62010-07-22 07:11:21 +00001864 if (Tok.isNot(tok::comma)) break;
1865 ConsumeToken();
1866 }
Chris Lattner64cb4752009-12-20 23:00:41 +00001867 }
1868 }
1869
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001870 T.consumeClose();
Chris Lattner64cb4752009-12-20 23:00:41 +00001871 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001872 NumOutputs, NumInputs, Names.data(),
Sebastian Redlf512e822009-01-18 18:03:53 +00001873 move_arg(Constraints), move_arg(Exprs),
John McCall9ae2f072010-08-23 23:25:46 +00001874 AsmString.take(), move_arg(Clobbers),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001875 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001876}
1877
1878/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattner64cb4752009-12-20 23:00:41 +00001879/// asm-statement, assuming the leading ':' token was eaten.
Reid Spencer5f016e22007-07-11 17:01:13 +00001880///
1881/// [GNU] asm-operands:
1882/// asm-operand
1883/// asm-operands ',' asm-operand
1884///
1885/// [GNU] asm-operand:
1886/// asm-string-literal '(' expression ')'
1887/// '[' identifier ']' asm-string-literal '(' expression ')'
1888///
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00001889//
1890// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001891bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001892 SmallVectorImpl<Expr *> &Constraints,
1893 SmallVectorImpl<Expr *> &Exprs) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 // 'asm-operands' isn't present?
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001895 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001896 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001897
1898 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 // Read the [id] if present.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001900 if (Tok.is(tok::l_square)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001901 BalancedDelimiterTracker T(*this, tok::l_square);
1902 T.consumeOpen();
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001904 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 Diag(Tok, diag::err_expected_ident);
1906 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001907 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 }
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Anders Carlssonb235fc22007-11-22 01:36:19 +00001910 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner69efba72007-10-29 04:06:22 +00001911 ConsumeToken();
Anders Carlssonb235fc22007-11-22 01:36:19 +00001912
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001913 Names.push_back(II);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001914 T.consumeClose();
Anders Carlssonb235fc22007-11-22 01:36:19 +00001915 } else
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001916 Names.push_back(0);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001917
John McCall60d7b3a2010-08-24 06:29:42 +00001918 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001919 if (Constraint.isInvalid()) {
Anders Carlssonb235fc22007-11-22 01:36:19 +00001920 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001921 return true;
Anders Carlssonb235fc22007-11-22 01:36:19 +00001922 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001923 Constraints.push_back(Constraint.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00001924
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001925 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001926 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001928 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001929 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001930
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 // Read the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001932 BalancedDelimiterTracker T(*this, tok::l_paren);
1933 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00001934 ExprResult Res(ParseExpression());
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001935 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001936 if (Res.isInvalid()) {
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 Exprs.push_back(Res.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 // Eat the comma and continue parsing if it exists.
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001942 if (Tok.isNot(tok::comma)) return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 ConsumeToken();
1944 }
1945}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001946
Douglas Gregorc9977d02011-03-16 17:05:57 +00001947Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00001948 assert(Tok.is(tok::l_brace));
1949 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001950
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001951 if (SkipFunctionBodies && trySkippingFunctionBody()) {
1952 BodyScope.Exit();
1953 return Actions.ActOnFinishFunctionBody(Decl, 0);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001954 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001955
John McCallf312b1e2010-08-26 23:41:50 +00001956 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1957 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001959 // Do not enter a scope for the brace, as the arguments are in the same scope
1960 // (the function body) as the body itself. Instead, just read the statement
1961 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00001962 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00001963
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00001964 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001965 if (FnBody.isInvalid()) {
1966 Sema::CompoundScopeRAII CompoundScope(Actions);
Mike Stump1eb44332009-09-09 15:08:12 +00001967 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Chris Lattner40e9bc82009-03-05 00:49:17 +00001968 MultiStmtArg(Actions), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001969 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001970
Douglas Gregorc9977d02011-03-16 17:05:57 +00001971 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00001972 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00001973}
Sebastian Redla0fd8652008-12-21 16:41:36 +00001974
Sebastian Redld3a413d2009-04-26 20:35:05 +00001975/// ParseFunctionTryBlock - Parse a C++ function-try-block.
1976///
1977/// function-try-block:
1978/// 'try' ctor-initializer[opt] compound-statement handler-seq
1979///
Douglas Gregorc9977d02011-03-16 17:05:57 +00001980Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00001981 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1982 SourceLocation TryLoc = ConsumeToken();
1983
John McCallf312b1e2010-08-26 23:41:50 +00001984 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1985 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00001986
1987 // Constructor initializer list?
1988 if (Tok.is(tok::colon))
1989 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00001990 else
1991 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001992
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001993 if (SkipFunctionBodies && trySkippingFunctionBody()) {
1994 BodyScope.Exit();
1995 return Actions.ActOnFinishFunctionBody(Decl, 0);
Douglas Gregorc9977d02011-03-16 17:05:57 +00001996 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00001997
Sebastian Redlde1b60a2009-04-26 21:08:36 +00001998 SourceLocation LBraceLoc = Tok.getLocation();
John McCall60d7b3a2010-08-24 06:29:42 +00001999 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
Sebastian Redld3a413d2009-04-26 20:35:05 +00002000 // If we failed to parse the try-catch, we just give the function an empty
2001 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002002 if (FnBody.isInvalid()) {
2003 Sema::CompoundScopeRAII CompoundScope(Actions);
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002004 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Sebastian Redld3a413d2009-04-26 20:35:05 +00002005 MultiStmtArg(Actions), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002006 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00002007
Douglas Gregorc9977d02011-03-16 17:05:57 +00002008 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002009 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redld3a413d2009-04-26 20:35:05 +00002010}
2011
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002012bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002013 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002014 assert(SkipFunctionBodies &&
2015 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002016
2017 // We're in code-completion mode. Skip parsing for all function bodies unless
2018 // the body contains the code-completion point.
2019 TentativeParsingAction PA(*this);
2020 ConsumeBrace();
2021 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002022 /*StopAtCodeCompletion=*/PP.isCodeCompletionEnabled())) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002023 PA.Commit();
2024 return true;
2025 }
2026
2027 PA.Revert();
2028 return false;
2029}
2030
Sebastian Redla0fd8652008-12-21 16:41:36 +00002031/// ParseCXXTryBlock - Parse a C++ try-block.
2032///
2033/// try-block:
2034/// 'try' compound-statement handler-seq
2035///
Richard Smith534986f2012-04-14 00:33:13 +00002036StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002037 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2038
2039 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002040 return ParseCXXTryBlockCommon(TryLoc);
2041}
2042
2043/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2044/// function-try-block.
2045///
2046/// try-block:
2047/// 'try' compound-statement handler-seq
2048///
2049/// function-try-block:
2050/// 'try' ctor-initializer[opt] compound-statement handler-seq
2051///
2052/// handler-seq:
2053/// handler handler-seq[opt]
2054///
John Wiegley28bbe4b2011-04-28 01:08:34 +00002055/// [Borland] try-block:
2056/// 'try' compound-statement seh-except-block
2057/// 'try' compound-statment seh-finally-block
2058///
John McCall60d7b3a2010-08-24 06:29:42 +00002059StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002060 if (Tok.isNot(tok::l_brace))
2061 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Sean Huntbbd37c62009-11-21 08:43:09 +00002062 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002063
2064 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002065 Scope::DeclScope|Scope::TryScope));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002066 if (TryBlock.isInvalid())
2067 return move(TryBlock);
2068
John Wiegley28bbe4b2011-04-28 01:08:34 +00002069 // Borland allows SEH-handlers with 'try'
Douglas Gregorb57791e2011-10-21 03:57:52 +00002070
Richard Smith534986f2012-04-14 00:33:13 +00002071 if ((Tok.is(tok::identifier) &&
2072 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2073 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002074 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2075 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00002076 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002077 SourceLocation Loc = ConsumeToken();
2078 Handler = ParseSEHExceptBlock(Loc);
2079 }
2080 else {
2081 SourceLocation Loc = ConsumeToken();
2082 Handler = ParseSEHFinallyBlock(Loc);
2083 }
2084 if(Handler.isInvalid())
2085 return move(Handler);
John McCall7f040a92010-12-24 02:08:15 +00002086
John Wiegley28bbe4b2011-04-28 01:08:34 +00002087 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2088 TryLoc,
2089 TryBlock.take(),
2090 Handler.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002091 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00002092 else {
2093 StmtVector Handlers(Actions);
Richard Smith534986f2012-04-14 00:33:13 +00002094 ParsedAttributesWithRange attrs(AttrFactory);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002095 MaybeParseCXX0XAttributes(attrs);
2096 ProhibitAttributes(attrs);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002097
John Wiegley28bbe4b2011-04-28 01:08:34 +00002098 if (Tok.isNot(tok::kw_catch))
2099 return StmtError(Diag(Tok, diag::err_expected_catch));
2100 while (Tok.is(tok::kw_catch)) {
2101 StmtResult Handler(ParseCXXCatchBlock());
2102 if (!Handler.isInvalid())
2103 Handlers.push_back(Handler.release());
2104 }
2105 // Don't bother creating the full statement if we don't have any usable
2106 // handlers.
2107 if (Handlers.empty())
2108 return StmtError();
2109
2110 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
2111 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002112}
2113
2114/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2115///
2116/// handler:
2117/// 'catch' '(' exception-declaration ')' compound-statement
2118///
2119/// exception-declaration:
2120/// type-specifier-seq declarator
2121/// type-specifier-seq abstract-declarator
2122/// type-specifier-seq
2123/// '...'
2124///
John McCall60d7b3a2010-08-24 06:29:42 +00002125StmtResult Parser::ParseCXXCatchBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002126 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2127
2128 SourceLocation CatchLoc = ConsumeToken();
2129
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002130 BalancedDelimiterTracker T(*this, tok::l_paren);
2131 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redla0fd8652008-12-21 16:41:36 +00002132 return StmtError();
2133
2134 // C++ 3.3.2p3:
2135 // The name in a catch exception-declaration is local to the handler and
2136 // shall not be redeclared in the outermost block of the handler.
2137 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
2138
2139 // exception-declaration is equivalent to '...' or a parameter-declaration
2140 // without default arguments.
John McCalld226f652010-08-21 09:40:31 +00002141 Decl *ExceptionDecl = 0;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002142 if (Tok.isNot(tok::ellipsis)) {
John McCall0b7e6782011-03-24 11:26:52 +00002143 DeclSpec DS(AttrFactory);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002144 if (ParseCXXTypeSpecifierSeq(DS))
2145 return StmtError();
Sebastian Redla0fd8652008-12-21 16:41:36 +00002146 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2147 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002148 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002149 } else
2150 ConsumeToken();
2151
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002152 T.consumeClose();
2153 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002154 return StmtError();
2155
2156 if (Tok.isNot(tok::l_brace))
2157 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2158
Sean Huntbbd37c62009-11-21 08:43:09 +00002159 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002160 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002161 if (Block.isInvalid())
2162 return move(Block);
2163
John McCall9ae2f072010-08-23 23:25:46 +00002164 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002165}
Francois Pichet1e862692011-05-06 20:48:22 +00002166
2167void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002168 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002169 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002170 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002171
Douglas Gregor3896fc52011-10-24 22:31:10 +00002172 // Handle dependent statements by parsing the braces as a compound statement.
2173 // This is not the same behavior as Visual C++, which don't treat this as a
2174 // compound statement, but for Clang's type checking we can't have anything
2175 // inside these braces escaping to the surrounding code.
2176 if (Result.Behavior == IEB_Dependent) {
2177 if (!Tok.is(tok::l_brace)) {
2178 Diag(Tok, diag::err_expected_lbrace);
Richard Smith534986f2012-04-14 00:33:13 +00002179 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002180 }
Richard Smith534986f2012-04-14 00:33:13 +00002181
2182 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002183 if (Compound.isInvalid())
2184 return;
Richard Smith534986f2012-04-14 00:33:13 +00002185
Douglas Gregorba0513d2011-10-25 01:33:02 +00002186 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2187 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002188 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002189 Result.Name,
2190 Compound.get());
2191 if (DepResult.isUsable())
2192 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002193 return;
2194 }
Richard Smith534986f2012-04-14 00:33:13 +00002195
Douglas Gregor3896fc52011-10-24 22:31:10 +00002196 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2197 if (Braces.consumeOpen()) {
Francois Pichet1e862692011-05-06 20:48:22 +00002198 Diag(Tok, diag::err_expected_lbrace);
2199 return;
2200 }
Francois Pichet1e862692011-05-06 20:48:22 +00002201
Douglas Gregor3896fc52011-10-24 22:31:10 +00002202 switch (Result.Behavior) {
2203 case IEB_Parse:
2204 // Parse the statements below.
2205 break;
2206
2207 case IEB_Dependent:
2208 llvm_unreachable("Dependent case handled above");
Douglas Gregor3896fc52011-10-24 22:31:10 +00002209
2210 case IEB_Skip:
2211 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002212 return;
2213 }
2214
2215 // Condition is true, parse the statements.
2216 while (Tok.isNot(tok::r_brace)) {
2217 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2218 if (R.isUsable())
2219 Stmts.push_back(R.release());
2220 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002221 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002222}