blob: 69f28ecd6db9681f3ca3d21e95ed7040457ae433 [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"
Chad Rosier8cd64b42012-06-11 20:47:18 +000023#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// C99 6.8: Statements and Blocks.
28//===----------------------------------------------------------------------===//
29
30/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
31/// StatementOrDeclaration:
32/// statement
33/// declaration
34///
35/// statement:
36/// labeled-statement
37/// compound-statement
38/// expression-statement
39/// selection-statement
40/// iteration-statement
41/// jump-statement
Argyrios Kyrtzidisdcdd55f2008-09-07 18:58:01 +000042/// [C++] declaration-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +000043/// [C++] try-block
John Wiegley28bbe4b2011-04-28 01:08:34 +000044/// [MS] seh-try-block
Fariborz Jahanianb384d322007-10-04 20:19:06 +000045/// [OBC] objc-throw-statement
46/// [OBC] objc-try-catch-statement
Fariborz Jahanianc385c902008-01-29 18:21:32 +000047/// [OBC] objc-synchronized-statement
Reid Spencer5f016e22007-07-11 17:01:13 +000048/// [GNU] asm-statement
49/// [OMP] openmp-construct [TODO]
50///
51/// labeled-statement:
52/// identifier ':' statement
53/// 'case' constant-expression ':' statement
54/// 'default' ':' statement
55///
56/// selection-statement:
57/// if-statement
58/// switch-statement
59///
60/// iteration-statement:
61/// while-statement
62/// do-statement
63/// for-statement
64///
65/// expression-statement:
66/// expression[opt] ';'
67///
68/// jump-statement:
69/// 'goto' identifier ';'
70/// 'continue' ';'
71/// 'break' ';'
72/// 'return' expression[opt] ';'
73/// [GNU] 'goto' '*' expression ';'
74///
Fariborz Jahanianb384d322007-10-04 20:19:06 +000075/// [OBC] objc-throw-statement:
76/// [OBC] '@' 'throw' expression ';'
Mike Stump1eb44332009-09-09 15:08:12 +000077/// [OBC] '@' 'throw' ';'
78///
John McCall60d7b3a2010-08-24 06:29:42 +000079StmtResult
Nico Weber5cb94a72011-12-22 23:26:17 +000080Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
81 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000082
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +000083 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +000084
Richard Smith534986f2012-04-14 00:33:13 +000085 ParsedAttributesWithRange Attrs(AttrFactory);
86 MaybeParseCXX0XAttributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
87
88 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
89 OnlyStatement, TrailingElseLoc, Attrs);
90
91 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
92 "attributes on empty statement");
93
94 if (Attrs.empty() || Res.isInvalid())
95 return Res;
96
97 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
98}
99
100StmtResult
101Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
102 bool OnlyStatement, SourceLocation *TrailingElseLoc,
103 ParsedAttributesWithRange &Attrs) {
104 const char *SemiError = 0;
105 StmtResult Res;
Sean Huntbbd37c62009-11-21 08:43:09 +0000106
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 // Cases in this switch statement should fall through if the parser expects
108 // the token to end in a semicolon (in which case SemiError should be set),
109 // or they directly 'return;' if not.
Douglas Gregor312eadb2011-04-24 05:37:28 +0000110Retry:
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000111 tok::TokenKind Kind = Tok.getKind();
112 SourceLocation AtLoc;
113 switch (Kind) {
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000114 case tok::at: // May be a @try or @throw statement
115 {
Richard Smith534986f2012-04-14 00:33:13 +0000116 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000117 AtLoc = ConsumeToken(); // consume @
Sebastian Redl43bc2a02008-12-11 20:12:42 +0000118 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000119 }
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000120
Douglas Gregor791215b2009-09-21 20:51:25 +0000121 case tok::code_completion:
John McCallf312b1e2010-08-26 23:41:50 +0000122 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000123 cutOffParsing();
124 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000125
Douglas Gregor312eadb2011-04-24 05:37:28 +0000126 case tok::identifier: {
127 Token Next = NextToken();
128 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000129 // identifier ':' statement
Richard Smith534986f2012-04-14 00:33:13 +0000130 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000131 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000132
Douglas Gregor3b887352011-04-27 04:48:22 +0000133 if (Next.isNot(tok::coloncolon)) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000134 CXXScopeSpec SS;
135 IdentifierInfo *Name = Tok.getIdentifierInfo();
136 SourceLocation NameLoc = Tok.getLocation();
Richard Trieu950be712011-09-19 19:01:00 +0000137
David Blaikie4e4d0842012-03-11 07:00:24 +0000138 if (getLangOpts().CPlusPlus)
Richard Trieu950be712011-09-19 19:01:00 +0000139 CheckForTemplateAndDigraph(Next, ParsedType(),
140 /*EnteringContext=*/false, *Name, SS);
141
Douglas Gregor312eadb2011-04-24 05:37:28 +0000142 Sema::NameClassification Classification
143 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next);
144 switch (Classification.getKind()) {
145 case Sema::NC_Keyword:
146 // The identifier was corrected to a keyword. Update the token
147 // to this keyword, and try again.
148 if (Name->getTokenID() != tok::identifier) {
149 Tok.setIdentifierInfo(Name);
150 Tok.setKind(Name->getTokenID());
151 goto Retry;
152 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000153
Douglas Gregor312eadb2011-04-24 05:37:28 +0000154 // Fall through via the normal error path.
155 // FIXME: This seems like it could only happen for context-sensitive
156 // keywords.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000157
Douglas Gregor312eadb2011-04-24 05:37:28 +0000158 case Sema::NC_Error:
159 // Handle errors here by skipping up to the next semicolon or '}', and
160 // eat the semicolon if that's what stopped us.
161 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
162 if (Tok.is(tok::semi))
163 ConsumeToken();
164 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000165
Douglas Gregor312eadb2011-04-24 05:37:28 +0000166 case Sema::NC_Unknown:
167 // Either we don't know anything about this identifier, or we know that
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000168 // we're in a syntactic context we haven't handled yet.
169 break;
170
Douglas Gregord9d75e52011-04-27 05:41:15 +0000171 case Sema::NC_Type:
Douglas Gregor3b887352011-04-27 04:48:22 +0000172 Tok.setKind(tok::annot_typename);
173 setTypeAnnotation(Tok, Classification.getType());
174 Tok.setAnnotationEndLoc(NameLoc);
Douglas Gregor3b887352011-04-27 04:48:22 +0000175 PP.AnnotateCachedTokens(Tok);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000176 break;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000177
Douglas Gregor312eadb2011-04-24 05:37:28 +0000178 case Sema::NC_Expression:
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000179 Tok.setKind(tok::annot_primary_expr);
180 setExprAnnotation(Tok, Classification.getExpression());
181 Tok.setAnnotationEndLoc(NameLoc);
182 PP.AnnotateCachedTokens(Tok);
183 break;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000184
Douglas Gregor312eadb2011-04-24 05:37:28 +0000185 case Sema::NC_TypeTemplate:
186 case Sema::NC_FunctionTemplate: {
187 ConsumeToken(); // the identifier
188 UnqualifiedId Id;
189 Id.setIdentifier(Name, NameLoc);
190 if (AnnotateTemplateIdToken(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000191 TemplateTy::make(Classification.getTemplateName()),
Douglas Gregor312eadb2011-04-24 05:37:28 +0000192 Classification.getTemplateNameKind(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000193 SS, SourceLocation(), Id,
Douglas Gregor3b887352011-04-27 04:48:22 +0000194 /*AllowTypeAnnotation=*/false)) {
195 // Handle errors here by skipping up to the next semicolon or '}', and
196 // eat the semicolon if that's what stopped us.
197 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
198 if (Tok.is(tok::semi))
199 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000200 return StmtError();
Douglas Gregor3b887352011-04-27 04:48:22 +0000201 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000202
203 // If the next token is '::', jump right into parsing a
Douglas Gregor3b887352011-04-27 04:48:22 +0000204 // nested-name-specifier. We don't want to leave the template-id
205 // hanging.
206 if (NextToken().is(tok::coloncolon) && TryAnnotateCXXScopeToken(false)){
Douglas Gregor312eadb2011-04-24 05:37:28 +0000207 // Handle errors here by skipping up to the next semicolon or '}', and
208 // eat the semicolon if that's what stopped us.
209 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
210 if (Tok.is(tok::semi))
211 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000212 return StmtError();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000213 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000214
Douglas Gregor312eadb2011-04-24 05:37:28 +0000215 // We've annotated a template-id, so try again now.
216 goto Retry;
217 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000218
Douglas Gregor312eadb2011-04-24 05:37:28 +0000219 case Sema::NC_NestedNameSpecifier:
220 // FIXME: Implement this!
221 break;
222 }
223 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000224
Douglas Gregor312eadb2011-04-24 05:37:28 +0000225 // Fall through
226 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000227
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000228 default: {
David Blaikie4e4d0842012-03-11 07:00:24 +0000229 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner97144fc2009-04-02 04:16:50 +0000230 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek8113ecf2010-11-10 05:59:39 +0000231 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smith534986f2012-04-14 00:33:13 +0000232 DeclEnd, Attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000233 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000234 }
235
236 if (Tok.is(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 Diag(Tok, diag::err_expected_statement);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000238 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 }
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Richard Smith534986f2012-04-14 00:33:13 +0000241 return ParseExprStatement();
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000242 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000243
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000245 return ParseCaseStatement();
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000247 return ParseDefaultStatement();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smith534986f2012-04-14 00:33:13 +0000250 return ParseCompoundStatement();
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000251 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +0000252 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
253 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000254 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000255
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smith534986f2012-04-14 00:33:13 +0000257 return ParseIfStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smith534986f2012-04-14 00:33:13 +0000259 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000260
Reid Spencer5f016e22007-07-11 17:01:13 +0000261 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smith534986f2012-04-14 00:33:13 +0000262 return ParseWhileStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smith534986f2012-04-14 00:33:13 +0000264 Res = ParseDoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000265 SemiError = "do/while";
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 break;
267 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smith534986f2012-04-14 00:33:13 +0000268 return ParseForStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000269
270 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smith534986f2012-04-14 00:33:13 +0000271 Res = ParseGotoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000272 SemiError = "goto";
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 break;
274 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smith534986f2012-04-14 00:33:13 +0000275 Res = ParseContinueStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000276 SemiError = "continue";
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 break;
278 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smith534986f2012-04-14 00:33:13 +0000279 Res = ParseBreakStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000280 SemiError = "break";
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 break;
282 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smith534986f2012-04-14 00:33:13 +0000283 Res = ParseReturnStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000284 SemiError = "return";
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 break;
Sebastian Redl61364dd2008-12-11 19:30:53 +0000286
Sebastian Redla0fd8652008-12-21 16:41:36 +0000287 case tok::kw_asm: {
Richard Smith534986f2012-04-14 00:33:13 +0000288 ProhibitAttributes(Attrs);
Steve Naroffd62701b2008-02-07 03:50:06 +0000289 bool msAsm = false;
290 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +0000291 Res = Actions.ActOnFinishFullStmt(Res.get());
Sebastian Redl61364dd2008-12-11 19:30:53 +0000292 if (msAsm) return move(Res);
Chris Lattner6869d8e2009-06-14 00:07:48 +0000293 SemiError = "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 break;
295 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000296
Sebastian Redla0fd8652008-12-21 16:41:36 +0000297 case tok::kw_try: // C++ 15: try-block
Richard Smith534986f2012-04-14 00:33:13 +0000298 return ParseCXXTryBlock();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000299
300 case tok::kw___try:
Richard Smith534986f2012-04-14 00:33:13 +0000301 ProhibitAttributes(Attrs); // TODO: is it correct?
302 return ParseSEHTryBlock();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000303
304 case tok::annot_pragma_vis:
Richard Smith534986f2012-04-14 00:33:13 +0000305 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000306 HandlePragmaVisibility();
307 return StmtEmpty();
308
309 case tok::annot_pragma_pack:
Richard Smith534986f2012-04-14 00:33:13 +0000310 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000311 HandlePragmaPack();
312 return StmtEmpty();
Sebastian Redla0fd8652008-12-21 16:41:36 +0000313 }
314
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 // If we reached this code, the statement must end in a semicolon.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000316 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 ConsumeToken();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000318 } else if (!Res.isInvalid()) {
Chris Lattner7b3684a2009-06-14 00:23:56 +0000319 // If the result was valid, then we do want to diagnose this. Use
320 // ExpectAndConsume to emit the diagnostic, even though we know it won't
321 // succeed.
322 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner19504402008-11-13 18:52:53 +0000323 // Skip until we see a } or ;, but don't eat it.
324 SkipUntil(tok::r_brace, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 }
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Sebastian Redl61364dd2008-12-11 19:30:53 +0000327 return move(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +0000328}
329
Douglas Gregor312eadb2011-04-24 05:37:28 +0000330/// \brief Parse an expression statement.
Richard Smith534986f2012-04-14 00:33:13 +0000331StmtResult Parser::ParseExprStatement() {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000332 // If a case keyword is missing, this is where it should be inserted.
333 Token OldToken = Tok;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000334
Douglas Gregor312eadb2011-04-24 05:37:28 +0000335 // expression[opt] ';'
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000336 ExprResult Expr(ParseExpression());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000337 if (Expr.isInvalid()) {
338 // If the expression is invalid, skip ahead to the next semicolon or '}'.
339 // Not doing this opens us up to the possibility of infinite loops if
340 // ParseExpression does not consume any tokens.
341 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
342 if (Tok.is(tok::semi))
343 ConsumeToken();
344 return StmtError();
345 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000346
Douglas Gregor312eadb2011-04-24 05:37:28 +0000347 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
348 Actions.CheckCaseExpression(Expr.get())) {
349 // If a constant expression is followed by a colon inside a switch block,
350 // suggest a missing case keyword.
351 Diag(OldToken, diag::err_expected_case_before_expression)
352 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000353
Douglas Gregor312eadb2011-04-24 05:37:28 +0000354 // Recover parsing as a case statement.
Richard Smith534986f2012-04-14 00:33:13 +0000355 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000356 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000357
Douglas Gregor312eadb2011-04-24 05:37:28 +0000358 // Otherwise, eat the semicolon.
359 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
360 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
John Wiegley28bbe4b2011-04-28 01:08:34 +0000361}
Douglas Gregor312eadb2011-04-24 05:37:28 +0000362
Richard Smith534986f2012-04-14 00:33:13 +0000363StmtResult Parser::ParseSEHTryBlock() {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000364 assert(Tok.is(tok::kw___try) && "Expected '__try'");
365 SourceLocation Loc = ConsumeToken();
366 return ParseSEHTryBlockCommon(Loc);
367}
368
369/// ParseSEHTryBlockCommon
370///
371/// seh-try-block:
372/// '__try' compound-statement seh-handler
373///
374/// seh-handler:
375/// seh-except-block
376/// seh-finally-block
377///
378StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
379 if(Tok.isNot(tok::l_brace))
380 return StmtError(Diag(Tok,diag::err_expected_lbrace));
381
Richard Smith534986f2012-04-14 00:33:13 +0000382 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000383 if(TryBlock.isInvalid())
384 return move(TryBlock);
385
386 StmtResult Handler;
Richard Smith534986f2012-04-14 00:33:13 +0000387 if (Tok.is(tok::identifier) &&
Douglas Gregorb57791e2011-10-21 03:57:52 +0000388 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000389 SourceLocation Loc = ConsumeToken();
390 Handler = ParseSEHExceptBlock(Loc);
391 } else if (Tok.is(tok::kw___finally)) {
392 SourceLocation Loc = ConsumeToken();
393 Handler = ParseSEHFinallyBlock(Loc);
394 } else {
395 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
396 }
397
398 if(Handler.isInvalid())
399 return move(Handler);
400
401 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
402 TryLoc,
403 TryBlock.take(),
404 Handler.take());
405}
406
407/// ParseSEHExceptBlock - Handle __except
408///
409/// seh-except-block:
410/// '__except' '(' seh-filter-expression ')' compound-statement
411///
412StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
413 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
414 raii2(Ident___exception_code, false),
415 raii3(Ident_GetExceptionCode, false);
416
417 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
418 return StmtError();
419
420 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
421
David Blaikie4e4d0842012-03-11 07:00:24 +0000422 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000423 Ident__exception_info->setIsPoisoned(false);
424 Ident___exception_info->setIsPoisoned(false);
425 Ident_GetExceptionInfo->setIsPoisoned(false);
426 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000427 ExprResult FilterExpr(ParseExpression());
Francois Pichetd7f02df2011-04-28 03:14:31 +0000428
David Blaikie4e4d0842012-03-11 07:00:24 +0000429 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000430 Ident__exception_info->setIsPoisoned(true);
431 Ident___exception_info->setIsPoisoned(true);
432 Ident_GetExceptionInfo->setIsPoisoned(true);
433 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000434
435 if(FilterExpr.isInvalid())
436 return StmtError();
437
438 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
439 return StmtError();
440
Richard Smith534986f2012-04-14 00:33:13 +0000441 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000442
443 if(Block.isInvalid())
444 return move(Block);
445
446 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
447}
448
449/// ParseSEHFinallyBlock - Handle __finally
450///
451/// seh-finally-block:
452/// '__finally' compound-statement
453///
454StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
455 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
456 raii2(Ident___abnormal_termination, false),
457 raii3(Ident_AbnormalTermination, false);
458
Richard Smith534986f2012-04-14 00:33:13 +0000459 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000460 if(Block.isInvalid())
461 return move(Block);
462
463 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000464}
465
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000466/// ParseLabeledStatement - We have an identifier and a ':' after it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000467///
468/// labeled-statement:
469/// identifier ':' statement
470/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000471///
Richard Smith534986f2012-04-14 00:33:13 +0000472StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000473 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
474 "Not an identifier!");
475
476 Token IdentTok = Tok; // Save the whole token.
477 ConsumeToken(); // eat the identifier.
478
479 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000480
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000481 // identifier ':' statement
482 SourceLocation ColonLoc = ConsumeToken();
483
Richard Smith534986f2012-04-14 00:33:13 +0000484 // Read label attributes, if present. attrs will contain both C++11 and GNU
485 // attributes (if present) after this point.
John McCall7f040a92010-12-24 02:08:15 +0000486 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000487
John McCall60d7b3a2010-08-24 06:29:42 +0000488 StmtResult SubStmt(ParseStatement());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000489
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000490 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000491 if (SubStmt.isInvalid())
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000492 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000493
Chris Lattner337e5502011-02-18 01:27:55 +0000494 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
495 IdentTok.getLocation());
Richard Smith534986f2012-04-14 00:33:13 +0000496 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattner337e5502011-02-18 01:27:55 +0000497 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smith534986f2012-04-14 00:33:13 +0000498 attrs.clear();
499 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000500
Chris Lattner337e5502011-02-18 01:27:55 +0000501 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
502 SubStmt.get());
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000503}
Reid Spencer5f016e22007-07-11 17:01:13 +0000504
505/// ParseCaseStatement
506/// labeled-statement:
507/// 'case' constant-expression ':' statement
508/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
509///
Richard Smith534986f2012-04-14 00:33:13 +0000510StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smith46f11102011-04-21 22:48:40 +0000511 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattner24e1e702009-03-04 04:23:07 +0000513 // It is very very common for code to contain many case statements recursively
514 // nested, as in (but usually without indentation):
515 // case 1:
516 // case 2:
517 // case 3:
518 // case 4:
519 // case 5: etc.
520 //
521 // Parsing this naively works, but is both inefficient and can cause us to run
522 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner26140c62009-03-04 18:24:58 +0000523 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner24e1e702009-03-04 04:23:07 +0000524 // but all the grossness is constrained to ParseCaseStatement (and some
525 // wierdness in the actions), so this is just local grossness :).
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner24e1e702009-03-04 04:23:07 +0000527 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
528 // example above.
John McCall60d7b3a2010-08-24 06:29:42 +0000529 StmtResult TopLevelCase(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner24e1e702009-03-04 04:23:07 +0000531 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
532 // gets updated each time a new case is parsed, and whose body is unset so
533 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieub2fc6902011-09-09 02:16:15 +0000534 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattner24e1e702009-03-04 04:23:07 +0000536 // While we have case statements, eat and stack them.
David Majnemer0e1e69c2011-06-13 05:50:12 +0000537 SourceLocation ColonLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000538 do {
Richard Trieubb9b80c2011-04-21 21:44:26 +0000539 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
540 ConsumeToken(); // eat the 'case'.
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000542 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000543 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000544 cutOffParsing();
545 return StmtError();
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000546 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000547
Chris Lattner6fb09c82009-12-10 00:38:54 +0000548 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
549 /// Disable this form of error recovery while we're parsing the case
550 /// expression.
551 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000552
Richard Trieubb9b80c2011-04-21 21:44:26 +0000553 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
554 MissingCase = false;
Chris Lattner24e1e702009-03-04 04:23:07 +0000555 if (LHS.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 SkipUntil(tok::colon);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000557 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000559
Chris Lattner24e1e702009-03-04 04:23:07 +0000560 // GNU case range extension.
561 SourceLocation DotDotDotLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000562 ExprResult RHS;
Chris Lattner24e1e702009-03-04 04:23:07 +0000563 if (Tok.is(tok::ellipsis)) {
564 Diag(Tok, diag::ext_gnu_case_range);
565 DotDotDotLoc = ConsumeToken();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000566
Chris Lattner24e1e702009-03-04 04:23:07 +0000567 RHS = ParseConstantExpression();
568 if (RHS.isInvalid()) {
569 SkipUntil(tok::colon);
570 return StmtError();
571 }
572 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000573
Chris Lattner6fb09c82009-12-10 00:38:54 +0000574 ColonProtection.restore();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000575
John McCallf6a3ab02011-01-22 09:28:32 +0000576 if (Tok.is(tok::colon)) {
577 ColonLoc = ConsumeToken();
578
579 // Treat "case blah;" as a typo for "case blah:".
580 } else if (Tok.is(tok::semi)) {
581 ColonLoc = ConsumeToken();
582 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
583 << FixItHint::CreateReplacement(ColonLoc, ":");
584 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000585 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
586 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
587 << FixItHint::CreateInsertion(ExpectedLoc, ":");
588 ColonLoc = ExpectedLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000589 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000590
John McCall60d7b3a2010-08-24 06:29:42 +0000591 StmtResult Case =
John McCall9ae2f072010-08-23 23:25:46 +0000592 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
593 RHS.get(), ColonLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Chris Lattner24e1e702009-03-04 04:23:07 +0000595 // If we had a sema error parsing this case, then just ignore it and
596 // continue parsing the sub-stmt.
597 if (Case.isInvalid()) {
598 if (TopLevelCase.isInvalid()) // No parsed case stmts.
599 return ParseStatement();
600 // Otherwise, just don't add it as a nested case.
601 } else {
602 // If this is the first case statement we parsed, it becomes TopLevelCase.
603 // Otherwise we link it into the current chain.
John McCallca0408f2010-08-23 06:44:23 +0000604 Stmt *NextDeepest = Case.get();
Chris Lattner24e1e702009-03-04 04:23:07 +0000605 if (TopLevelCase.isInvalid())
606 TopLevelCase = move(Case);
607 else
John McCall9ae2f072010-08-23 23:25:46 +0000608 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner24e1e702009-03-04 04:23:07 +0000609 DeepestParsedCaseStmt = NextDeepest;
610 }
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Chris Lattner24e1e702009-03-04 04:23:07 +0000612 // Handle all case statements.
613 } while (Tok.is(tok::kw_case));
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattner24e1e702009-03-04 04:23:07 +0000615 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Chris Lattner24e1e702009-03-04 04:23:07 +0000617 // If we found a non-case statement, start by parsing it.
John McCall60d7b3a2010-08-24 06:29:42 +0000618 StmtResult SubStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Chris Lattner24e1e702009-03-04 04:23:07 +0000620 if (Tok.isNot(tok::r_brace)) {
621 SubStmt = ParseStatement();
622 } else {
623 // Nicely diagnose the common error "switch (X) { case 4: }", which is
624 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000625 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000626 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
627 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner24e1e702009-03-04 04:23:07 +0000628 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 }
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Chris Lattner24e1e702009-03-04 04:23:07 +0000631 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000632 if (SubStmt.isInvalid())
Chris Lattner24e1e702009-03-04 04:23:07 +0000633 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chris Lattner24e1e702009-03-04 04:23:07 +0000635 // Install the body into the most deeply-nested case.
John McCall9ae2f072010-08-23 23:25:46 +0000636 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl61364dd2008-12-11 19:30:53 +0000637
Chris Lattner24e1e702009-03-04 04:23:07 +0000638 // Return the top level parsed statement tree.
Chris Lattner26140c62009-03-04 18:24:58 +0000639 return move(TopLevelCase);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640}
641
642/// ParseDefaultStatement
643/// labeled-statement:
644/// 'default' ':' statement
645/// Note that this does not parse the 'statement' at the end.
646///
Richard Smith534986f2012-04-14 00:33:13 +0000647StmtResult Parser::ParseDefaultStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000648 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000649 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
650
Douglas Gregor662a4822010-12-23 22:56:40 +0000651 SourceLocation ColonLoc;
John McCallf6a3ab02011-01-22 09:28:32 +0000652 if (Tok.is(tok::colon)) {
653 ColonLoc = ConsumeToken();
654
655 // Treat "default;" as a typo for "default:".
656 } else if (Tok.is(tok::semi)) {
657 ColonLoc = ConsumeToken();
658 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
659 << FixItHint::CreateReplacement(ColonLoc, ":");
660 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000661 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
662 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
663 << FixItHint::CreateInsertion(ExpectedLoc, ":");
664 ColonLoc = ExpectedLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000666
Richard Smith85b29a42012-02-17 01:35:32 +0000667 StmtResult SubStmt;
668
669 if (Tok.isNot(tok::r_brace)) {
670 SubStmt = ParseStatement();
671 } else {
672 // Diagnose the common error "switch (X) {... default: }", which is
673 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000674 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000675 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
676 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
677 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 }
679
Richard Smith85b29a42012-02-17 01:35:32 +0000680 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000681 if (SubStmt.isInvalid())
Richard Smith85b29a42012-02-17 01:35:32 +0000682 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000683
Sebastian Redl117054a2008-12-28 16:13:43 +0000684 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000685 SubStmt.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +0000686}
687
Richard Smith534986f2012-04-14 00:33:13 +0000688StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
689 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregorbca01b42011-07-06 22:04:06 +0000690}
Reid Spencer5f016e22007-07-11 17:01:13 +0000691
692/// ParseCompoundStatement - Parse a "{}" block.
693///
694/// compound-statement: [C99 6.8.2]
695/// { block-item-list[opt] }
696/// [GNU] { label-declarations block-item-list } [TODO]
697///
698/// block-item-list:
699/// block-item
700/// block-item-list block-item
701///
702/// block-item:
703/// declaration
Chris Lattner45a566c2007-08-27 01:01:57 +0000704/// [GNU] '__extension__' declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000705/// statement
706/// [OMP] openmp-directive [TODO]
707///
708/// [GNU] label-declarations:
709/// [GNU] label-declaration
710/// [GNU] label-declarations label-declaration
711///
712/// [GNU] label-declaration:
713/// [GNU] '__label__' identifier-list ';'
714///
715/// [OMP] openmp-directive: [TODO]
716/// [OMP] barrier-directive
717/// [OMP] flush-directive
718///
Richard Smith534986f2012-04-14 00:33:13 +0000719StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000720 unsigned ScopeFlags) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000721 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000722
Chris Lattner31e05722007-08-26 06:24:45 +0000723 // Enter a scope to hold everything within the compound stmt. Compound
724 // statements can always hold declarations.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000725 ParseScope CompoundScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000726
727 // Parse the statements in the body.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000728 return ParseCompoundStatementBody(isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000729}
730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff1b273c42007-09-16 14:56:35 +0000732/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Reid Spencer5f016e22007-07-11 17:01:13 +0000733/// consume the '}' at the end of the block. It does not manipulate the scope
734/// stack.
John McCall60d7b3a2010-08-24 06:29:42 +0000735StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump1eb44332009-09-09 15:08:12 +0000736 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerae50fa02009-03-05 00:00:31 +0000737 Tok.getLocation(),
738 "in compound statement ('{}')");
Douglas Gregor0fbda682010-09-15 14:51:05 +0000739 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000740 BalancedDelimiterTracker T(*this, tok::l_brace);
741 if (T.consumeOpen())
742 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000743
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000744 Sema::CompoundScopeRAII CompoundScope(Actions);
745
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000746 StmtVector Stmts(Actions);
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000747
Chris Lattner4ae493c2011-02-18 02:08:43 +0000748 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
749 // only allowed at the start of a compound stmt regardless of the language.
750 while (Tok.is(tok::kw___label__)) {
751 SourceLocation LabelLoc = ConsumeToken();
752 Diag(LabelLoc, diag::ext_gnu_local_label);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000753
Chris Lattner5f9e2722011-07-23 10:55:15 +0000754 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000755 while (1) {
756 if (Tok.isNot(tok::identifier)) {
757 Diag(Tok, diag::err_expected_ident);
758 break;
759 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000760
Chris Lattner4ae493c2011-02-18 02:08:43 +0000761 IdentifierInfo *II = Tok.getIdentifierInfo();
762 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara67843042011-03-05 18:21:20 +0000763 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000764
Chris Lattner4ae493c2011-02-18 02:08:43 +0000765 if (!Tok.is(tok::comma))
766 break;
767 ConsumeToken();
768 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000769
John McCall0b7e6782011-03-24 11:26:52 +0000770 DeclSpec DS(AttrFactory);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000771 DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
772 DeclsInGroup.data(), DeclsInGroup.size());
773 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000774
Chris Lattner8bb21d32012-04-28 16:12:17 +0000775 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000776 if (R.isUsable())
777 Stmts.push_back(R.release());
778 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000779
Chris Lattner4ae493c2011-02-18 02:08:43 +0000780 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000781 if (Tok.is(tok::annot_pragma_unused)) {
782 HandlePragmaUnused();
783 continue;
784 }
785
David Blaikie4e4d0842012-03-11 07:00:24 +0000786 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet1e862692011-05-06 20:48:22 +0000787 Tok.is(tok::kw___if_not_exists))) {
788 ParseMicrosoftIfExistsStatement(Stmts);
789 continue;
790 }
791
John McCall60d7b3a2010-08-24 06:29:42 +0000792 StmtResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000793 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000794 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattner45a566c2007-08-27 01:01:57 +0000795 } else {
796 // __extension__ can start declarations and it can also be a unary
797 // operator for expressions. Consume multiple __extension__ markers here
798 // until we can determine which is which.
Eli Friedmanadf077f2009-01-27 08:43:38 +0000799 // FIXME: This loses extension expressions in the AST!
Chris Lattner45a566c2007-08-27 01:01:57 +0000800 SourceLocation ExtLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000801 while (Tok.is(tok::kw___extension__))
Chris Lattner45a566c2007-08-27 01:01:57 +0000802 ConsumeToken();
Chris Lattner39146d62008-10-20 06:51:33 +0000803
John McCall0b7e6782011-03-24 11:26:52 +0000804 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith6ee326a2012-04-10 01:32:12 +0000805 MaybeParseCXX0XAttributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000806
Chris Lattner45a566c2007-08-27 01:01:57 +0000807 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis5404a152008-10-05 00:06:24 +0000808 if (isDeclarationStatement()) {
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000809 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner97144fc2009-04-02 04:16:50 +0000810 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000811 ExtensionRAIIObject O(Diags);
812
Chris Lattner97144fc2009-04-02 04:16:50 +0000813 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000814 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
815 Declarator::BlockContext, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000816 attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000817 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattner45a566c2007-08-27 01:01:57 +0000818 } else {
Eli Friedmanadf077f2009-01-27 08:43:38 +0000819 // Otherwise this was a unary __extension__ marker.
John McCall60d7b3a2010-08-24 06:29:42 +0000820 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattner043a0b52008-03-13 06:32:11 +0000821
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000822 if (Res.isInvalid()) {
Chris Lattner45a566c2007-08-27 01:01:57 +0000823 SkipUntil(tok::semi);
824 continue;
825 }
Sebastian Redlf512e822009-01-18 18:03:53 +0000826
Sean Huntbbd37c62009-11-21 08:43:09 +0000827 // FIXME: Use attributes?
Chris Lattner39146d62008-10-20 06:51:33 +0000828 // Eat the semicolon at the end of stmt and convert the expr into a
829 // statement.
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000830 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
John McCall9ae2f072010-08-23 23:25:46 +0000831 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
Chris Lattner45a566c2007-08-27 01:01:57 +0000832 }
833 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000834
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000835 if (R.isUsable())
Sebastian Redleffa8d12008-12-10 00:02:53 +0000836 Stmts.push_back(R.release());
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000838
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000839 SourceLocation CloseLoc = Tok.getLocation();
840
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 // We broke out of the while loop because we found a '}' or EOF.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000842 if (Tok.isNot(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 Diag(Tok, diag::err_expected_rbrace);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000844 Diag(T.getOpenLocation(), diag::note_matching) << "{";
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000845 // Recover by creating a compound statement with what we parsed so far,
846 // instead of dropping everything and returning StmtError();
847 } else {
848 if (!T.consumeClose())
849 CloseLoc = T.getCloseLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000850 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000851
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000852 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000853 move_arg(Stmts), isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000854}
855
Chris Lattner15ff1112008-12-12 06:31:07 +0000856/// ParseParenExprOrCondition:
857/// [C ] '(' expression ')'
Chris Lattnerff871fb2008-12-12 06:35:28 +0000858/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattner15ff1112008-12-12 06:31:07 +0000859///
860/// This function parses and performs error recovery on the specified condition
861/// or expression (depending on whether we're in C++ or C mode). This function
862/// goes out of its way to recover well. It returns true if there was a parser
863/// error (the right paren couldn't be found), which indicates that the caller
864/// should try to recover harder. It returns false if the condition is
865/// successfully parsed. Note that a successful parse can still have semantic
866/// errors in the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000867bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCalld226f652010-08-21 09:40:31 +0000868 Decl *&DeclResult,
Douglas Gregor586596f2010-05-06 17:25:47 +0000869 SourceLocation Loc,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000870 bool ConvertToBoolean) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000871 BalancedDelimiterTracker T(*this, tok::l_paren);
872 T.consumeOpen();
873
David Blaikie4e4d0842012-03-11 07:00:24 +0000874 if (getLangOpts().CPlusPlus)
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000875 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000876 else {
877 ExprResult = ParseExpression();
John McCalld226f652010-08-21 09:40:31 +0000878 DeclResult = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000879
Douglas Gregor586596f2010-05-06 17:25:47 +0000880 // If required, convert to a boolean value.
881 if (!ExprResult.isInvalid() && ConvertToBoolean)
882 ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000883 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000884 }
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Chris Lattner15ff1112008-12-12 06:31:07 +0000886 // If the parser was confused by the condition and we don't have a ')', try to
887 // recover by skipping ahead to a semi and bailing out. If condexp is
888 // semantically invalid but we have well formed code, keep going.
John McCalld226f652010-08-21 09:40:31 +0000889 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattner15ff1112008-12-12 06:31:07 +0000890 SkipUntil(tok::semi);
891 // Skipping may have stopped if it found the containing ')'. If so, we can
892 // continue parsing the if statement.
893 if (Tok.isNot(tok::r_paren))
894 return true;
895 }
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattner15ff1112008-12-12 06:31:07 +0000897 // Otherwise the condition is valid or the rparen is present.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000898 T.consumeClose();
Chad Rosierb6604462012-07-10 21:35:27 +0000899
Chris Lattnerbddc7e52012-04-28 16:24:20 +0000900 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
901 // that all callers are looking for a statement after the condition, so ")"
902 // isn't valid.
903 while (Tok.is(tok::r_paren)) {
904 Diag(Tok, diag::err_extraneous_rparen_in_condition)
905 << FixItHint::CreateRemoval(Tok.getLocation());
906 ConsumeParen();
907 }
Chad Rosierb6604462012-07-10 21:35:27 +0000908
Chris Lattner15ff1112008-12-12 06:31:07 +0000909 return false;
910}
911
912
Reid Spencer5f016e22007-07-11 17:01:13 +0000913/// ParseIfStatement
914/// if-statement: [C99 6.8.4.1]
915/// 'if' '(' expression ')' statement
916/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000917/// [C++] 'if' '(' condition ')' statement
918/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +0000919///
Richard Smith534986f2012-04-14 00:33:13 +0000920StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000921 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
923
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000924 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000925 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000927 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000929
David Blaikie4e4d0842012-03-11 07:00:24 +0000930 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000931
Chris Lattner22153252007-08-26 23:08:06 +0000932 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
933 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000934 //
935 // C++ 6.4p3:
936 // A name introduced by a declaration in a condition is in scope from its
937 // point of declaration until the end of the substatements controlled by the
938 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +0000939 // C++ 3.3.2p4:
940 // Names declared in the for-init-statement, and in the condition of if,
941 // while, for, and switch statements are local to the if, while, for, or
942 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000943 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000944 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +0000945
Reid Spencer5f016e22007-07-11 17:01:13 +0000946 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000947 ExprResult CondExp;
John McCalld226f652010-08-21 09:40:31 +0000948 Decl *CondVar = 0;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000949 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +0000950 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +0000951
David Blaikiedef07622012-05-16 04:20:04 +0000952 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Chris Lattner0ecea032007-08-22 05:28:50 +0000954 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000955 // there is no compound stmt. C90 does not have this clause. We only do this
956 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000957 //
958 // C++ 6.4p1:
959 // The substatement in a selection-statement (each substatement, in the else
960 // form of the if statement) implicitly defines a local scope.
961 //
962 // For C++ we create a scope for the condition and a new scope for
963 // substatements because:
964 // -When the 'then' scope exits, we want the condition declaration to still be
965 // active for the 'else' scope too.
966 // -Sema will detect name clashes by considering declarations of a
967 // 'ControlScope' as part of its direct subscope.
968 // -If we wanted the condition and substatement to be in the same scope, we
969 // would have to notify ParseStatement not to create a new scope. It's
970 // simpler to let it create a new scope.
971 //
Mike Stump1eb44332009-09-09 15:08:12 +0000972 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000973 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000974
Chris Lattnerb96728d2007-10-29 05:08:52 +0000975 // Read the 'then' stmt.
976 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +0000977
978 SourceLocation InnerStatementTrailingElseLoc;
979 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000980
Chris Lattnera36ce712007-08-22 05:16:28 +0000981 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000982 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000983
Reid Spencer5f016e22007-07-11 17:01:13 +0000984 // If it has an else, parse it.
985 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +0000986 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000987 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000988
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000989 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +0000990 if (TrailingElseLoc)
991 *TrailingElseLoc = Tok.getLocation();
992
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +0000994 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000995
Chris Lattner0ecea032007-08-22 05:28:50 +0000996 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000997 // there is no compound stmt. C90 does not have this clause. We only do
998 // this if the body isn't a compound statement to avoid push/pop in common
999 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001000 //
1001 // C++ 6.4p1:
1002 // The substatement in a selection-statement (each substatement, in the else
1003 // form of the if statement) implicitly defines a local scope.
1004 //
Sebastian Redl61364dd2008-12-11 19:30:53 +00001005 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001006 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001007
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001009
Chris Lattnera36ce712007-08-22 05:16:28 +00001010 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001011 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +00001012 } else if (Tok.is(tok::code_completion)) {
1013 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001014 cutOffParsing();
1015 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +00001016 } else if (InnerStatementTrailingElseLoc.isValid()) {
1017 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001019
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001020 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattner18914bc2008-12-12 06:19:11 +00001022 // If the condition was invalid, discard the if statement. We could recover
1023 // better by replacing it with a valid expr, but don't do that yet.
John McCalld226f652010-08-21 09:40:31 +00001024 if (CondExp.isInvalid() && !CondVar)
Chris Lattner18914bc2008-12-12 06:19:11 +00001025 return StmtError();
Chris Lattner22153252007-08-26 23:08:06 +00001026
Chris Lattnerb96728d2007-10-29 05:08:52 +00001027 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +00001028 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +00001029 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001030 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1031 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1032 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +00001033 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +00001034 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +00001035 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001036
Chris Lattnerb96728d2007-10-29 05:08:52 +00001037 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001038 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001039 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001040 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001041 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001042
John McCall9ae2f072010-08-23 23:25:46 +00001043 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001044 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001045}
1046
1047/// ParseSwitchStatement
1048/// switch-statement:
1049/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001050/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001051StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001052 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1054
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001055 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001056 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001057 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001058 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 }
Chris Lattner22153252007-08-26 23:08:06 +00001060
David Blaikie4e4d0842012-03-11 07:00:24 +00001061 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001062
Chris Lattner22153252007-08-26 23:08:06 +00001063 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1064 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001065 //
1066 // C++ 6.4p3:
1067 // A name introduced by a declaration in a condition is in scope from its
1068 // point of declaration until the end of the substatements controlled by the
1069 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001070 // C++ 3.3.2p4:
1071 // Names declared in the for-init-statement, and in the condition of if,
1072 // while, for, and switch statements are local to the if, while, for, or
1073 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001074 //
Richard Trieubb9b80c2011-04-21 21:44:26 +00001075 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001076 if (C99orCXX)
1077 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001078 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001079
1080 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001081 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001082 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001083 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001084 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001085
John McCall60d7b3a2010-08-24 06:29:42 +00001086 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001087 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001088
Douglas Gregor586596f2010-05-06 17:25:47 +00001089 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001090 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001091 // FIXME: This is not optimal recovery, but parsing the body is more
1092 // dangerous due to the presence of case and default statements, which
1093 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001094 if (Tok.is(tok::l_brace)) {
1095 ConsumeBrace();
1096 SkipUntil(tok::r_brace, false, false);
1097 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001098 SkipUntil(tok::semi);
1099 return move(Switch);
1100 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001101
Chris Lattner0ecea032007-08-22 05:28:50 +00001102 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001103 // there is no compound stmt. C90 does not have this clause. We only do this
1104 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001105 //
1106 // C++ 6.4p1:
1107 // The substatement in a selection-statement (each substatement, in the else
1108 // form of the if statement) implicitly defines a local scope.
1109 //
1110 // See comments in ParseIfStatement for why we create a scope for the
1111 // condition and a new scope for substatement in C++.
1112 //
Mike Stump1eb44332009-09-09 15:08:12 +00001113 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001114 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001115
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001117 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001118
Chris Lattner7e52de42010-01-24 01:50:29 +00001119 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001120 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001121 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001122
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001123 if (Body.isInvalid()) {
Chris Lattner7e52de42010-01-24 01:50:29 +00001124 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001125
1126 // Put the synthesized null statement on the same line as the end of switch
1127 // condition.
1128 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1129 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1130 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001131
John McCall9ae2f072010-08-23 23:25:46 +00001132 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001133}
1134
1135/// ParseWhileStatement
1136/// while-statement: [C99 6.8.5.1]
1137/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001138/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001139StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001140 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 SourceLocation WhileLoc = Tok.getLocation();
1142 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001143
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001144 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001145 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001147 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001149
David Blaikie4e4d0842012-03-11 07:00:24 +00001150 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001151
Chris Lattner22153252007-08-26 23:08:06 +00001152 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1153 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001154 //
1155 // C++ 6.4p3:
1156 // A name introduced by a declaration in a condition is in scope from its
1157 // point of declaration until the end of the substatements controlled by the
1158 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001159 // C++ 3.3.2p4:
1160 // Names declared in the for-init-statement, and in the condition of if,
1161 // while, for, and switch statements are local to the if, while, for, or
1162 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001163 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001164 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001165 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001166 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1167 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001168 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001169 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1170 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001171
1172 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001173 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001174 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001175 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001176 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001177
David Blaikiedef07622012-05-16 04:20:04 +00001178 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Chris Lattner0ecea032007-08-22 05:28:50 +00001180 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001181 // there is no compound stmt. C90 does not have this clause. We only do this
1182 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001183 //
1184 // C++ 6.5p2:
1185 // The substatement in an iteration-statement implicitly defines a local scope
1186 // which is entered and exited each time through the loop.
1187 //
1188 // See comments in ParseIfStatement for why we create a scope for the
1189 // condition and a new scope for substatement in C++.
1190 //
Mike Stump1eb44332009-09-09 15:08:12 +00001191 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001192 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001193
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001195 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001196
Chris Lattner0ecea032007-08-22 05:28:50 +00001197 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001198 InnerScope.Exit();
1199 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001200
John McCalld226f652010-08-21 09:40:31 +00001201 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001202 return StmtError();
1203
John McCall9ae2f072010-08-23 23:25:46 +00001204 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001205}
1206
1207/// ParseDoStatement
1208/// do-statement: [C99 6.8.5.2]
1209/// 'do' statement 'while' '(' expression ')' ';'
1210/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001211StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001212 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001214
Chris Lattner22153252007-08-26 23:08:06 +00001215 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1216 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001217 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001218 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001219 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001220 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001221 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001222
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001223 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001224
Chris Lattner0ecea032007-08-22 05:28:50 +00001225 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001226 // there is no compound stmt. C90 does not have this clause. We only do this
1227 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001228 //
1229 // C++ 6.5p2:
1230 // The substatement in an iteration-statement implicitly defines a local scope
1231 // which is entered and exited each time through the loop.
1232 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001233 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikie4e4d0842012-03-11 07:00:24 +00001234 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001235 Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001238 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001239
Chris Lattner0ecea032007-08-22 05:28:50 +00001240 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001241 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001242
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001243 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001244 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001245 Diag(Tok, diag::err_expected_while);
Chris Lattner28eb7e92008-11-23 23:17:07 +00001246 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner19504402008-11-13 18:52:53 +00001247 SkipUntil(tok::semi, false, true);
1248 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001249 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 }
1251 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001252
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001253 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001254 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner19504402008-11-13 18:52:53 +00001255 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001256 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001258
Chris Lattnerff871fb2008-12-12 06:35:28 +00001259 // Parse the parenthesized condition.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001260 BalancedDelimiterTracker T(*this, tok::l_paren);
1261 T.consumeOpen();
Chad Rosierb6604462012-07-10 21:35:27 +00001262
Sean Hunt2edf0a22012-06-23 05:07:58 +00001263 // FIXME: Do not just parse the attribute contents and throw them away
1264 ParsedAttributesWithRange attrs(AttrFactory);
1265 MaybeParseCXX0XAttributes(attrs);
1266 ProhibitAttributes(attrs);
1267
John McCall60d7b3a2010-08-24 06:29:42 +00001268 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001269 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001270 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001271
Sebastian Redl9a920342008-12-11 19:48:14 +00001272 if (Cond.isInvalid() || Body.isInvalid())
1273 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001274
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001275 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1276 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001277}
1278
1279/// ParseForStatement
1280/// for-statement: [C99 6.8.5.3]
1281/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1282/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001283/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1284/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001285/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001286/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1287/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001288///
1289/// [C++] for-init-statement:
1290/// [C++] expression-statement
1291/// [C++] simple-declaration
1292///
Richard Smithad762fc2011-04-14 22:09:26 +00001293/// [C++0x] for-range-declaration:
1294/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1295/// [C++0x] for-range-initializer:
1296/// [C++0x] expression
1297/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001298StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001299 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001301
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001302 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001303 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001305 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001307
Chad Rosierb6604462012-07-10 21:35:27 +00001308 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1309 getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001310
Chris Lattner22153252007-08-26 23:08:06 +00001311 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1312 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001313 //
1314 // C++ 6.4p3:
1315 // A name introduced by a declaration in a condition is in scope from its
1316 // point of declaration until the end of the substatements controlled by the
1317 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001318 // C++ 3.3.2p4:
1319 // Names declared in the for-init-statement, and in the condition of if,
1320 // while, for, and switch statements are local to the if, while, for, or
1321 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001322 // C++ 6.5.3p1:
1323 // Names declared in the for-init-statement are in the same declarative-region
1324 // as those declared in the condition.
1325 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001326 unsigned ScopeFlags;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001327 if (C99orCXXorObjC)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001328 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1329 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001330 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001331 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1332
1333 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001334
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001335 BalancedDelimiterTracker T(*this, tok::l_paren);
1336 T.consumeOpen();
1337
John McCall60d7b3a2010-08-24 06:29:42 +00001338 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001339
Richard Smithad762fc2011-04-14 22:09:26 +00001340 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001341 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001342 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001343 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001344 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001345 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001346 FullExprArg ThirdPart(Actions);
John McCalld226f652010-08-21 09:40:31 +00001347 Decl *SecondVar = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001348
Douglas Gregor791215b2009-09-21 20:51:25 +00001349 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001350 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001351 C99orCXXorObjC? Sema::PCC_ForInit
1352 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001353 cutOffParsing();
1354 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001355 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001356
Sean Hunt2edf0a22012-06-23 05:07:58 +00001357 ParsedAttributesWithRange attrs(AttrFactory);
1358 MaybeParseCXX0XAttributes(attrs);
1359
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001361 if (Tok.is(tok::semi)) { // for (;
Sean Hunt2edf0a22012-06-23 05:07:58 +00001362 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 // no first part, eat the ';'.
1364 ConsumeToken();
Eli Friedman9490ab42011-12-20 01:50:37 +00001365 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001367 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001369
John McCall0b7e6782011-03-24 11:26:52 +00001370 ParsedAttributesWithRange attrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +00001371 MaybeParseCXX0XAttributes(attrs);
Sean Huntbbd37c62009-11-21 08:43:09 +00001372
Richard Smithad762fc2011-04-14 22:09:26 +00001373 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001374 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001375 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1376
Chris Lattner97144fc2009-04-02 04:16:50 +00001377 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +00001378 StmtVector Stmts(Actions);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001379 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smithad762fc2011-04-14 22:09:26 +00001380 DeclEnd, attrs, false,
1381 MightBeForRangeStmt ?
1382 &ForRangeInit : 0);
Chris Lattnercd147752009-03-29 17:27:48 +00001383 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Richard Smithad762fc2011-04-14 22:09:26 +00001385 if (ForRangeInit.ParsedForRangeDecl()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001386 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001387 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001388
Richard Smithad762fc2011-04-14 22:09:26 +00001389 ForRange = true;
1390 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001391 ConsumeToken();
1392 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001393 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001394 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001395 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001396
Douglas Gregorfb629412010-08-23 21:17:50 +00001397 if (Tok.is(tok::code_completion)) {
1398 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001399 cutOffParsing();
1400 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001401 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001402 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001403 } else {
1404 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001405 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 } else {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001407 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 Value = ParseExpression();
1409
John McCallf6a16482010-12-04 03:47:34 +00001410 ForEach = isTokIdentifier_in();
1411
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001413 if (!Value.isInvalid()) {
1414 if (ForEach)
1415 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1416 else
1417 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1418 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001419
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001420 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001422 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001423 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001424
Douglas Gregorfb629412010-08-23 21:17:50 +00001425 if (Tok.is(tok::code_completion)) {
1426 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001427 cutOffParsing();
1428 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001429 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001430 Collection = ParseExpression();
David Blaikie4e4d0842012-03-11 07:00:24 +00001431 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001432 // User tried to write the reasonable, but ill-formed, for-range-statement
1433 // for (expr : expr) { ... }
1434 Diag(Tok, diag::err_for_range_expected_decl)
1435 << FirstPart.get()->getSourceRange();
1436 SkipUntil(tok::r_paren, false, true);
1437 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001438 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001439 if (!Value.isInvalid()) {
1440 Diag(Tok, diag::err_expected_semi_for);
1441 } else {
1442 // Skip until semicolon or rparen, don't consume it.
1443 SkipUntil(tok::r_paren, true, true);
1444 if (Tok.is(tok::semi))
1445 ConsumeToken();
1446 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 }
1448 }
Richard Smithad762fc2011-04-14 22:09:26 +00001449 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001450 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001451 // Parse the second part of the for specifier.
1452 if (Tok.is(tok::semi)) { // for (...;;
1453 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001454 } else if (Tok.is(tok::r_paren)) {
1455 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001456 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001457 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001458 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001459 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1460 else {
1461 Second = ParseExpression();
1462 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001463 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001464 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001465 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001466 SecondPartIsInvalid = Second.isInvalid();
David Blaikiedef07622012-05-16 04:20:04 +00001467 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001468 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001469
Douglas Gregorb72c7782011-02-17 03:38:46 +00001470 if (Tok.isNot(tok::semi)) {
1471 if (!SecondPartIsInvalid || SecondVar)
1472 Diag(Tok, diag::err_expected_semi_for);
1473 else
1474 // Skip until semicolon or rparen, don't consume it.
1475 SkipUntil(tok::r_paren, true, true);
1476 }
1477
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001478 if (Tok.is(tok::semi)) {
1479 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001480 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001481
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001482 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001483 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001484 ExprResult Third = ParseExpression();
John McCall9ae2f072010-08-23 23:25:46 +00001485 ThirdPart = Actions.MakeFullExpr(Third.take());
Douglas Gregor586596f2010-05-06 17:25:47 +00001486 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001489 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001490
Richard Smithad762fc2011-04-14 22:09:26 +00001491 // We need to perform most of the semantic analysis for a C++0x for-range
1492 // statememt before parsing the body, in order to be able to deduce the type
1493 // of an auto-typed loop variable.
1494 StmtResult ForRangeStmt;
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001495 StmtResult ForEachStmt;
Chad Rosierb6604462012-07-10 21:35:27 +00001496
John McCall990567c2011-07-27 01:07:15 +00001497 if (ForRange) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001498 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, T.getOpenLocation(),
Richard Smithad762fc2011-04-14 22:09:26 +00001499 FirstPart.take(),
1500 ForRangeInit.ColonLoc,
1501 ForRangeInit.RangeExpr.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001502 T.getCloseLocation());
Richard Smithad762fc2011-04-14 22:09:26 +00001503
John McCall990567c2011-07-27 01:07:15 +00001504
1505 // Similarly, we need to do the semantic analysis for a for-range
1506 // statement immediately in order to close over temporaries correctly.
1507 } else if (ForEach) {
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001508 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc, T.getOpenLocation(),
1509 FirstPart.take(),
Chad Rosierb6604462012-07-10 21:35:27 +00001510 Collection.take(),
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001511 T.getCloseLocation());
John McCall990567c2011-07-27 01:07:15 +00001512 }
1513
Chris Lattner0ecea032007-08-22 05:28:50 +00001514 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001515 // there is no compound stmt. C90 does not have this clause. We only do this
1516 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001517 //
1518 // C++ 6.5p2:
1519 // The substatement in an iteration-statement implicitly defines a local scope
1520 // which is entered and exited each time through the loop.
1521 //
1522 // See comments in ParseIfStatement for why we create a scope for
1523 // for-init-statement/condition and a new scope for substatement in C++.
1524 //
Mike Stump1eb44332009-09-09 15:08:12 +00001525 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001526 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001527
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001529 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001530
Chris Lattner0ecea032007-08-22 05:28:50 +00001531 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001532 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001533
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001535 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001536
1537 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001538 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001539
Richard Smithad762fc2011-04-14 22:09:26 +00001540 if (ForEach)
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001541 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1542 Body.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Richard Smithad762fc2011-04-14 22:09:26 +00001544 if (ForRange)
1545 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1546
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001547 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1548 SecondPart, SecondVar, ThirdPart,
1549 T.getCloseLocation(), Body.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001550}
1551
1552/// ParseGotoStatement
1553/// jump-statement:
1554/// 'goto' identifier ';'
1555/// [GNU] 'goto' '*' expression ';'
1556///
1557/// Note: this lets the caller parse the end ';'.
1558///
Richard Smith534986f2012-04-14 00:33:13 +00001559StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001560 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001562
John McCall60d7b3a2010-08-24 06:29:42 +00001563 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001564 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001565 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1566 Tok.getLocation());
1567 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001569 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 // GNU indirect goto extension.
1571 Diag(Tok, diag::ext_gnu_indirect_goto);
1572 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001573 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001574 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001576 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 }
John McCall9ae2f072010-08-23 23:25:46 +00001578 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattner95cfb852007-07-22 04:13:33 +00001579 } else {
1580 Diag(Tok, diag::err_expected_ident);
Sebastian Redl9a920342008-12-11 19:48:14 +00001581 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001583
Sebastian Redl9a920342008-12-11 19:48:14 +00001584 return move(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001585}
1586
1587/// ParseContinueStatement
1588/// jump-statement:
1589/// 'continue' ';'
1590///
1591/// Note: this lets the caller parse the end ';'.
1592///
Richard Smith534986f2012-04-14 00:33:13 +00001593StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001595 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001596}
1597
1598/// ParseBreakStatement
1599/// jump-statement:
1600/// 'break' ';'
1601///
1602/// Note: this lets the caller parse the end ';'.
1603///
Richard Smith534986f2012-04-14 00:33:13 +00001604StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001606 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001607}
1608
1609/// ParseReturnStatement
1610/// jump-statement:
1611/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001612StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001613 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001615
John McCall60d7b3a2010-08-24 06:29:42 +00001616 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001617 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001618 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001619 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001620 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001621 return StmtError();
1622 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001623
David Blaikie4e4d0842012-03-11 07:00:24 +00001624 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001625 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001626 if (R.isUsable())
David Blaikie4e4d0842012-03-11 07:00:24 +00001627 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +00001628 diag::warn_cxx98_compat_generalized_initializer_lists :
1629 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001630 << R.get()->getSourceRange();
1631 } else
1632 R = ParseExpression();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001633 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001635 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 }
1637 }
John McCall9ae2f072010-08-23 23:25:46 +00001638 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001639}
1640
Chad Rosiera01eddb2012-06-12 19:03:42 +00001641// needSpaceAsmToken - This function handles whitespace around asm punctuation.
Chad Rosierb6604462012-07-10 21:35:27 +00001642// Returns true if a space should be emitted.
Chad Rosiera01eddb2012-06-12 19:03:42 +00001643static inline bool needSpaceAsmToken(Token currTok) {
1644 static Token prevTok;
1645
1646 // No need for space after prevToken.
1647 switch(prevTok.getKind()) {
1648 default:
1649 break;
1650 case tok::l_square:
1651 case tok::r_square:
1652 case tok::l_brace:
1653 case tok::r_brace:
1654 case tok::colon:
1655 prevTok = currTok;
1656 return false;
1657 }
1658
1659 // No need for a space before currToken.
1660 switch(currTok.getKind()) {
1661 default:
1662 break;
1663 case tok::l_square:
1664 case tok::r_square:
1665 case tok::l_brace:
1666 case tok::r_brace:
1667 case tok::comma:
1668 case tok::colon:
1669 prevTok = currTok;
1670 return false;
1671 }
1672 prevTok = currTok;
1673 return true;
1674}
1675
Eli Friedman3fedbe12011-09-30 01:13:51 +00001676/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1677/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier8cd64b42012-06-11 20:47:18 +00001678///
1679/// [MS] ms-asm-statement:
1680/// ms-asm-block
1681/// ms-asm-block ms-asm-statement
1682///
1683/// [MS] ms-asm-block:
1684/// '__asm' ms-asm-line '\n'
1685/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1686///
1687/// [MS] ms-asm-instruction-block
1688/// ms-asm-line
1689/// ms-asm-line '\n' ms-asm-instruction-block
1690///
Eli Friedman3fedbe12011-09-30 01:13:51 +00001691StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1692 SourceManager &SrcMgr = PP.getSourceManager();
1693 SourceLocation EndLoc = AsmLoc;
Chad Rosier8cd64b42012-06-11 20:47:18 +00001694 SmallVector<Token, 4> AsmToks;
1695 SmallVector<unsigned, 4> LineEnds;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001696 do {
1697 bool InBraces = false;
NAKAMURA Takumi96e21712011-10-08 11:31:53 +00001698 unsigned short savedBraceCount = 0;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001699 bool InAsmComment = false;
1700 FileID FID;
NAKAMURA Takumi96e21712011-10-08 11:31:53 +00001701 unsigned LineNo = 0;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001702 unsigned NumTokensRead = 0;
1703 SourceLocation LBraceLoc;
1704
1705 if (Tok.is(tok::l_brace)) {
1706 // Braced inline asm: consume the opening brace.
1707 InBraces = true;
1708 savedBraceCount = BraceCount;
1709 EndLoc = LBraceLoc = ConsumeBrace();
1710 ++NumTokensRead;
1711 } else {
1712 // Single-line inline asm; compute which line it is on.
1713 std::pair<FileID, unsigned> ExpAsmLoc =
1714 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1715 FID = ExpAsmLoc.first;
1716 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1717 }
1718
Steve Naroff03d6bc62008-02-08 03:36:19 +00001719 SourceLocation TokLoc = Tok.getLocation();
Steve Naroff36280972008-02-08 18:01:27 +00001720 do {
Eli Friedman3fedbe12011-09-30 01:13:51 +00001721 // If we hit EOF, we're done, period.
1722 if (Tok.is(tok::eof))
1723 break;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001724
Chad Rosierb3b26bf2012-06-12 20:30:26 +00001725 // The asm keyword is a statement separator, so multiple asm statements
1726 // are allowed.
1727 if (!InAsmComment && Tok.is(tok::kw_asm))
1728 break;
1729
Eli Friedman3fedbe12011-09-30 01:13:51 +00001730 if (!InAsmComment && Tok.is(tok::semi)) {
1731 // A semicolon in an asm is the start of a comment.
1732 InAsmComment = true;
1733 if (InBraces) {
1734 // Compute which line the comment is on.
1735 std::pair<FileID, unsigned> ExpSemiLoc =
1736 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1737 FID = ExpSemiLoc.first;
1738 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
1739 }
1740 } else if (!InBraces || InAsmComment) {
1741 // If end-of-line is significant, check whether this token is on a
1742 // new line.
1743 std::pair<FileID, unsigned> ExpLoc =
1744 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1745 if (ExpLoc.first != FID ||
1746 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
1747 // If this is a single-line __asm, we're done.
1748 if (!InBraces)
1749 break;
1750 // We're no longer in a comment.
1751 InAsmComment = false;
1752 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
1753 // Single-line asm always ends when a closing brace is seen.
1754 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
1755 // does MSVC do here?
1756 break;
1757 }
Chad Rosiera01eddb2012-06-12 19:03:42 +00001758 }
1759 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
1760 BraceCount == (savedBraceCount + 1)) {
Chad Rosier8cd64b42012-06-11 20:47:18 +00001761 // Consume the closing brace, and finish
1762 EndLoc = ConsumeBrace();
1763 break;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001764 }
1765
1766 // Consume the next token; make sure we don't modify the brace count etc.
1767 // if we are in a comment.
Abramo Bagnaraa44724d2010-12-02 18:34:55 +00001768 EndLoc = TokLoc;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001769 if (InAsmComment)
1770 PP.Lex(Tok);
Chad Rosiera01eddb2012-06-12 19:03:42 +00001771 else {
1772 AsmToks.push_back(Tok);
Eli Friedman3fedbe12011-09-30 01:13:51 +00001773 ConsumeAnyToken();
Chad Rosiera01eddb2012-06-12 19:03:42 +00001774 }
Steve Naroff36280972008-02-08 18:01:27 +00001775 TokLoc = Tok.getLocation();
Eli Friedman3fedbe12011-09-30 01:13:51 +00001776 ++NumTokensRead;
1777 } while (1);
1778
Chad Rosier8cd64b42012-06-11 20:47:18 +00001779 LineEnds.push_back(AsmToks.size());
1780
Eli Friedman3fedbe12011-09-30 01:13:51 +00001781 if (InBraces && BraceCount != savedBraceCount) {
1782 // __asm without closing brace (this can happen at EOF).
1783 Diag(Tok, diag::err_expected_rbrace);
1784 Diag(LBraceLoc, diag::note_matching) << "{";
1785 return StmtError();
1786 } else if (NumTokensRead == 0) {
1787 // Empty __asm.
1788 Diag(Tok, diag::err_expected_lbrace);
1789 return StmtError();
1790 }
1791 // Multiple adjacent asm's form together into a single asm statement
1792 // in the AST.
1793 if (!Tok.is(tok::kw_asm))
1794 break;
1795 EndLoc = ConsumeToken();
1796 } while (1);
Chad Rosier8cd64b42012-06-11 20:47:18 +00001797
1798 // Collect the tokens into a string
1799 SmallString<512> Asm;
1800 SmallString<512> TokenBuf;
1801 TokenBuf.resize(512);
1802 unsigned AsmLineNum = 0;
Chad Rosiera01eddb2012-06-12 19:03:42 +00001803 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
Chad Rosier8cd64b42012-06-11 20:47:18 +00001804 const char *ThisTokBuf = &TokenBuf[0];
1805 bool StringInvalid = false;
Chad Rosierb6604462012-07-10 21:35:27 +00001806 unsigned ThisTokLen =
Chad Rosier8cd64b42012-06-11 20:47:18 +00001807 Lexer::getSpelling(AsmToks[i], ThisTokBuf, PP.getSourceManager(),
1808 PP.getLangOpts(), &StringInvalid);
Chad Rosiera01eddb2012-06-12 19:03:42 +00001809 if (i && (!AsmLineNum || i != LineEnds[AsmLineNum-1]) &&
1810 needSpaceAsmToken(AsmToks[i]))
1811 Asm += ' ';
Chad Rosier8cd64b42012-06-11 20:47:18 +00001812 Asm += StringRef(ThisTokBuf, ThisTokLen);
1813 if (i + 1 == LineEnds[AsmLineNum] && i + 1 != AsmToks.size()) {
1814 Asm += '\n';
1815 ++AsmLineNum;
1816 }
1817 }
1818
Chad Rosier8f726de2012-08-06 20:03:45 +00001819 // FIXME: We should be passing source locations for better diagnostics.
Chad Rosiera01eddb2012-06-12 19:03:42 +00001820 std::string AsmString = Asm.c_str();
Chad Rosier8f726de2012-08-06 20:03:45 +00001821 return Actions.ActOnMSAsmStmt(AsmLoc, AsmToks, AsmString, EndLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00001822}
1823
Reid Spencer5f016e22007-07-11 17:01:13 +00001824/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff5f8aa692008-02-11 23:15:56 +00001825/// asm-statement:
1826/// gnu-asm-statement
1827/// ms-asm-statement
1828///
1829/// [GNU] gnu-asm-statement:
Reid Spencer5f016e22007-07-11 17:01:13 +00001830/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1831///
1832/// [GNU] asm-argument:
1833/// asm-string-literal
1834/// asm-string-literal ':' asm-operands[opt]
1835/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1836/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1837/// ':' asm-clobbers
1838///
1839/// [GNU] asm-clobbers:
1840/// asm-string-literal
1841/// asm-clobbers ',' asm-string-literal
1842///
John McCall60d7b3a2010-08-24 06:29:42 +00001843StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001844 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattnerfe795952007-10-29 04:04:16 +00001845 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001846
Chad Rosierb6604462012-07-10 21:35:27 +00001847 if (getLangOpts().MicrosoftExt && Tok.isNot(tok::l_paren) &&
1848 !isTypeQualifier()) {
Steve Naroffd62701b2008-02-07 03:50:06 +00001849 msAsm = true;
Eli Friedman3fedbe12011-09-30 01:13:51 +00001850 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00001851 }
John McCall0b7e6782011-03-24 11:26:52 +00001852 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 SourceLocation Loc = Tok.getLocation();
Sean Huntbbd37c62009-11-21 08:43:09 +00001854 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redl9a920342008-12-11 19:48:14 +00001855
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1857 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner1ab3b962008-11-18 07:48:38 +00001858 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner1ab3b962008-11-18 07:48:38 +00001860 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Sebastian Redl9a920342008-12-11 19:48:14 +00001861
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 // Remember if this was a volatile asm.
Anders Carlsson39c47b52007-11-23 23:12:25 +00001863 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001864 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001865 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +00001866 SkipUntil(tok::r_paren);
Sebastian Redl9a920342008-12-11 19:48:14 +00001867 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001869 BalancedDelimiterTracker T(*this, tok::l_paren);
1870 T.consumeOpen();
Sebastian Redl9a920342008-12-11 19:48:14 +00001871
John McCall60d7b3a2010-08-24 06:29:42 +00001872 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenek320fa4b2011-12-02 01:30:14 +00001873 if (AsmString.isInvalid()) {
Richard Smith99831e42012-03-06 03:21:47 +00001874 // Consume up to and including the closing paren.
1875 T.skipToEnd();
Sebastian Redl9a920342008-12-11 19:48:14 +00001876 return StmtError();
Ted Kremenek320fa4b2011-12-02 01:30:14 +00001877 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001878
Chris Lattner5f9e2722011-07-23 10:55:15 +00001879 SmallVector<IdentifierInfo *, 4> Names;
Sebastian Redla55e52c2008-11-25 22:21:31 +00001880 ExprVector Constraints(Actions);
1881 ExprVector Exprs(Actions);
1882 ExprVector Clobbers(Actions);
Reid Spencer5f016e22007-07-11 17:01:13 +00001883
Anders Carlssondfab34a2008-02-05 23:03:50 +00001884 if (Tok.is(tok::r_paren)) {
Chris Lattner64cb4752009-12-20 23:00:41 +00001885 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001886 T.consumeClose();
Chris Lattner64cb4752009-12-20 23:00:41 +00001887 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001888 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
Chris Lattner64cb4752009-12-20 23:00:41 +00001889 move_arg(Constraints), move_arg(Exprs),
John McCall9ae2f072010-08-23 23:25:46 +00001890 AsmString.take(), move_arg(Clobbers),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001891 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001892 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001893
Chris Lattner64cb4752009-12-20 23:00:41 +00001894 // Parse Outputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001895 bool AteExtraColon = false;
1896 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1897 // In C++ mode, parse "::" like ": :".
1898 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattner64cb4752009-12-20 23:00:41 +00001899 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001900
Chris Lattner64056462009-12-20 23:08:04 +00001901 if (!AteExtraColon &&
1902 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00001903 return StmtError();
1904 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001905
Chris Lattner64cb4752009-12-20 23:00:41 +00001906 unsigned NumOutputs = Names.size();
1907
1908 // Parse Inputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001909 if (AteExtraColon ||
1910 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1911 // In C++ mode, parse "::" like ": :".
1912 if (AteExtraColon)
1913 AteExtraColon = false;
1914 else {
1915 AteExtraColon = Tok.is(tok::coloncolon);
1916 ConsumeToken();
1917 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001918
Chris Lattner64056462009-12-20 23:08:04 +00001919 if (!AteExtraColon &&
1920 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00001921 return StmtError();
1922 }
1923
1924 assert(Names.size() == Constraints.size() &&
1925 Constraints.size() == Exprs.size() &&
1926 "Input operand size mismatch!");
1927
1928 unsigned NumInputs = Names.size() - NumOutputs;
1929
1930 // Parse the clobbers, if present.
Chris Lattner64056462009-12-20 23:08:04 +00001931 if (AteExtraColon || Tok.is(tok::colon)) {
1932 if (!AteExtraColon)
1933 ConsumeToken();
Chris Lattner64cb4752009-12-20 23:00:41 +00001934
Chandler Carruth102e1b62010-07-22 07:11:21 +00001935 // Parse the asm-string list for clobbers if present.
1936 if (Tok.isNot(tok::r_paren)) {
1937 while (1) {
John McCall60d7b3a2010-08-24 06:29:42 +00001938 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattner64cb4752009-12-20 23:00:41 +00001939
Chandler Carruth102e1b62010-07-22 07:11:21 +00001940 if (Clobber.isInvalid())
1941 break;
Chris Lattner64cb4752009-12-20 23:00:41 +00001942
Chandler Carruth102e1b62010-07-22 07:11:21 +00001943 Clobbers.push_back(Clobber.release());
Chris Lattner64cb4752009-12-20 23:00:41 +00001944
Chandler Carruth102e1b62010-07-22 07:11:21 +00001945 if (Tok.isNot(tok::comma)) break;
1946 ConsumeToken();
1947 }
Chris Lattner64cb4752009-12-20 23:00:41 +00001948 }
1949 }
1950
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001951 T.consumeClose();
Chris Lattner64cb4752009-12-20 23:00:41 +00001952 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001953 NumOutputs, NumInputs, Names.data(),
Sebastian Redlf512e822009-01-18 18:03:53 +00001954 move_arg(Constraints), move_arg(Exprs),
John McCall9ae2f072010-08-23 23:25:46 +00001955 AsmString.take(), move_arg(Clobbers),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001956 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001957}
1958
1959/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattner64cb4752009-12-20 23:00:41 +00001960/// asm-statement, assuming the leading ':' token was eaten.
Reid Spencer5f016e22007-07-11 17:01:13 +00001961///
1962/// [GNU] asm-operands:
1963/// asm-operand
1964/// asm-operands ',' asm-operand
1965///
1966/// [GNU] asm-operand:
1967/// asm-string-literal '(' expression ')'
1968/// '[' identifier ']' asm-string-literal '(' expression ')'
1969///
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00001970//
1971// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001972bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001973 SmallVectorImpl<Expr *> &Constraints,
1974 SmallVectorImpl<Expr *> &Exprs) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 // 'asm-operands' isn't present?
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001976 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001977 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001978
1979 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 // Read the [id] if present.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001981 if (Tok.is(tok::l_square)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001982 BalancedDelimiterTracker T(*this, tok::l_square);
1983 T.consumeOpen();
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001985 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 Diag(Tok, diag::err_expected_ident);
1987 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00001988 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 }
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Anders Carlssonb235fc22007-11-22 01:36:19 +00001991 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner69efba72007-10-29 04:06:22 +00001992 ConsumeToken();
Anders Carlssonb235fc22007-11-22 01:36:19 +00001993
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001994 Names.push_back(II);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001995 T.consumeClose();
Anders Carlssonb235fc22007-11-22 01:36:19 +00001996 } else
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001997 Names.push_back(0);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001998
John McCall60d7b3a2010-08-24 06:29:42 +00001999 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002000 if (Constraint.isInvalid()) {
Anders Carlssonb235fc22007-11-22 01:36:19 +00002001 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002002 return true;
Anders Carlssonb235fc22007-11-22 01:36:19 +00002003 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002004 Constraints.push_back(Constraint.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00002005
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002006 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00002007 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002009 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002011
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 // Read the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002013 BalancedDelimiterTracker T(*this, tok::l_paren);
2014 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00002015 ExprResult Res(ParseExpression());
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002016 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002017 if (Res.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002018 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002019 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002021 Exprs.push_back(Res.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 // Eat the comma and continue parsing if it exists.
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002023 if (Tok.isNot(tok::comma)) return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002024 ConsumeToken();
2025 }
2026}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002027
Douglas Gregorc9977d02011-03-16 17:05:57 +00002028Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00002029 assert(Tok.is(tok::l_brace));
2030 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002031
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002032 if (SkipFunctionBodies && trySkippingFunctionBody()) {
2033 BodyScope.Exit();
2034 return Actions.ActOnFinishFunctionBody(Decl, 0);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002035 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002036
John McCallf312b1e2010-08-26 23:41:50 +00002037 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2038 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002040 // Do not enter a scope for the brace, as the arguments are in the same scope
2041 // (the function body) as the body itself. Instead, just read the statement
2042 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00002043 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00002044
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002045 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002046 if (FnBody.isInvalid()) {
2047 Sema::CompoundScopeRAII CompoundScope(Actions);
Mike Stump1eb44332009-09-09 15:08:12 +00002048 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Chris Lattner40e9bc82009-03-05 00:49:17 +00002049 MultiStmtArg(Actions), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002050 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00002051
Douglas Gregorc9977d02011-03-16 17:05:57 +00002052 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002053 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00002054}
Sebastian Redla0fd8652008-12-21 16:41:36 +00002055
Sebastian Redld3a413d2009-04-26 20:35:05 +00002056/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2057///
2058/// function-try-block:
2059/// 'try' ctor-initializer[opt] compound-statement handler-seq
2060///
Douglas Gregorc9977d02011-03-16 17:05:57 +00002061Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00002062 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2063 SourceLocation TryLoc = ConsumeToken();
2064
John McCallf312b1e2010-08-26 23:41:50 +00002065 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2066 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00002067
2068 // Constructor initializer list?
2069 if (Tok.is(tok::colon))
2070 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00002071 else
2072 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002073
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002074 if (SkipFunctionBodies && trySkippingFunctionBody()) {
2075 BodyScope.Exit();
2076 return Actions.ActOnFinishFunctionBody(Decl, 0);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002077 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002078
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002079 SourceLocation LBraceLoc = Tok.getLocation();
John McCall60d7b3a2010-08-24 06:29:42 +00002080 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
Sebastian Redld3a413d2009-04-26 20:35:05 +00002081 // If we failed to parse the try-catch, we just give the function an empty
2082 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002083 if (FnBody.isInvalid()) {
2084 Sema::CompoundScopeRAII CompoundScope(Actions);
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002085 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Sebastian Redld3a413d2009-04-26 20:35:05 +00002086 MultiStmtArg(Actions), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002087 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00002088
Douglas Gregorc9977d02011-03-16 17:05:57 +00002089 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002090 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redld3a413d2009-04-26 20:35:05 +00002091}
2092
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002093bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002094 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002095 assert(SkipFunctionBodies &&
2096 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002097
2098 // We're in code-completion mode. Skip parsing for all function bodies unless
2099 // the body contains the code-completion point.
2100 TentativeParsingAction PA(*this);
2101 ConsumeBrace();
2102 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002103 /*StopAtCodeCompletion=*/PP.isCodeCompletionEnabled())) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002104 PA.Commit();
2105 return true;
2106 }
2107
2108 PA.Revert();
2109 return false;
2110}
2111
Sebastian Redla0fd8652008-12-21 16:41:36 +00002112/// ParseCXXTryBlock - Parse a C++ try-block.
2113///
2114/// try-block:
2115/// 'try' compound-statement handler-seq
2116///
Richard Smith534986f2012-04-14 00:33:13 +00002117StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002118 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2119
2120 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002121 return ParseCXXTryBlockCommon(TryLoc);
2122}
2123
2124/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2125/// function-try-block.
2126///
2127/// try-block:
2128/// 'try' compound-statement handler-seq
2129///
2130/// function-try-block:
2131/// 'try' ctor-initializer[opt] compound-statement handler-seq
2132///
2133/// handler-seq:
2134/// handler handler-seq[opt]
2135///
John Wiegley28bbe4b2011-04-28 01:08:34 +00002136/// [Borland] try-block:
2137/// 'try' compound-statement seh-except-block
2138/// 'try' compound-statment seh-finally-block
2139///
John McCall60d7b3a2010-08-24 06:29:42 +00002140StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002141 if (Tok.isNot(tok::l_brace))
2142 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Sean Huntbbd37c62009-11-21 08:43:09 +00002143 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002144
2145 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002146 Scope::DeclScope|Scope::TryScope));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002147 if (TryBlock.isInvalid())
2148 return move(TryBlock);
2149
John Wiegley28bbe4b2011-04-28 01:08:34 +00002150 // Borland allows SEH-handlers with 'try'
Chad Rosierb6604462012-07-10 21:35:27 +00002151
Richard Smith534986f2012-04-14 00:33:13 +00002152 if ((Tok.is(tok::identifier) &&
2153 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2154 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002155 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2156 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00002157 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002158 SourceLocation Loc = ConsumeToken();
2159 Handler = ParseSEHExceptBlock(Loc);
2160 }
2161 else {
2162 SourceLocation Loc = ConsumeToken();
2163 Handler = ParseSEHFinallyBlock(Loc);
2164 }
2165 if(Handler.isInvalid())
2166 return move(Handler);
John McCall7f040a92010-12-24 02:08:15 +00002167
John Wiegley28bbe4b2011-04-28 01:08:34 +00002168 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2169 TryLoc,
2170 TryBlock.take(),
2171 Handler.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002172 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00002173 else {
2174 StmtVector Handlers(Actions);
Richard Smith534986f2012-04-14 00:33:13 +00002175 ParsedAttributesWithRange attrs(AttrFactory);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002176 MaybeParseCXX0XAttributes(attrs);
2177 ProhibitAttributes(attrs);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002178
John Wiegley28bbe4b2011-04-28 01:08:34 +00002179 if (Tok.isNot(tok::kw_catch))
2180 return StmtError(Diag(Tok, diag::err_expected_catch));
2181 while (Tok.is(tok::kw_catch)) {
2182 StmtResult Handler(ParseCXXCatchBlock());
2183 if (!Handler.isInvalid())
2184 Handlers.push_back(Handler.release());
2185 }
2186 // Don't bother creating the full statement if we don't have any usable
2187 // handlers.
2188 if (Handlers.empty())
2189 return StmtError();
2190
Chad Rosierb6604462012-07-10 21:35:27 +00002191 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(),move_arg(Handlers));
John Wiegley28bbe4b2011-04-28 01:08:34 +00002192 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002193}
2194
2195/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2196///
2197/// handler:
2198/// 'catch' '(' exception-declaration ')' compound-statement
2199///
2200/// exception-declaration:
2201/// type-specifier-seq declarator
2202/// type-specifier-seq abstract-declarator
2203/// type-specifier-seq
2204/// '...'
2205///
John McCall60d7b3a2010-08-24 06:29:42 +00002206StmtResult Parser::ParseCXXCatchBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002207 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2208
2209 SourceLocation CatchLoc = ConsumeToken();
2210
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002211 BalancedDelimiterTracker T(*this, tok::l_paren);
2212 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redla0fd8652008-12-21 16:41:36 +00002213 return StmtError();
2214
2215 // C++ 3.3.2p3:
2216 // The name in a catch exception-declaration is local to the handler and
2217 // shall not be redeclared in the outermost block of the handler.
2218 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
2219
2220 // exception-declaration is equivalent to '...' or a parameter-declaration
2221 // without default arguments.
John McCalld226f652010-08-21 09:40:31 +00002222 Decl *ExceptionDecl = 0;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002223 if (Tok.isNot(tok::ellipsis)) {
John McCall0b7e6782011-03-24 11:26:52 +00002224 DeclSpec DS(AttrFactory);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002225 if (ParseCXXTypeSpecifierSeq(DS))
2226 return StmtError();
Sebastian Redla0fd8652008-12-21 16:41:36 +00002227 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2228 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002229 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002230 } else
2231 ConsumeToken();
2232
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002233 T.consumeClose();
2234 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002235 return StmtError();
2236
2237 if (Tok.isNot(tok::l_brace))
2238 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2239
Sean Huntbbd37c62009-11-21 08:43:09 +00002240 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002241 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002242 if (Block.isInvalid())
2243 return move(Block);
2244
John McCall9ae2f072010-08-23 23:25:46 +00002245 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002246}
Francois Pichet1e862692011-05-06 20:48:22 +00002247
2248void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002249 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002250 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002251 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002252
Douglas Gregor3896fc52011-10-24 22:31:10 +00002253 // Handle dependent statements by parsing the braces as a compound statement.
2254 // This is not the same behavior as Visual C++, which don't treat this as a
2255 // compound statement, but for Clang's type checking we can't have anything
2256 // inside these braces escaping to the surrounding code.
2257 if (Result.Behavior == IEB_Dependent) {
2258 if (!Tok.is(tok::l_brace)) {
2259 Diag(Tok, diag::err_expected_lbrace);
Richard Smith534986f2012-04-14 00:33:13 +00002260 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002261 }
Richard Smith534986f2012-04-14 00:33:13 +00002262
2263 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002264 if (Compound.isInvalid())
2265 return;
Richard Smith534986f2012-04-14 00:33:13 +00002266
Douglas Gregorba0513d2011-10-25 01:33:02 +00002267 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2268 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002269 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002270 Result.Name,
2271 Compound.get());
2272 if (DepResult.isUsable())
2273 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002274 return;
2275 }
Richard Smith534986f2012-04-14 00:33:13 +00002276
Douglas Gregor3896fc52011-10-24 22:31:10 +00002277 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2278 if (Braces.consumeOpen()) {
Francois Pichet1e862692011-05-06 20:48:22 +00002279 Diag(Tok, diag::err_expected_lbrace);
2280 return;
2281 }
Francois Pichet1e862692011-05-06 20:48:22 +00002282
Douglas Gregor3896fc52011-10-24 22:31:10 +00002283 switch (Result.Behavior) {
2284 case IEB_Parse:
2285 // Parse the statements below.
2286 break;
Chad Rosierb6604462012-07-10 21:35:27 +00002287
Douglas Gregor3896fc52011-10-24 22:31:10 +00002288 case IEB_Dependent:
2289 llvm_unreachable("Dependent case handled above");
Chad Rosierb6604462012-07-10 21:35:27 +00002290
Douglas Gregor3896fc52011-10-24 22:31:10 +00002291 case IEB_Skip:
2292 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002293 return;
2294 }
2295
2296 // Condition is true, parse the statements.
2297 while (Tok.isNot(tok::r_brace)) {
2298 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2299 if (R.isUsable())
2300 Stmts.push_back(R.release());
2301 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002302 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002303}