blob: b03891082f4592ba8229a8fb39298178d28aebcf [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Statement and Block portions of the Parser
11// interface.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Parse/Parser.h"
Chris Lattnerd167ca02009-12-10 00:21:05 +000016#include "RAIIObjectsForParser.h"
John McCallaeeacf72013-05-03 00:10:13 +000017#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/PrettyStackTrace.h"
20#include "clang/Basic/SourceManager.h"
John McCallaeeacf72013-05-03 00:10:13 +000021#include "clang/Basic/TargetInfo.h"
John McCall19510852010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
John McCallf312b1e2010-08-26 23:41:50 +000023#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall19510852010-08-20 18:27:03 +000024#include "clang/Sema/Scope.h"
Richard Smith05766812012-08-18 00:55:03 +000025#include "clang/Sema/TypoCorrection.h"
John McCallaeeacf72013-05-03 00:10:13 +000026#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCObjectFileInfo.h"
29#include "llvm/MC/MCParser/MCAsmParser.h"
30#include "llvm/MC/MCRegisterInfo.h"
31#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSubtargetInfo.h"
33#include "llvm/MC/MCTargetAsmParser.h"
34#include "llvm/Support/SourceMgr.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
Chad Rosier8cd64b42012-06-11 20:47:18 +000037#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// C99 6.8: Statements and Blocks.
42//===----------------------------------------------------------------------===//
43
44/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
45/// StatementOrDeclaration:
46/// statement
47/// declaration
48///
49/// statement:
50/// labeled-statement
51/// compound-statement
52/// expression-statement
53/// selection-statement
54/// iteration-statement
55/// jump-statement
Argyrios Kyrtzidisdcdd55f2008-09-07 18:58:01 +000056/// [C++] declaration-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +000057/// [C++] try-block
John Wiegley28bbe4b2011-04-28 01:08:34 +000058/// [MS] seh-try-block
Fariborz Jahanianb384d322007-10-04 20:19:06 +000059/// [OBC] objc-throw-statement
60/// [OBC] objc-try-catch-statement
Fariborz Jahanianc385c902008-01-29 18:21:32 +000061/// [OBC] objc-synchronized-statement
Reid Spencer5f016e22007-07-11 17:01:13 +000062/// [GNU] asm-statement
63/// [OMP] openmp-construct [TODO]
64///
65/// labeled-statement:
66/// identifier ':' statement
67/// 'case' constant-expression ':' statement
68/// 'default' ':' statement
69///
70/// selection-statement:
71/// if-statement
72/// switch-statement
73///
74/// iteration-statement:
75/// while-statement
76/// do-statement
77/// for-statement
78///
79/// expression-statement:
80/// expression[opt] ';'
81///
82/// jump-statement:
83/// 'goto' identifier ';'
84/// 'continue' ';'
85/// 'break' ';'
86/// 'return' expression[opt] ';'
87/// [GNU] 'goto' '*' expression ';'
88///
Fariborz Jahanianb384d322007-10-04 20:19:06 +000089/// [OBC] objc-throw-statement:
90/// [OBC] '@' 'throw' expression ';'
Mike Stump1eb44332009-09-09 15:08:12 +000091/// [OBC] '@' 'throw' ';'
92///
John McCall60d7b3a2010-08-24 06:29:42 +000093StmtResult
Nico Weber5cb94a72011-12-22 23:26:17 +000094Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
95 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000096
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +000097 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +000098
Richard Smith534986f2012-04-14 00:33:13 +000099 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +0000100 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
Richard Smith534986f2012-04-14 00:33:13 +0000101
102 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
103 OnlyStatement, TrailingElseLoc, Attrs);
104
105 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
106 "attributes on empty statement");
107
108 if (Attrs.empty() || Res.isInvalid())
109 return Res;
110
111 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
112}
113
114StmtResult
115Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
116 bool OnlyStatement, SourceLocation *TrailingElseLoc,
117 ParsedAttributesWithRange &Attrs) {
118 const char *SemiError = 0;
119 StmtResult Res;
Sean Huntbbd37c62009-11-21 08:43:09 +0000120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 // Cases in this switch statement should fall through if the parser expects
122 // the token to end in a semicolon (in which case SemiError should be set),
123 // or they directly 'return;' if not.
Douglas Gregor312eadb2011-04-24 05:37:28 +0000124Retry:
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000125 tok::TokenKind Kind = Tok.getKind();
126 SourceLocation AtLoc;
127 switch (Kind) {
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000128 case tok::at: // May be a @try or @throw statement
129 {
Richard Smith534986f2012-04-14 00:33:13 +0000130 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000131 AtLoc = ConsumeToken(); // consume @
Sebastian Redl43bc2a02008-12-11 20:12:42 +0000132 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000133 }
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000134
Douglas Gregor791215b2009-09-21 20:51:25 +0000135 case tok::code_completion:
John McCallf312b1e2010-08-26 23:41:50 +0000136 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000137 cutOffParsing();
138 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000139
Douglas Gregor312eadb2011-04-24 05:37:28 +0000140 case tok::identifier: {
141 Token Next = NextToken();
142 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000143 // identifier ':' statement
Richard Smith534986f2012-04-14 00:33:13 +0000144 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000145 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000146
Richard Smith05766812012-08-18 00:55:03 +0000147 // Look up the identifier, and typo-correct it to a keyword if it's not
148 // found.
Douglas Gregor3b887352011-04-27 04:48:22 +0000149 if (Next.isNot(tok::coloncolon)) {
Richard Smith05766812012-08-18 00:55:03 +0000150 // Try to limit which sets of keywords should be included in typo
151 // correction based on what the next token is.
152 // FIXME: Pass the next token into the CorrectionCandidateCallback and
153 // do this filtering in a more fine-grained manner.
154 CorrectionCandidateCallback DefaultValidator;
155 DefaultValidator.WantTypeSpecifiers =
156 Next.is(tok::l_paren) || Next.is(tok::less) ||
157 Next.is(tok::identifier) || Next.is(tok::star) ||
158 Next.is(tok::amp) || Next.is(tok::l_square);
159 DefaultValidator.WantExpressionKeywords =
160 Next.is(tok::l_paren) || Next.is(tok::identifier) ||
161 Next.is(tok::arrow) || Next.is(tok::period);
162 DefaultValidator.WantRemainingKeywords =
163 Next.is(tok::l_paren) || Next.is(tok::semi) ||
164 Next.is(tok::identifier) || Next.is(tok::l_brace);
165 DefaultValidator.WantCXXNamedCasts = false;
166 if (TryAnnotateName(/*IsAddressOfOperand*/false, &DefaultValidator)
167 == ANK_Error) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000168 // Handle errors here by skipping up to the next semicolon or '}', and
169 // eat the semicolon if that's what stopped us.
170 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
171 if (Tok.is(tok::semi))
172 ConsumeToken();
173 return StmtError();
Richard Smith05766812012-08-18 00:55:03 +0000174 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000175
Richard Smith05766812012-08-18 00:55:03 +0000176 // If the identifier was typo-corrected, try again.
177 if (Tok.isNot(tok::identifier))
Douglas Gregor312eadb2011-04-24 05:37:28 +0000178 goto Retry;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000179 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000180
Douglas Gregor312eadb2011-04-24 05:37:28 +0000181 // Fall through
182 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000183
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000184 default: {
David Blaikie4e4d0842012-03-11 07:00:24 +0000185 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner97144fc2009-04-02 04:16:50 +0000186 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek8113ecf2010-11-10 05:59:39 +0000187 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smith534986f2012-04-14 00:33:13 +0000188 DeclEnd, Attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000189 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000190 }
191
192 if (Tok.is(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 Diag(Tok, diag::err_expected_statement);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000194 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 }
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Richard Smith534986f2012-04-14 00:33:13 +0000197 return ParseExprStatement();
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000198 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000199
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000201 return ParseCaseStatement();
Reid Spencer5f016e22007-07-11 17:01:13 +0000202 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000203 return ParseDefaultStatement();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000204
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smith534986f2012-04-14 00:33:13 +0000206 return ParseCompoundStatement();
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000207 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +0000208 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
209 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000210 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000211
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smith534986f2012-04-14 00:33:13 +0000213 return ParseIfStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smith534986f2012-04-14 00:33:13 +0000215 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smith534986f2012-04-14 00:33:13 +0000218 return ParseWhileStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000219 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smith534986f2012-04-14 00:33:13 +0000220 Res = ParseDoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000221 SemiError = "do/while";
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 break;
223 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smith534986f2012-04-14 00:33:13 +0000224 return ParseForStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000225
226 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smith534986f2012-04-14 00:33:13 +0000227 Res = ParseGotoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000228 SemiError = "goto";
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 break;
230 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smith534986f2012-04-14 00:33:13 +0000231 Res = ParseContinueStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000232 SemiError = "continue";
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 break;
234 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smith534986f2012-04-14 00:33:13 +0000235 Res = ParseBreakStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000236 SemiError = "break";
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 break;
238 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smith534986f2012-04-14 00:33:13 +0000239 Res = ParseReturnStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000240 SemiError = "return";
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 break;
Sebastian Redl61364dd2008-12-11 19:30:53 +0000242
Sebastian Redla0fd8652008-12-21 16:41:36 +0000243 case tok::kw_asm: {
Richard Smith534986f2012-04-14 00:33:13 +0000244 ProhibitAttributes(Attrs);
Steve Naroffd62701b2008-02-07 03:50:06 +0000245 bool msAsm = false;
246 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +0000247 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000248 if (msAsm) return Res;
Chris Lattner6869d8e2009-06-14 00:07:48 +0000249 SemiError = "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 break;
251 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000252
Sebastian Redla0fd8652008-12-21 16:41:36 +0000253 case tok::kw_try: // C++ 15: try-block
Richard Smith534986f2012-04-14 00:33:13 +0000254 return ParseCXXTryBlock();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000255
256 case tok::kw___try:
Richard Smith534986f2012-04-14 00:33:13 +0000257 ProhibitAttributes(Attrs); // TODO: is it correct?
258 return ParseSEHTryBlock();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000259
260 case tok::annot_pragma_vis:
Richard Smith534986f2012-04-14 00:33:13 +0000261 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000262 HandlePragmaVisibility();
263 return StmtEmpty();
264
265 case tok::annot_pragma_pack:
Richard Smith534986f2012-04-14 00:33:13 +0000266 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000267 HandlePragmaPack();
268 return StmtEmpty();
Eli Friedman9595c7e2012-10-04 02:36:51 +0000269
Eli Friedman8b2bfdd2012-10-09 22:46:54 +0000270 case tok::annot_pragma_msstruct:
271 ProhibitAttributes(Attrs);
272 HandlePragmaMSStruct();
273 return StmtEmpty();
274
Eli Friedman3ef38ee2012-10-08 23:52:38 +0000275 case tok::annot_pragma_align:
276 ProhibitAttributes(Attrs);
277 HandlePragmaAlign();
278 return StmtEmpty();
279
Eli Friedman8b2bfdd2012-10-09 22:46:54 +0000280 case tok::annot_pragma_weak:
281 ProhibitAttributes(Attrs);
282 HandlePragmaWeak();
283 return StmtEmpty();
284
285 case tok::annot_pragma_weakalias:
286 ProhibitAttributes(Attrs);
287 HandlePragmaWeakAlias();
288 return StmtEmpty();
289
290 case tok::annot_pragma_redefine_extname:
291 ProhibitAttributes(Attrs);
292 HandlePragmaRedefineExtname();
293 return StmtEmpty();
294
Eli Friedman9595c7e2012-10-04 02:36:51 +0000295 case tok::annot_pragma_fp_contract:
Lang Hames860022c2012-10-21 01:10:01 +0000296 Diag(Tok, diag::err_pragma_fp_contract_scope);
297 ConsumeToken();
298 return StmtError();
299
Eli Friedman9595c7e2012-10-04 02:36:51 +0000300 case tok::annot_pragma_opencl_extension:
301 ProhibitAttributes(Attrs);
302 HandlePragmaOpenCLExtension();
303 return StmtEmpty();
Alexey Bataevc6400582013-03-22 06:34:35 +0000304
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000305 case tok::annot_pragma_captured:
306 return HandlePragmaCaptured();
307
Alexey Bataevc6400582013-03-22 06:34:35 +0000308 case tok::annot_pragma_openmp:
Alexey Bataev4fa7eab2013-07-19 03:13:43 +0000309 return ParseOpenMPDeclarativeOrExecutableDirective();
310
Sebastian Redla0fd8652008-12-21 16:41:36 +0000311 }
312
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 // If we reached this code, the statement must end in a semicolon.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000314 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 ConsumeToken();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000316 } else if (!Res.isInvalid()) {
Chris Lattner7b3684a2009-06-14 00:23:56 +0000317 // If the result was valid, then we do want to diagnose this. Use
318 // ExpectAndConsume to emit the diagnostic, even though we know it won't
319 // succeed.
320 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner19504402008-11-13 18:52:53 +0000321 // Skip until we see a } or ;, but don't eat it.
322 SkipUntil(tok::r_brace, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 }
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000325 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000326}
327
Douglas Gregor312eadb2011-04-24 05:37:28 +0000328/// \brief Parse an expression statement.
Richard Smith534986f2012-04-14 00:33:13 +0000329StmtResult Parser::ParseExprStatement() {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000330 // If a case keyword is missing, this is where it should be inserted.
331 Token OldToken = Tok;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000332
Douglas Gregor312eadb2011-04-24 05:37:28 +0000333 // expression[opt] ';'
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000334 ExprResult Expr(ParseExpression());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000335 if (Expr.isInvalid()) {
336 // If the expression is invalid, skip ahead to the next semicolon or '}'.
337 // Not doing this opens us up to the possibility of infinite loops if
338 // ParseExpression does not consume any tokens.
339 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
340 if (Tok.is(tok::semi))
341 ConsumeToken();
John McCallb760f112013-03-22 02:10:40 +0000342 return Actions.ActOnExprStmtError();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000343 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000344
Douglas Gregor312eadb2011-04-24 05:37:28 +0000345 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
346 Actions.CheckCaseExpression(Expr.get())) {
347 // If a constant expression is followed by a colon inside a switch block,
348 // suggest a missing case keyword.
349 Diag(OldToken, diag::err_expected_case_before_expression)
350 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000351
Douglas Gregor312eadb2011-04-24 05:37:28 +0000352 // Recover parsing as a case statement.
Richard Smith534986f2012-04-14 00:33:13 +0000353 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000354 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000355
Douglas Gregor312eadb2011-04-24 05:37:28 +0000356 // Otherwise, eat the semicolon.
357 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000358 return Actions.ActOnExprStmt(Expr);
John Wiegley28bbe4b2011-04-28 01:08:34 +0000359}
Douglas Gregor312eadb2011-04-24 05:37:28 +0000360
Richard Smith534986f2012-04-14 00:33:13 +0000361StmtResult Parser::ParseSEHTryBlock() {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000362 assert(Tok.is(tok::kw___try) && "Expected '__try'");
363 SourceLocation Loc = ConsumeToken();
364 return ParseSEHTryBlockCommon(Loc);
365}
366
367/// ParseSEHTryBlockCommon
368///
369/// seh-try-block:
370/// '__try' compound-statement seh-handler
371///
372/// seh-handler:
373/// seh-except-block
374/// seh-finally-block
375///
376StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
377 if(Tok.isNot(tok::l_brace))
378 return StmtError(Diag(Tok,diag::err_expected_lbrace));
379
Joao Matos568ba872012-09-04 17:49:35 +0000380 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000381 if(TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000382 return TryBlock;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000383
384 StmtResult Handler;
Richard Smith534986f2012-04-14 00:33:13 +0000385 if (Tok.is(tok::identifier) &&
Douglas Gregorb57791e2011-10-21 03:57:52 +0000386 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000387 SourceLocation Loc = ConsumeToken();
388 Handler = ParseSEHExceptBlock(Loc);
389 } else if (Tok.is(tok::kw___finally)) {
390 SourceLocation Loc = ConsumeToken();
391 Handler = ParseSEHFinallyBlock(Loc);
392 } else {
393 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
394 }
395
396 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000397 return Handler;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000398
399 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
400 TryLoc,
401 TryBlock.take(),
402 Handler.take());
403}
404
405/// ParseSEHExceptBlock - Handle __except
406///
407/// seh-except-block:
408/// '__except' '(' seh-filter-expression ')' compound-statement
409///
410StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
411 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
412 raii2(Ident___exception_code, false),
413 raii3(Ident_GetExceptionCode, false);
414
415 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
416 return StmtError();
417
418 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
419
David Blaikie4e4d0842012-03-11 07:00:24 +0000420 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000421 Ident__exception_info->setIsPoisoned(false);
422 Ident___exception_info->setIsPoisoned(false);
423 Ident_GetExceptionInfo->setIsPoisoned(false);
424 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000425 ExprResult FilterExpr(ParseExpression());
Francois Pichetd7f02df2011-04-28 03:14:31 +0000426
David Blaikie4e4d0842012-03-11 07:00:24 +0000427 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000428 Ident__exception_info->setIsPoisoned(true);
429 Ident___exception_info->setIsPoisoned(true);
430 Ident_GetExceptionInfo->setIsPoisoned(true);
431 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000432
433 if(FilterExpr.isInvalid())
434 return StmtError();
435
436 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
437 return StmtError();
438
Richard Smith534986f2012-04-14 00:33:13 +0000439 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000440
441 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000442 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000443
444 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
445}
446
447/// ParseSEHFinallyBlock - Handle __finally
448///
449/// seh-finally-block:
450/// '__finally' compound-statement
451///
452StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
453 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
454 raii2(Ident___abnormal_termination, false),
455 raii3(Ident_AbnormalTermination, false);
456
Richard Smith534986f2012-04-14 00:33:13 +0000457 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000458 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000459 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000460
461 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000462}
463
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000464/// ParseLabeledStatement - We have an identifier and a ':' after it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000465///
466/// labeled-statement:
467/// identifier ':' statement
468/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000469///
Richard Smith534986f2012-04-14 00:33:13 +0000470StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000471 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
472 "Not an identifier!");
473
474 Token IdentTok = Tok; // Save the whole token.
475 ConsumeToken(); // eat the identifier.
476
477 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000478
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000479 // identifier ':' statement
480 SourceLocation ColonLoc = ConsumeToken();
481
Richard Smith534986f2012-04-14 00:33:13 +0000482 // Read label attributes, if present. attrs will contain both C++11 and GNU
483 // attributes (if present) after this point.
John McCall7f040a92010-12-24 02:08:15 +0000484 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000485
John McCall60d7b3a2010-08-24 06:29:42 +0000486 StmtResult SubStmt(ParseStatement());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000487
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000488 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000489 if (SubStmt.isInvalid())
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000490 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000491
Chris Lattner337e5502011-02-18 01:27:55 +0000492 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
493 IdentTok.getLocation());
Richard Smith534986f2012-04-14 00:33:13 +0000494 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattner337e5502011-02-18 01:27:55 +0000495 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smith534986f2012-04-14 00:33:13 +0000496 attrs.clear();
497 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000498
Chris Lattner337e5502011-02-18 01:27:55 +0000499 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
500 SubStmt.get());
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000501}
Reid Spencer5f016e22007-07-11 17:01:13 +0000502
503/// ParseCaseStatement
504/// labeled-statement:
505/// 'case' constant-expression ':' statement
506/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
507///
Richard Smith534986f2012-04-14 00:33:13 +0000508StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smith46f11102011-04-21 22:48:40 +0000509 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner24e1e702009-03-04 04:23:07 +0000511 // It is very very common for code to contain many case statements recursively
512 // nested, as in (but usually without indentation):
513 // case 1:
514 // case 2:
515 // case 3:
516 // case 4:
517 // case 5: etc.
518 //
519 // Parsing this naively works, but is both inefficient and can cause us to run
520 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner26140c62009-03-04 18:24:58 +0000521 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner24e1e702009-03-04 04:23:07 +0000522 // but all the grossness is constrained to ParseCaseStatement (and some
523 // wierdness in the actions), so this is just local grossness :).
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner24e1e702009-03-04 04:23:07 +0000525 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
526 // example above.
John McCall60d7b3a2010-08-24 06:29:42 +0000527 StmtResult TopLevelCase(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Chris Lattner24e1e702009-03-04 04:23:07 +0000529 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
530 // gets updated each time a new case is parsed, and whose body is unset so
531 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieub2fc6902011-09-09 02:16:15 +0000532 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Chris Lattner24e1e702009-03-04 04:23:07 +0000534 // While we have case statements, eat and stack them.
David Majnemer0e1e69c2011-06-13 05:50:12 +0000535 SourceLocation ColonLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000536 do {
Richard Trieubb9b80c2011-04-21 21:44:26 +0000537 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
538 ConsumeToken(); // eat the 'case'.
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000540 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000541 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000542 cutOffParsing();
543 return StmtError();
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000544 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000545
Chris Lattner6fb09c82009-12-10 00:38:54 +0000546 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
547 /// Disable this form of error recovery while we're parsing the case
548 /// expression.
549 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000550
Richard Trieubb9b80c2011-04-21 21:44:26 +0000551 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
552 MissingCase = false;
Chris Lattner24e1e702009-03-04 04:23:07 +0000553 if (LHS.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 SkipUntil(tok::colon);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000555 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000557
Chris Lattner24e1e702009-03-04 04:23:07 +0000558 // GNU case range extension.
559 SourceLocation DotDotDotLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000560 ExprResult RHS;
Chris Lattner24e1e702009-03-04 04:23:07 +0000561 if (Tok.is(tok::ellipsis)) {
562 Diag(Tok, diag::ext_gnu_case_range);
563 DotDotDotLoc = ConsumeToken();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000564
Chris Lattner24e1e702009-03-04 04:23:07 +0000565 RHS = ParseConstantExpression();
566 if (RHS.isInvalid()) {
567 SkipUntil(tok::colon);
568 return StmtError();
569 }
570 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000571
Chris Lattner6fb09c82009-12-10 00:38:54 +0000572 ColonProtection.restore();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000573
John McCallf6a3ab02011-01-22 09:28:32 +0000574 if (Tok.is(tok::colon)) {
575 ColonLoc = ConsumeToken();
576
577 // Treat "case blah;" as a typo for "case blah:".
578 } else if (Tok.is(tok::semi)) {
579 ColonLoc = ConsumeToken();
580 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
581 << FixItHint::CreateReplacement(ColonLoc, ":");
582 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000583 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
584 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
585 << FixItHint::CreateInsertion(ExpectedLoc, ":");
586 ColonLoc = ExpectedLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000587 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000588
John McCall60d7b3a2010-08-24 06:29:42 +0000589 StmtResult Case =
John McCall9ae2f072010-08-23 23:25:46 +0000590 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
591 RHS.get(), ColonLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner24e1e702009-03-04 04:23:07 +0000593 // If we had a sema error parsing this case, then just ignore it and
594 // continue parsing the sub-stmt.
595 if (Case.isInvalid()) {
596 if (TopLevelCase.isInvalid()) // No parsed case stmts.
597 return ParseStatement();
598 // Otherwise, just don't add it as a nested case.
599 } else {
600 // If this is the first case statement we parsed, it becomes TopLevelCase.
601 // Otherwise we link it into the current chain.
John McCallca0408f2010-08-23 06:44:23 +0000602 Stmt *NextDeepest = Case.get();
Chris Lattner24e1e702009-03-04 04:23:07 +0000603 if (TopLevelCase.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000604 TopLevelCase = Case;
Chris Lattner24e1e702009-03-04 04:23:07 +0000605 else
John McCall9ae2f072010-08-23 23:25:46 +0000606 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner24e1e702009-03-04 04:23:07 +0000607 DeepestParsedCaseStmt = NextDeepest;
608 }
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattner24e1e702009-03-04 04:23:07 +0000610 // Handle all case statements.
611 } while (Tok.is(tok::kw_case));
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Chris Lattner24e1e702009-03-04 04:23:07 +0000613 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattner24e1e702009-03-04 04:23:07 +0000615 // If we found a non-case statement, start by parsing it.
John McCall60d7b3a2010-08-24 06:29:42 +0000616 StmtResult SubStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattner24e1e702009-03-04 04:23:07 +0000618 if (Tok.isNot(tok::r_brace)) {
619 SubStmt = ParseStatement();
620 } else {
621 // Nicely diagnose the common error "switch (X) { case 4: }", which is
622 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000623 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000624 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
625 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner24e1e702009-03-04 04:23:07 +0000626 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 }
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattner24e1e702009-03-04 04:23:07 +0000629 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000630 if (SubStmt.isInvalid())
Chris Lattner24e1e702009-03-04 04:23:07 +0000631 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattner24e1e702009-03-04 04:23:07 +0000633 // Install the body into the most deeply-nested case.
John McCall9ae2f072010-08-23 23:25:46 +0000634 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl61364dd2008-12-11 19:30:53 +0000635
Chris Lattner24e1e702009-03-04 04:23:07 +0000636 // Return the top level parsed statement tree.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000637 return TopLevelCase;
Reid Spencer5f016e22007-07-11 17:01:13 +0000638}
639
640/// ParseDefaultStatement
641/// labeled-statement:
642/// 'default' ':' statement
643/// Note that this does not parse the 'statement' at the end.
644///
Richard Smith534986f2012-04-14 00:33:13 +0000645StmtResult Parser::ParseDefaultStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000646 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
648
Douglas Gregor662a4822010-12-23 22:56:40 +0000649 SourceLocation ColonLoc;
John McCallf6a3ab02011-01-22 09:28:32 +0000650 if (Tok.is(tok::colon)) {
651 ColonLoc = ConsumeToken();
652
653 // Treat "default;" as a typo for "default:".
654 } else if (Tok.is(tok::semi)) {
655 ColonLoc = ConsumeToken();
656 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
657 << FixItHint::CreateReplacement(ColonLoc, ":");
658 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000659 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
660 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
661 << FixItHint::CreateInsertion(ExpectedLoc, ":");
662 ColonLoc = ExpectedLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000664
Richard Smith85b29a42012-02-17 01:35:32 +0000665 StmtResult SubStmt;
666
667 if (Tok.isNot(tok::r_brace)) {
668 SubStmt = ParseStatement();
669 } else {
670 // Diagnose the common error "switch (X) {... default: }", which is
671 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000672 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000673 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
674 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
675 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000676 }
677
Richard Smith85b29a42012-02-17 01:35:32 +0000678 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000679 if (SubStmt.isInvalid())
Richard Smith85b29a42012-02-17 01:35:32 +0000680 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000681
Sebastian Redl117054a2008-12-28 16:13:43 +0000682 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000683 SubStmt.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +0000684}
685
Richard Smith534986f2012-04-14 00:33:13 +0000686StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
687 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregorbca01b42011-07-06 22:04:06 +0000688}
Reid Spencer5f016e22007-07-11 17:01:13 +0000689
690/// ParseCompoundStatement - Parse a "{}" block.
691///
692/// compound-statement: [C99 6.8.2]
693/// { block-item-list[opt] }
694/// [GNU] { label-declarations block-item-list } [TODO]
695///
696/// block-item-list:
697/// block-item
698/// block-item-list block-item
699///
700/// block-item:
701/// declaration
Chris Lattner45a566c2007-08-27 01:01:57 +0000702/// [GNU] '__extension__' declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000703/// statement
704/// [OMP] openmp-directive [TODO]
705///
706/// [GNU] label-declarations:
707/// [GNU] label-declaration
708/// [GNU] label-declarations label-declaration
709///
710/// [GNU] label-declaration:
711/// [GNU] '__label__' identifier-list ';'
712///
713/// [OMP] openmp-directive: [TODO]
714/// [OMP] barrier-directive
715/// [OMP] flush-directive
716///
Richard Smith534986f2012-04-14 00:33:13 +0000717StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000718 unsigned ScopeFlags) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000719 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000720
Chris Lattner31e05722007-08-26 06:24:45 +0000721 // Enter a scope to hold everything within the compound stmt. Compound
722 // statements can always hold declarations.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000723 ParseScope CompoundScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000724
725 // Parse the statements in the body.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000726 return ParseCompoundStatementBody(isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000727}
728
Lang Hamesa60d21d2012-11-03 22:29:05 +0000729/// Parse any pragmas at the start of the compound expression. We handle these
730/// separately since some pragmas (FP_CONTRACT) must appear before any C
731/// statement in the compound, but may be intermingled with other pragmas.
732void Parser::ParseCompoundStatementLeadingPragmas() {
733 bool checkForPragmas = true;
734 while (checkForPragmas) {
735 switch (Tok.getKind()) {
736 case tok::annot_pragma_vis:
737 HandlePragmaVisibility();
738 break;
739 case tok::annot_pragma_pack:
740 HandlePragmaPack();
741 break;
742 case tok::annot_pragma_msstruct:
743 HandlePragmaMSStruct();
744 break;
745 case tok::annot_pragma_align:
746 HandlePragmaAlign();
747 break;
748 case tok::annot_pragma_weak:
749 HandlePragmaWeak();
750 break;
751 case tok::annot_pragma_weakalias:
752 HandlePragmaWeakAlias();
753 break;
754 case tok::annot_pragma_redefine_extname:
755 HandlePragmaRedefineExtname();
756 break;
757 case tok::annot_pragma_opencl_extension:
758 HandlePragmaOpenCLExtension();
759 break;
760 case tok::annot_pragma_fp_contract:
761 HandlePragmaFPContract();
762 break;
763 default:
764 checkForPragmas = false;
765 break;
766 }
767 }
768
769}
770
Reid Spencer5f016e22007-07-11 17:01:13 +0000771/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff1b273c42007-09-16 14:56:35 +0000772/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Reid Spencer5f016e22007-07-11 17:01:13 +0000773/// consume the '}' at the end of the block. It does not manipulate the scope
774/// stack.
John McCall60d7b3a2010-08-24 06:29:42 +0000775StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump1eb44332009-09-09 15:08:12 +0000776 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerae50fa02009-03-05 00:00:31 +0000777 Tok.getLocation(),
778 "in compound statement ('{}')");
Lang Hamesbe9af122012-10-02 04:45:10 +0000779
780 // Record the state of the FP_CONTRACT pragma, restore on leaving the
781 // compound statement.
782 Sema::FPContractStateRAII SaveFPContractState(Actions);
783
Douglas Gregor0fbda682010-09-15 14:51:05 +0000784 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000785 BalancedDelimiterTracker T(*this, tok::l_brace);
786 if (T.consumeOpen())
787 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000788
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000789 Sema::CompoundScopeRAII CompoundScope(Actions);
790
Lang Hamesa60d21d2012-11-03 22:29:05 +0000791 // Parse any pragmas at the beginning of the compound statement.
792 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000793
Lang Hamesa60d21d2012-11-03 22:29:05 +0000794 StmtVector Stmts;
Lang Hames860022c2012-10-21 01:10:01 +0000795
Chris Lattner4ae493c2011-02-18 02:08:43 +0000796 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
797 // only allowed at the start of a compound stmt regardless of the language.
798 while (Tok.is(tok::kw___label__)) {
799 SourceLocation LabelLoc = ConsumeToken();
800 Diag(LabelLoc, diag::ext_gnu_local_label);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000801
Chris Lattner5f9e2722011-07-23 10:55:15 +0000802 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000803 while (1) {
804 if (Tok.isNot(tok::identifier)) {
805 Diag(Tok, diag::err_expected_ident);
806 break;
807 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000808
Chris Lattner4ae493c2011-02-18 02:08:43 +0000809 IdentifierInfo *II = Tok.getIdentifierInfo();
810 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara67843042011-03-05 18:21:20 +0000811 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000812
Chris Lattner4ae493c2011-02-18 02:08:43 +0000813 if (!Tok.is(tok::comma))
814 break;
815 ConsumeToken();
816 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000817
John McCall0b7e6782011-03-24 11:26:52 +0000818 DeclSpec DS(AttrFactory);
Rafael Espindola4549d7f2013-07-09 12:05:01 +0000819 DeclGroupPtrTy Res =
820 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000821 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000822
Chris Lattner8bb21d32012-04-28 16:12:17 +0000823 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000824 if (R.isUsable())
825 Stmts.push_back(R.release());
826 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000827
Chris Lattner4ae493c2011-02-18 02:08:43 +0000828 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000829 if (Tok.is(tok::annot_pragma_unused)) {
830 HandlePragmaUnused();
831 continue;
832 }
833
David Blaikie4e4d0842012-03-11 07:00:24 +0000834 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet1e862692011-05-06 20:48:22 +0000835 Tok.is(tok::kw___if_not_exists))) {
836 ParseMicrosoftIfExistsStatement(Stmts);
837 continue;
838 }
839
John McCall60d7b3a2010-08-24 06:29:42 +0000840 StmtResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000841 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000842 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattner45a566c2007-08-27 01:01:57 +0000843 } else {
844 // __extension__ can start declarations and it can also be a unary
845 // operator for expressions. Consume multiple __extension__ markers here
846 // until we can determine which is which.
Eli Friedmanadf077f2009-01-27 08:43:38 +0000847 // FIXME: This loses extension expressions in the AST!
Chris Lattner45a566c2007-08-27 01:01:57 +0000848 SourceLocation ExtLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000849 while (Tok.is(tok::kw___extension__))
Chris Lattner45a566c2007-08-27 01:01:57 +0000850 ConsumeToken();
Chris Lattner39146d62008-10-20 06:51:33 +0000851
John McCall0b7e6782011-03-24 11:26:52 +0000852 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +0000853 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000854
Chris Lattner45a566c2007-08-27 01:01:57 +0000855 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis5404a152008-10-05 00:06:24 +0000856 if (isDeclarationStatement()) {
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000857 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner97144fc2009-04-02 04:16:50 +0000858 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000859 ExtensionRAIIObject O(Diags);
860
Chris Lattner97144fc2009-04-02 04:16:50 +0000861 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000862 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
863 Declarator::BlockContext, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000864 attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000865 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattner45a566c2007-08-27 01:01:57 +0000866 } else {
Eli Friedmanadf077f2009-01-27 08:43:38 +0000867 // Otherwise this was a unary __extension__ marker.
John McCall60d7b3a2010-08-24 06:29:42 +0000868 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattner043a0b52008-03-13 06:32:11 +0000869
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000870 if (Res.isInvalid()) {
Chris Lattner45a566c2007-08-27 01:01:57 +0000871 SkipUntil(tok::semi);
872 continue;
873 }
Sebastian Redlf512e822009-01-18 18:03:53 +0000874
Sean Huntbbd37c62009-11-21 08:43:09 +0000875 // FIXME: Use attributes?
Chris Lattner39146d62008-10-20 06:51:33 +0000876 // Eat the semicolon at the end of stmt and convert the expr into a
877 // statement.
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000878 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000879 R = Actions.ActOnExprStmt(Res);
Chris Lattner45a566c2007-08-27 01:01:57 +0000880 }
881 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000882
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000883 if (R.isUsable())
Sebastian Redleffa8d12008-12-10 00:02:53 +0000884 Stmts.push_back(R.release());
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000886
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000887 SourceLocation CloseLoc = Tok.getLocation();
888
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 // We broke out of the while loop because we found a '}' or EOF.
Nico Weberd11f4352012-12-30 23:36:56 +0000890 if (!T.consumeClose())
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000891 // Recover by creating a compound statement with what we parsed so far,
892 // instead of dropping everything and returning StmtError();
Nico Weberd11f4352012-12-30 23:36:56 +0000893 CloseLoc = T.getCloseLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000894
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000895 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000896 Stmts, isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000897}
898
Chris Lattner15ff1112008-12-12 06:31:07 +0000899/// ParseParenExprOrCondition:
900/// [C ] '(' expression ')'
Chris Lattnerff871fb2008-12-12 06:35:28 +0000901/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattner15ff1112008-12-12 06:31:07 +0000902///
903/// This function parses and performs error recovery on the specified condition
904/// or expression (depending on whether we're in C++ or C mode). This function
905/// goes out of its way to recover well. It returns true if there was a parser
906/// error (the right paren couldn't be found), which indicates that the caller
907/// should try to recover harder. It returns false if the condition is
908/// successfully parsed. Note that a successful parse can still have semantic
909/// errors in the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000910bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCalld226f652010-08-21 09:40:31 +0000911 Decl *&DeclResult,
Douglas Gregor586596f2010-05-06 17:25:47 +0000912 SourceLocation Loc,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000913 bool ConvertToBoolean) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000914 BalancedDelimiterTracker T(*this, tok::l_paren);
915 T.consumeOpen();
916
David Blaikie4e4d0842012-03-11 07:00:24 +0000917 if (getLangOpts().CPlusPlus)
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000918 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000919 else {
920 ExprResult = ParseExpression();
John McCalld226f652010-08-21 09:40:31 +0000921 DeclResult = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000922
Douglas Gregor586596f2010-05-06 17:25:47 +0000923 // If required, convert to a boolean value.
924 if (!ExprResult.isInvalid() && ConvertToBoolean)
925 ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000926 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000927 }
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Chris Lattner15ff1112008-12-12 06:31:07 +0000929 // If the parser was confused by the condition and we don't have a ')', try to
930 // recover by skipping ahead to a semi and bailing out. If condexp is
931 // semantically invalid but we have well formed code, keep going.
John McCalld226f652010-08-21 09:40:31 +0000932 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattner15ff1112008-12-12 06:31:07 +0000933 SkipUntil(tok::semi);
934 // Skipping may have stopped if it found the containing ')'. If so, we can
935 // continue parsing the if statement.
936 if (Tok.isNot(tok::r_paren))
937 return true;
938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner15ff1112008-12-12 06:31:07 +0000940 // Otherwise the condition is valid or the rparen is present.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000941 T.consumeClose();
Chad Rosierb6604462012-07-10 21:35:27 +0000942
Chris Lattnerbddc7e52012-04-28 16:24:20 +0000943 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
944 // that all callers are looking for a statement after the condition, so ")"
945 // isn't valid.
946 while (Tok.is(tok::r_paren)) {
947 Diag(Tok, diag::err_extraneous_rparen_in_condition)
948 << FixItHint::CreateRemoval(Tok.getLocation());
949 ConsumeParen();
950 }
Chad Rosierb6604462012-07-10 21:35:27 +0000951
Chris Lattner15ff1112008-12-12 06:31:07 +0000952 return false;
953}
954
955
Reid Spencer5f016e22007-07-11 17:01:13 +0000956/// ParseIfStatement
957/// if-statement: [C99 6.8.4.1]
958/// 'if' '(' expression ')' statement
959/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000960/// [C++] 'if' '(' condition ')' statement
961/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +0000962///
Richard Smith534986f2012-04-14 00:33:13 +0000963StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000964 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
966
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000967 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +0000968 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000970 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +0000972
David Blaikie4e4d0842012-03-11 07:00:24 +0000973 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000974
Chris Lattner22153252007-08-26 23:08:06 +0000975 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
976 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000977 //
978 // C++ 6.4p3:
979 // A name introduced by a declaration in a condition is in scope from its
980 // point of declaration until the end of the substatements controlled by the
981 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +0000982 // C++ 3.3.2p4:
983 // Names declared in the for-init-statement, and in the condition of if,
984 // while, for, and switch statements are local to the if, while, for, or
985 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +0000986 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +0000987 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +0000988
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000990 ExprResult CondExp;
John McCalld226f652010-08-21 09:40:31 +0000991 Decl *CondVar = 0;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000992 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +0000993 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +0000994
David Blaikiedef07622012-05-16 04:20:04 +0000995 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chris Lattner0ecea032007-08-22 05:28:50 +0000997 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +0000998 // there is no compound stmt. C90 does not have this clause. We only do this
999 // if the body isn't a compound statement to avoid push/pop in common 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 //
1005 // For C++ we create a scope for the condition and a new scope for
1006 // substatements because:
1007 // -When the 'then' scope exits, we want the condition declaration to still be
1008 // active for the 'else' scope too.
1009 // -Sema will detect name clashes by considering declarations of a
1010 // 'ControlScope' as part of its direct subscope.
1011 // -If we wanted the condition and substatement to be in the same scope, we
1012 // would have to notify ParseStatement not to create a new scope. It's
1013 // simpler to let it create a new scope.
1014 //
Mike Stump1eb44332009-09-09 15:08:12 +00001015 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001016 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001017
Chris Lattnerb96728d2007-10-29 05:08:52 +00001018 // Read the 'then' stmt.
1019 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +00001020
1021 SourceLocation InnerStatementTrailingElseLoc;
1022 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001023
Chris Lattnera36ce712007-08-22 05:16:28 +00001024 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001025 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001026
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 // If it has an else, parse it.
1028 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +00001029 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +00001030 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001031
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001032 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +00001033 if (TrailingElseLoc)
1034 *TrailingElseLoc = Tok.getLocation();
1035
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +00001037 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001038
Chris Lattner0ecea032007-08-22 05:28:50 +00001039 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001040 // there is no compound stmt. C90 does not have this clause. We only do
1041 // this if the body isn't a compound statement to avoid push/pop in common
1042 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001043 //
1044 // C++ 6.4p1:
1045 // The substatement in a selection-statement (each substatement, in the else
1046 // form of the if statement) implicitly defines a local scope.
1047 //
Sebastian Redl61364dd2008-12-11 19:30:53 +00001048 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001049 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001050
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001052
Chris Lattnera36ce712007-08-22 05:16:28 +00001053 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001054 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +00001055 } else if (Tok.is(tok::code_completion)) {
1056 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001057 cutOffParsing();
1058 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +00001059 } else if (InnerStatementTrailingElseLoc.isValid()) {
1060 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001062
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001063 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Chris Lattnerb96728d2007-10-29 05:08:52 +00001065 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +00001066 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +00001067 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001068 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1069 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1070 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +00001071 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +00001072 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +00001073 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001074
Chris Lattnerb96728d2007-10-29 05:08:52 +00001075 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001076 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001077 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001078 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001079 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001080
John McCall9ae2f072010-08-23 23:25:46 +00001081 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001082 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001083}
1084
1085/// ParseSwitchStatement
1086/// switch-statement:
1087/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001088/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001089StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001090 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1092
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001093 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001094 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001096 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 }
Chris Lattner22153252007-08-26 23:08:06 +00001098
David Blaikie4e4d0842012-03-11 07:00:24 +00001099 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001100
Chris Lattner22153252007-08-26 23:08:06 +00001101 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1102 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001103 //
1104 // C++ 6.4p3:
1105 // A name introduced by a declaration in a condition is in scope from its
1106 // point of declaration until the end of the substatements controlled by the
1107 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001108 // C++ 3.3.2p4:
1109 // Names declared in the for-init-statement, and in the condition of if,
1110 // while, for, and switch statements are local to the if, while, for, or
1111 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001112 //
Richard Trieubb9b80c2011-04-21 21:44:26 +00001113 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001114 if (C99orCXX)
1115 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001116 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001117
1118 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001119 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001120 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001121 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001122 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001123
John McCall60d7b3a2010-08-24 06:29:42 +00001124 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001125 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001126
Douglas Gregor586596f2010-05-06 17:25:47 +00001127 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001128 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001129 // FIXME: This is not optimal recovery, but parsing the body is more
1130 // dangerous due to the presence of case and default statements, which
1131 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001132 if (Tok.is(tok::l_brace)) {
1133 ConsumeBrace();
1134 SkipUntil(tok::r_brace, false, false);
1135 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001136 SkipUntil(tok::semi);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001137 return Switch;
Douglas Gregor586596f2010-05-06 17:25:47 +00001138 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001139
Chris Lattner0ecea032007-08-22 05:28:50 +00001140 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001141 // there is no compound stmt. C90 does not have this clause. We only do this
1142 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001143 //
1144 // C++ 6.4p1:
1145 // The substatement in a selection-statement (each substatement, in the else
1146 // form of the if statement) implicitly defines a local scope.
1147 //
1148 // See comments in ParseIfStatement for why we create a scope for the
1149 // condition and a new scope for substatement in C++.
1150 //
Mike Stump1eb44332009-09-09 15:08:12 +00001151 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001152 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001153
Reid Spencer5f016e22007-07-11 17:01:13 +00001154 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001155 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001156
Chris Lattner7e52de42010-01-24 01:50:29 +00001157 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001158 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001159 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001160
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001161 if (Body.isInvalid()) {
Chris Lattner7e52de42010-01-24 01:50:29 +00001162 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001163
1164 // Put the synthesized null statement on the same line as the end of switch
1165 // condition.
1166 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1167 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1168 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001169
John McCall9ae2f072010-08-23 23:25:46 +00001170 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001171}
1172
1173/// ParseWhileStatement
1174/// while-statement: [C99 6.8.5.1]
1175/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001176/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001177StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001178 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 SourceLocation WhileLoc = Tok.getLocation();
1180 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001181
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001182 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001183 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001185 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001187
David Blaikie4e4d0842012-03-11 07:00:24 +00001188 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001189
Chris Lattner22153252007-08-26 23:08:06 +00001190 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1191 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001192 //
1193 // C++ 6.4p3:
1194 // A name introduced by a declaration in a condition is in scope from its
1195 // point of declaration until the end of the substatements controlled by the
1196 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001197 // C++ 3.3.2p4:
1198 // Names declared in the for-init-statement, and in the condition of if,
1199 // while, for, and switch statements are local to the if, while, for, or
1200 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001201 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001202 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001203 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001204 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1205 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001206 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001207 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1208 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001209
1210 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001211 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001212 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001213 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001214 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001215
David Blaikiedef07622012-05-16 04:20:04 +00001216 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Chris Lattner0ecea032007-08-22 05:28:50 +00001218 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001219 // there is no compound stmt. C90 does not have this clause. We only do this
1220 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001221 //
1222 // C++ 6.5p2:
1223 // The substatement in an iteration-statement implicitly defines a local scope
1224 // which is entered and exited each time through the loop.
1225 //
1226 // See comments in ParseIfStatement for why we create a scope for the
1227 // condition and a new scope for substatement in C++.
1228 //
Mike Stump1eb44332009-09-09 15:08:12 +00001229 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001230 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001231
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001233 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001234
Chris Lattner0ecea032007-08-22 05:28:50 +00001235 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001236 InnerScope.Exit();
1237 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001238
John McCalld226f652010-08-21 09:40:31 +00001239 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001240 return StmtError();
1241
John McCall9ae2f072010-08-23 23:25:46 +00001242 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001243}
1244
1245/// ParseDoStatement
1246/// do-statement: [C99 6.8.5.2]
1247/// 'do' statement 'while' '(' expression ')' ';'
1248/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001249StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001250 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001252
Chris Lattner22153252007-08-26 23:08:06 +00001253 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1254 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001255 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001256 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001257 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001258 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001259 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001260
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001261 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001262
Chris Lattner0ecea032007-08-22 05:28:50 +00001263 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001264 // there is no compound stmt. C90 does not have this clause. We only do this
1265 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001266 //
1267 // C++ 6.5p2:
1268 // The substatement in an iteration-statement implicitly defines a local scope
1269 // which is entered and exited each time through the loop.
1270 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001271 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikie4e4d0842012-03-11 07:00:24 +00001272 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001273 Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001274
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001276 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001277
Chris Lattner0ecea032007-08-22 05:28:50 +00001278 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001279 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001280
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001281 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001282 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001283 Diag(Tok, diag::err_expected_while);
Chris Lattner28eb7e92008-11-23 23:17:07 +00001284 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner19504402008-11-13 18:52:53 +00001285 SkipUntil(tok::semi, false, true);
1286 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001287 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 }
1289 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001290
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001291 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001292 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner19504402008-11-13 18:52:53 +00001293 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001294 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001296
Chris Lattnerff871fb2008-12-12 06:35:28 +00001297 // Parse the parenthesized condition.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001298 BalancedDelimiterTracker T(*this, tok::l_paren);
1299 T.consumeOpen();
Chad Rosierb6604462012-07-10 21:35:27 +00001300
Sean Hunt2edf0a22012-06-23 05:07:58 +00001301 // FIXME: Do not just parse the attribute contents and throw them away
1302 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001303 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001304 ProhibitAttributes(attrs);
1305
John McCall60d7b3a2010-08-24 06:29:42 +00001306 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001307 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001308 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001309
Sebastian Redl9a920342008-12-11 19:48:14 +00001310 if (Cond.isInvalid() || Body.isInvalid())
1311 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001312
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001313 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1314 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001315}
1316
1317/// ParseForStatement
1318/// for-statement: [C99 6.8.5.3]
1319/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1320/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001321/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1322/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001323/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001324/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1325/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001326///
1327/// [C++] for-init-statement:
1328/// [C++] expression-statement
1329/// [C++] simple-declaration
1330///
Richard Smithad762fc2011-04-14 22:09:26 +00001331/// [C++0x] for-range-declaration:
1332/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1333/// [C++0x] for-range-initializer:
1334/// [C++0x] expression
1335/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001336StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001337 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001339
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001340 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001341 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001343 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001345
Chad Rosierb6604462012-07-10 21:35:27 +00001346 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1347 getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001348
Chris Lattner22153252007-08-26 23:08:06 +00001349 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1350 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001351 //
1352 // C++ 6.4p3:
1353 // A name introduced by a declaration in a condition is in scope from its
1354 // point of declaration until the end of the substatements controlled by the
1355 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001356 // C++ 3.3.2p4:
1357 // Names declared in the for-init-statement, and in the condition of if,
1358 // while, for, and switch statements are local to the if, while, for, or
1359 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001360 // C++ 6.5.3p1:
1361 // Names declared in the for-init-statement are in the same declarative-region
1362 // as those declared in the condition.
1363 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001364 unsigned ScopeFlags;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001365 if (C99orCXXorObjC)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001366 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1367 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001368 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001369 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1370
1371 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001372
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001373 BalancedDelimiterTracker T(*this, tok::l_paren);
1374 T.consumeOpen();
1375
John McCall60d7b3a2010-08-24 06:29:42 +00001376 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001377
Richard Smithad762fc2011-04-14 22:09:26 +00001378 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001379 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001380 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001381 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001382 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001383 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001384 FullExprArg ThirdPart(Actions);
John McCalld226f652010-08-21 09:40:31 +00001385 Decl *SecondVar = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001386
Douglas Gregor791215b2009-09-21 20:51:25 +00001387 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001388 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001389 C99orCXXorObjC? Sema::PCC_ForInit
1390 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001391 cutOffParsing();
1392 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001393 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001394
Sean Hunt2edf0a22012-06-23 05:07:58 +00001395 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001396 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001397
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001399 if (Tok.is(tok::semi)) { // for (;
Sean Hunt2edf0a22012-06-23 05:07:58 +00001400 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 // no first part, eat the ';'.
1402 ConsumeToken();
Eli Friedman9490ab42011-12-20 01:50:37 +00001403 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001405 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001407
Richard Smithad762fc2011-04-14 22:09:26 +00001408 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001409 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001410 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1411
Chris Lattner97144fc2009-04-02 04:16:50 +00001412 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001413 StmtVector Stmts;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001414 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smithad762fc2011-04-14 22:09:26 +00001415 DeclEnd, attrs, false,
1416 MightBeForRangeStmt ?
1417 &ForRangeInit : 0);
Chris Lattnercd147752009-03-29 17:27:48 +00001418 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Richard Smithad762fc2011-04-14 22:09:26 +00001420 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001421 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001422 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001423
Richard Smithad762fc2011-04-14 22:09:26 +00001424 ForRange = true;
1425 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001426 ConsumeToken();
1427 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001428 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001429 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001430 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001431
Douglas Gregorfb629412010-08-23 21:17:50 +00001432 if (Tok.is(tok::code_completion)) {
1433 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001434 cutOffParsing();
1435 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001436 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001437 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001438 } else {
1439 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001440 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 } else {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001442 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001443 Value = ParseExpression();
1444
John McCallf6a16482010-12-04 03:47:34 +00001445 ForEach = isTokIdentifier_in();
1446
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001448 if (!Value.isInvalid()) {
1449 if (ForEach)
1450 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1451 else
Richard Smith41956372013-01-14 22:39:08 +00001452 FirstPart = Actions.ActOnExprStmt(Value);
John McCallf6a16482010-12-04 03:47:34 +00001453 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001454
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001455 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001457 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001458 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001459
Douglas Gregorfb629412010-08-23 21:17:50 +00001460 if (Tok.is(tok::code_completion)) {
1461 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001462 cutOffParsing();
1463 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001464 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001465 Collection = ParseExpression();
Richard Smith80ad52f2013-01-02 11:42:31 +00001466 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001467 // User tried to write the reasonable, but ill-formed, for-range-statement
1468 // for (expr : expr) { ... }
1469 Diag(Tok, diag::err_for_range_expected_decl)
1470 << FirstPart.get()->getSourceRange();
1471 SkipUntil(tok::r_paren, false, true);
1472 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001473 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001474 if (!Value.isInvalid()) {
1475 Diag(Tok, diag::err_expected_semi_for);
1476 } else {
1477 // Skip until semicolon or rparen, don't consume it.
1478 SkipUntil(tok::r_paren, true, true);
1479 if (Tok.is(tok::semi))
1480 ConsumeToken();
1481 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 }
1483 }
Richard Smithad762fc2011-04-14 22:09:26 +00001484 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001485 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001486 // Parse the second part of the for specifier.
1487 if (Tok.is(tok::semi)) { // for (...;;
1488 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001489 } else if (Tok.is(tok::r_paren)) {
1490 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001491 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001492 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001493 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001494 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1495 else {
1496 Second = ParseExpression();
1497 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001498 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001499 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001500 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001501 SecondPartIsInvalid = Second.isInvalid();
David Blaikiedef07622012-05-16 04:20:04 +00001502 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001503 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001504
Douglas Gregorb72c7782011-02-17 03:38:46 +00001505 if (Tok.isNot(tok::semi)) {
1506 if (!SecondPartIsInvalid || SecondVar)
1507 Diag(Tok, diag::err_expected_semi_for);
1508 else
1509 // Skip until semicolon or rparen, don't consume it.
1510 SkipUntil(tok::r_paren, true, true);
1511 }
1512
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001513 if (Tok.is(tok::semi)) {
1514 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001515 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001516
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001517 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001518 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001519 ExprResult Third = ParseExpression();
Richard Smith41956372013-01-14 22:39:08 +00001520 // FIXME: The C++11 standard doesn't actually say that this is a
1521 // discarded-value expression, but it clearly should be.
1522 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregor586596f2010-05-06 17:25:47 +00001523 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001526 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001527
Richard Smithad762fc2011-04-14 22:09:26 +00001528 // We need to perform most of the semantic analysis for a C++0x for-range
1529 // statememt before parsing the body, in order to be able to deduce the type
1530 // of an auto-typed loop variable.
1531 StmtResult ForRangeStmt;
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001532 StmtResult ForEachStmt;
Chad Rosierb6604462012-07-10 21:35:27 +00001533
John McCall990567c2011-07-27 01:07:15 +00001534 if (ForRange) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001535 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smithad762fc2011-04-14 22:09:26 +00001536 ForRangeInit.ColonLoc,
1537 ForRangeInit.RangeExpr.get(),
Richard Smith8b533d92012-09-20 21:52:32 +00001538 T.getCloseLocation(),
1539 Sema::BFRK_Build);
Richard Smithad762fc2011-04-14 22:09:26 +00001540
John McCall990567c2011-07-27 01:07:15 +00001541
1542 // Similarly, we need to do the semantic analysis for a for-range
1543 // statement immediately in order to close over temporaries correctly.
1544 } else if (ForEach) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001545 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001546 FirstPart.take(),
Chad Rosierb6604462012-07-10 21:35:27 +00001547 Collection.take(),
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001548 T.getCloseLocation());
John McCall990567c2011-07-27 01:07:15 +00001549 }
1550
Chris Lattner0ecea032007-08-22 05:28:50 +00001551 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001552 // there is no compound stmt. C90 does not have this clause. We only do this
1553 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001554 //
1555 // C++ 6.5p2:
1556 // The substatement in an iteration-statement implicitly defines a local scope
1557 // which is entered and exited each time through the loop.
1558 //
1559 // See comments in ParseIfStatement for why we create a scope for
1560 // for-init-statement/condition and a new scope for substatement in C++.
1561 //
Mike Stump1eb44332009-09-09 15:08:12 +00001562 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001563 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001566 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001567
Chris Lattner0ecea032007-08-22 05:28:50 +00001568 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001569 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001572 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001573
1574 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001575 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001576
Richard Smithad762fc2011-04-14 22:09:26 +00001577 if (ForEach)
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001578 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1579 Body.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Richard Smithad762fc2011-04-14 22:09:26 +00001581 if (ForRange)
1582 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1583
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001584 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1585 SecondPart, SecondVar, ThirdPart,
1586 T.getCloseLocation(), Body.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001587}
1588
1589/// ParseGotoStatement
1590/// jump-statement:
1591/// 'goto' identifier ';'
1592/// [GNU] 'goto' '*' expression ';'
1593///
1594/// Note: this lets the caller parse the end ';'.
1595///
Richard Smith534986f2012-04-14 00:33:13 +00001596StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001597 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001599
John McCall60d7b3a2010-08-24 06:29:42 +00001600 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001601 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001602 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1603 Tok.getLocation());
1604 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001606 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 // GNU indirect goto extension.
1608 Diag(Tok, diag::ext_gnu_indirect_goto);
1609 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001610 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001611 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001613 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 }
John McCall9ae2f072010-08-23 23:25:46 +00001615 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattner95cfb852007-07-22 04:13:33 +00001616 } else {
1617 Diag(Tok, diag::err_expected_ident);
Sebastian Redl9a920342008-12-11 19:48:14 +00001618 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001620
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001621 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +00001622}
1623
1624/// ParseContinueStatement
1625/// jump-statement:
1626/// 'continue' ';'
1627///
1628/// Note: this lets the caller parse the end ';'.
1629///
Richard Smith534986f2012-04-14 00:33:13 +00001630StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001632 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001633}
1634
1635/// ParseBreakStatement
1636/// jump-statement:
1637/// 'break' ';'
1638///
1639/// Note: this lets the caller parse the end ';'.
1640///
Richard Smith534986f2012-04-14 00:33:13 +00001641StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001643 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001644}
1645
1646/// ParseReturnStatement
1647/// jump-statement:
1648/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001649StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001650 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001652
John McCall60d7b3a2010-08-24 06:29:42 +00001653 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001654 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001655 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001656 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001657 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001658 return StmtError();
1659 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001660
David Blaikie4e4d0842012-03-11 07:00:24 +00001661 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001662 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001663 if (R.isUsable())
Richard Smith80ad52f2013-01-02 11:42:31 +00001664 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001665 diag::warn_cxx98_compat_generalized_initializer_lists :
1666 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001667 << R.get()->getSourceRange();
1668 } else
1669 R = ParseExpression();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001670 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001672 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 }
1674 }
John McCall9ae2f072010-08-23 23:25:46 +00001675 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001676}
1677
John McCallaeeacf72013-05-03 00:10:13 +00001678namespace {
1679 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1680 Parser &TheParser;
1681 SourceLocation AsmLoc;
1682 StringRef AsmString;
1683
1684 /// The tokens we streamed into AsmString and handed off to MC.
1685 ArrayRef<Token> AsmToks;
1686
1687 /// The offset of each token in AsmToks within AsmString.
1688 ArrayRef<unsigned> AsmTokOffsets;
1689
1690 public:
1691 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1692 StringRef AsmString,
1693 ArrayRef<Token> Toks,
1694 ArrayRef<unsigned> Offsets)
1695 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1696 AsmToks(Toks), AsmTokOffsets(Offsets) {
1697 assert(AsmToks.size() == AsmTokOffsets.size());
1698 }
1699
1700 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1701 InlineAsmIdentifierInfo &Info,
1702 bool IsUnevaluatedContext) {
1703 // Collect the desired tokens.
1704 SmallVector<Token, 16> LineToks;
1705 const Token *FirstOrigToken = 0;
1706 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1707
1708 unsigned NumConsumedToks;
1709 ExprResult Result =
1710 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1711 IsUnevaluatedContext);
1712
1713 // If we consumed the entire line, tell MC that.
1714 // Also do this if we consumed nothing as a way of reporting failure.
1715 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1716 // By not modifying LineBuf, we're implicitly consuming it all.
1717
1718 // Otherwise, consume up to the original tokens.
1719 } else {
1720 assert(FirstOrigToken && "not using original tokens?");
1721
1722 // Since we're using original tokens, apply that offset.
1723 assert(FirstOrigToken[NumConsumedToks].getLocation()
1724 == LineToks[NumConsumedToks].getLocation());
1725 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1726 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1727
1728 // The total length we've consumed is the relative offset
1729 // of the last token we consumed plus its length.
1730 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1731 + AsmToks[LastIndex].getLength()
1732 - AsmTokOffsets[FirstIndex]);
1733 LineBuf = LineBuf.substr(0, TotalOffset);
1734 }
1735
1736 // Initialize the "decl" with the lookup result.
1737 Info.OpDecl = static_cast<void*>(Result.take());
1738 return Info.OpDecl;
1739 }
1740
1741 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1742 unsigned &Offset) {
1743 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1744 Offset, AsmLoc);
1745 }
1746
1747 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1748 void *Context) {
1749 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1750 }
1751
1752 private:
1753 /// Collect the appropriate tokens for the given string.
1754 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1755 const Token *&FirstOrigToken) const {
1756 // For now, assert that the string we're working with is a substring
1757 // of what we gave to MC. This lets us use the original tokens.
1758 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1759 !std::less<const char*>()(AsmString.end(), Str.end()));
1760
1761 // Try to find a token whose offset matches the first token.
1762 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1763 const unsigned *FirstTokOffset
1764 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1765 FirstCharOffset);
1766
1767 // For now, assert that the start of the string exactly
1768 // corresponds to the start of a token.
1769 assert(*FirstTokOffset == FirstCharOffset);
1770
1771 // Use all the original tokens for this line. (We assume the
1772 // end of the line corresponds cleanly to a token break.)
1773 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1774 FirstOrigToken = &AsmToks[FirstTokIndex];
1775 unsigned LastCharOffset = Str.end() - AsmString.begin();
1776 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1777 if (AsmTokOffsets[i] >= LastCharOffset) break;
1778 TempToks.push_back(AsmToks[i]);
1779 }
1780 }
1781
1782 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1783 // Compute an offset into the inline asm buffer.
1784 // FIXME: This isn't right if .macro is involved (but hopefully, no
1785 // real-world code does that).
1786 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1787 const llvm::MemoryBuffer *LBuf =
1788 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1789 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1790
1791 // Figure out which token that offset points into.
1792 const unsigned *TokOffsetPtr =
1793 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1794 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1795 unsigned TokOffset = *TokOffsetPtr;
1796
1797 // If we come up with an answer which seems sane, use it; otherwise,
1798 // just point at the __asm keyword.
1799 // FIXME: Assert the answer is sane once we handle .macro correctly.
1800 SourceLocation Loc = AsmLoc;
1801 if (TokIndex < AsmToks.size()) {
1802 const Token &Tok = AsmToks[TokIndex];
1803 Loc = Tok.getLocation();
1804 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1805 }
1806 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1807 << D.getMessage();
1808 }
1809 };
1810}
1811
1812/// Parse an identifier in an MS-style inline assembly block.
1813///
1814/// \param CastInfo - a void* so that we don't have to teach Parser.h
1815/// about the actual type.
1816ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1817 unsigned &NumLineToksConsumed,
1818 void *CastInfo,
1819 bool IsUnevaluatedContext) {
1820 llvm::InlineAsmIdentifierInfo &Info =
1821 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1822
1823 // Push a fake token on the end so that we don't overrun the token
1824 // stream. We use ';' because it expression-parsing should never
1825 // overrun it.
1826 const tok::TokenKind EndOfStream = tok::semi;
1827 Token EndOfStreamTok;
1828 EndOfStreamTok.startToken();
1829 EndOfStreamTok.setKind(EndOfStream);
1830 LineToks.push_back(EndOfStreamTok);
1831
1832 // Also copy the current token over.
1833 LineToks.push_back(Tok);
1834
1835 PP.EnterTokenStream(LineToks.begin(),
1836 LineToks.size(),
1837 /*disable macros*/ true,
1838 /*owns tokens*/ false);
1839
1840 // Clear the current token and advance to the first token in LineToks.
1841 ConsumeAnyToken();
1842
1843 // Parse an optional scope-specifier if we're in C++.
1844 CXXScopeSpec SS;
1845 if (getLangOpts().CPlusPlus) {
1846 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1847 }
1848
1849 // Require an identifier here.
1850 SourceLocation TemplateKWLoc;
1851 UnqualifiedId Id;
1852 bool Invalid = ParseUnqualifiedId(SS,
1853 /*EnteringContext=*/false,
1854 /*AllowDestructorName=*/false,
1855 /*AllowConstructorName=*/false,
1856 /*ObjectType=*/ ParsedType(),
1857 TemplateKWLoc,
1858 Id);
1859
1860 // If we've run into the poison token we inserted before, or there
1861 // was a parsing error, then claim the entire line.
1862 if (Invalid || Tok.is(EndOfStream)) {
1863 NumLineToksConsumed = LineToks.size() - 2;
1864
1865 // Otherwise, claim up to the start of the next token.
1866 } else {
1867 // Figure out how many tokens we are into LineToks.
1868 unsigned LineIndex = 0;
1869 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1870 LineIndex++;
1871 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1872 }
1873
1874 NumLineToksConsumed = LineIndex;
1875 }
1876
1877 // Finally, restore the old parsing state by consuming all the
1878 // tokens we staged before, implicitly killing off the
1879 // token-lexer we pushed.
1880 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1881 ConsumeAnyToken();
1882 }
1883 ConsumeToken(EndOfStream);
1884
1885 // Leave LineToks in its original state.
1886 LineToks.pop_back();
1887 LineToks.pop_back();
1888
1889 // Perform the lookup.
1890 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1891 IsUnevaluatedContext);
1892}
1893
1894/// Turn a sequence of our tokens back into a string that we can hand
1895/// to the MC asm parser.
1896static bool buildMSAsmString(Preprocessor &PP,
1897 SourceLocation AsmLoc,
1898 ArrayRef<Token> AsmToks,
1899 SmallVectorImpl<unsigned> &TokOffsets,
1900 SmallString<512> &Asm) {
1901 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1902
1903 // Is this the start of a new assembly statement?
1904 bool isNewStatement = true;
1905
1906 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1907 const Token &Tok = AsmToks[i];
1908
1909 // Start each new statement with a newline and a tab.
1910 if (!isNewStatement &&
1911 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1912 Asm += "\n\t";
1913 isNewStatement = true;
1914 }
1915
1916 // Preserve the existence of leading whitespace except at the
1917 // start of a statement.
1918 if (!isNewStatement && Tok.hasLeadingSpace())
1919 Asm += ' ';
1920
1921 // Remember the offset of this token.
1922 TokOffsets.push_back(Asm.size());
1923
1924 // Don't actually write '__asm' into the assembly stream.
1925 if (Tok.is(tok::kw_asm)) {
1926 // Complain about __asm at the end of the stream.
1927 if (i + 1 == e) {
1928 PP.Diag(AsmLoc, diag::err_asm_empty);
1929 return true;
1930 }
1931
1932 continue;
1933 }
1934
1935 // Append the spelling of the token.
1936 SmallString<32> SpellingBuffer;
1937 bool SpellingInvalid = false;
1938 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
1939 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
1940
1941 // We are no longer at the start of a statement.
1942 isNewStatement = false;
1943 }
1944
1945 // Ensure that the buffer is null-terminated.
1946 Asm.push_back('\0');
1947 Asm.pop_back();
1948
1949 assert(TokOffsets.size() == AsmToks.size());
1950 return false;
1951}
1952
Eli Friedman3fedbe12011-09-30 01:13:51 +00001953/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1954/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier8cd64b42012-06-11 20:47:18 +00001955///
1956/// [MS] ms-asm-statement:
1957/// ms-asm-block
1958/// ms-asm-block ms-asm-statement
1959///
1960/// [MS] ms-asm-block:
1961/// '__asm' ms-asm-line '\n'
1962/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1963///
1964/// [MS] ms-asm-instruction-block
1965/// ms-asm-line
1966/// ms-asm-line '\n' ms-asm-instruction-block
1967///
Eli Friedman3fedbe12011-09-30 01:13:51 +00001968StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1969 SourceManager &SrcMgr = PP.getSourceManager();
1970 SourceLocation EndLoc = AsmLoc;
Chad Rosier8cd64b42012-06-11 20:47:18 +00001971 SmallVector<Token, 4> AsmToks;
Chad Rosier21ef7112012-08-14 19:22:06 +00001972
1973 bool InBraces = false;
1974 unsigned short savedBraceCount = 0;
1975 bool InAsmComment = false;
1976 FileID FID;
1977 unsigned LineNo = 0;
1978 unsigned NumTokensRead = 0;
1979 SourceLocation LBraceLoc;
1980
1981 if (Tok.is(tok::l_brace)) {
1982 // Braced inline asm: consume the opening brace.
1983 InBraces = true;
1984 savedBraceCount = BraceCount;
1985 EndLoc = LBraceLoc = ConsumeBrace();
1986 ++NumTokensRead;
1987 } else {
1988 // Single-line inline asm; compute which line it is on.
1989 std::pair<FileID, unsigned> ExpAsmLoc =
1990 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1991 FID = ExpAsmLoc.first;
1992 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1993 }
1994
1995 SourceLocation TokLoc = Tok.getLocation();
Eli Friedman3fedbe12011-09-30 01:13:51 +00001996 do {
Chad Rosier21ef7112012-08-14 19:22:06 +00001997 // If we hit EOF, we're done, period.
1998 if (Tok.is(tok::eof))
Eli Friedman3fedbe12011-09-30 01:13:51 +00001999 break;
Chad Rosier21ef7112012-08-14 19:22:06 +00002000
Chad Rosier21ef7112012-08-14 19:22:06 +00002001 if (!InAsmComment && Tok.is(tok::semi)) {
2002 // A semicolon in an asm is the start of a comment.
2003 InAsmComment = true;
2004 if (InBraces) {
2005 // Compute which line the comment is on.
2006 std::pair<FileID, unsigned> ExpSemiLoc =
2007 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2008 FID = ExpSemiLoc.first;
2009 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2010 }
2011 } else if (!InBraces || InAsmComment) {
2012 // If end-of-line is significant, check whether this token is on a
2013 // new line.
2014 std::pair<FileID, unsigned> ExpLoc =
2015 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2016 if (ExpLoc.first != FID ||
2017 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2018 // If this is a single-line __asm, we're done.
2019 if (!InBraces)
2020 break;
2021 // We're no longer in a comment.
2022 InAsmComment = false;
2023 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2024 // Single-line asm always ends when a closing brace is seen.
2025 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2026 // does MSVC do here?
2027 break;
2028 }
2029 }
2030 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2031 BraceCount == (savedBraceCount + 1)) {
2032 // Consume the closing brace, and finish
2033 EndLoc = ConsumeBrace();
2034 break;
2035 }
2036
2037 // Consume the next token; make sure we don't modify the brace count etc.
2038 // if we are in a comment.
2039 EndLoc = TokLoc;
2040 if (InAsmComment)
2041 PP.Lex(Tok);
2042 else {
2043 AsmToks.push_back(Tok);
2044 ConsumeAnyToken();
2045 }
2046 TokLoc = Tok.getLocation();
2047 ++NumTokensRead;
Eli Friedman3fedbe12011-09-30 01:13:51 +00002048 } while (1);
Chad Rosier8cd64b42012-06-11 20:47:18 +00002049
Chad Rosier21ef7112012-08-14 19:22:06 +00002050 if (InBraces && BraceCount != savedBraceCount) {
2051 // __asm without closing brace (this can happen at EOF).
2052 Diag(Tok, diag::err_expected_rbrace);
2053 Diag(LBraceLoc, diag::note_matching) << "{";
2054 return StmtError();
2055 } else if (NumTokensRead == 0) {
2056 // Empty __asm.
2057 Diag(Tok, diag::err_expected_lbrace);
2058 return StmtError();
2059 }
2060
John McCallaeeacf72013-05-03 00:10:13 +00002061 // Okay, prepare to use MC to parse the assembly.
2062 SmallVector<StringRef, 4> ConstraintRefs;
2063 SmallVector<Expr*, 4> Exprs;
2064 SmallVector<StringRef, 4> ClobberRefs;
2065
2066 // We need an actual supported target.
2067 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2068 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
2069 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2070 ArchTy != llvm::Triple::x86_64);
2071 if (UnsupportedArch)
2072 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
2073
2074 // If we don't support assembly, or the assembly is empty, we don't
2075 // need to instantiate the AsmParser, etc.
2076 if (UnsupportedArch || AsmToks.empty()) {
2077 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2078 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2079 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2080 }
2081
2082 // Expand the tokens into a string buffer.
2083 SmallString<512> AsmString;
2084 SmallVector<unsigned, 8> TokOffsets;
2085 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2086 return StmtError();
2087
2088 // Find the target and create the target specific parser.
2089 std::string Error;
2090 const std::string &TT = TheTriple.getTriple();
2091 const llvm::Target *TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2092
John McCallaeeacf72013-05-03 00:10:13 +00002093 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
Rafael Espindola1fcf31e2013-05-13 01:24:18 +00002094 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
John McCallaeeacf72013-05-03 00:10:13 +00002095 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2096 OwningPtr<llvm::MCSubtargetInfo>
2097 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2098
2099 llvm::SourceMgr TempSrcMgr;
Bill Wendling4b7bae32013-06-18 07:22:05 +00002100 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallaeeacf72013-05-03 00:10:13 +00002101 llvm::MemoryBuffer *Buffer =
2102 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2103
2104 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2105 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2106
2107 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2108 OwningPtr<llvm::MCAsmParser>
2109 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2110 OwningPtr<llvm::MCTargetAsmParser>
2111 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
2112
2113 // Get the instruction descriptor.
2114 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
2115 llvm::MCInstPrinter *IP =
2116 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2117
2118 // Change to the Intel dialect.
2119 Parser->setAssemblerDialect(1);
2120 Parser->setTargetParser(*TargetParser.get());
2121 Parser->setParsingInlineAsm(true);
2122 TargetParser->setParsingInlineAsm(true);
2123
2124 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2125 AsmToks, TokOffsets);
2126 TargetParser->setSemaCallback(&Callback);
2127 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2128 &Callback);
2129
2130 unsigned NumOutputs;
2131 unsigned NumInputs;
2132 std::string AsmStringIR;
2133 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2134 SmallVector<std::string, 4> Constraints;
2135 SmallVector<std::string, 4> Clobbers;
2136 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2137 NumOutputs, NumInputs, OpExprs, Constraints,
2138 Clobbers, MII, IP, Callback))
2139 return StmtError();
2140
2141 // Build the vector of clobber StringRefs.
2142 unsigned NumClobbers = Clobbers.size();
2143 ClobberRefs.resize(NumClobbers);
2144 for (unsigned i = 0; i != NumClobbers; ++i)
2145 ClobberRefs[i] = StringRef(Clobbers[i]);
2146
2147 // Recast the void pointers and build the vector of constraint StringRefs.
2148 unsigned NumExprs = NumOutputs + NumInputs;
2149 ConstraintRefs.resize(NumExprs);
2150 Exprs.resize(NumExprs);
2151 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2152 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2153 if (!OpExpr)
2154 return StmtError();
2155
2156 // Need address of variable.
2157 if (OpExprs[i].second)
2158 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2159 .take();
2160
2161 ConstraintRefs[i] = StringRef(Constraints[i]);
2162 Exprs[i] = OpExpr;
2163 }
2164
Chad Rosier8f726de2012-08-06 20:03:45 +00002165 // FIXME: We should be passing source locations for better diagnostics.
John McCallaeeacf72013-05-03 00:10:13 +00002166 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2167 NumOutputs, NumInputs,
2168 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00002169}
2170
Reid Spencer5f016e22007-07-11 17:01:13 +00002171/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff5f8aa692008-02-11 23:15:56 +00002172/// asm-statement:
2173/// gnu-asm-statement
2174/// ms-asm-statement
2175///
2176/// [GNU] gnu-asm-statement:
Reid Spencer5f016e22007-07-11 17:01:13 +00002177/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2178///
2179/// [GNU] asm-argument:
2180/// asm-string-literal
2181/// asm-string-literal ':' asm-operands[opt]
2182/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2183/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2184/// ':' asm-clobbers
2185///
2186/// [GNU] asm-clobbers:
2187/// asm-string-literal
2188/// asm-clobbers ',' asm-string-literal
2189///
John McCall60d7b3a2010-08-24 06:29:42 +00002190StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002191 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattnerfe795952007-10-29 04:04:16 +00002192 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00002193
Chad Rosier15490fd2012-12-05 21:08:21 +00002194 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosierb6604462012-07-10 21:35:27 +00002195 !isTypeQualifier()) {
Steve Naroffd62701b2008-02-07 03:50:06 +00002196 msAsm = true;
Eli Friedman3fedbe12011-09-30 01:13:51 +00002197 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00002198 }
John McCall0b7e6782011-03-24 11:26:52 +00002199 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 SourceLocation Loc = Tok.getLocation();
Sean Huntbbd37c62009-11-21 08:43:09 +00002201 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redl9a920342008-12-11 19:48:14 +00002202
Reid Spencer5f016e22007-07-11 17:01:13 +00002203 // GNU asms accept, but warn, about type-qualifiers other than volatile.
2204 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner1ab3b962008-11-18 07:48:38 +00002205 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Reid Spencer5f016e22007-07-11 17:01:13 +00002206 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner1ab3b962008-11-18 07:48:38 +00002207 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith4cf4a5e2013-03-28 01:55:44 +00002208 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2209 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2210 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redl9a920342008-12-11 19:48:14 +00002211
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 // Remember if this was a volatile asm.
Anders Carlsson39c47b52007-11-23 23:12:25 +00002213 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002214 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00002215 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +00002216 SkipUntil(tok::r_paren);
Sebastian Redl9a920342008-12-11 19:48:14 +00002217 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002219 BalancedDelimiterTracker T(*this, tok::l_paren);
2220 T.consumeOpen();
Sebastian Redl9a920342008-12-11 19:48:14 +00002221
John McCall60d7b3a2010-08-24 06:29:42 +00002222 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenek320fa4b2011-12-02 01:30:14 +00002223 if (AsmString.isInvalid()) {
Richard Smith99831e42012-03-06 03:21:47 +00002224 // Consume up to and including the closing paren.
2225 T.skipToEnd();
Sebastian Redl9a920342008-12-11 19:48:14 +00002226 return StmtError();
Ted Kremenek320fa4b2011-12-02 01:30:14 +00002227 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002228
Chris Lattner5f9e2722011-07-23 10:55:15 +00002229 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002230 ExprVector Constraints;
2231 ExprVector Exprs;
2232 ExprVector Clobbers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002233
Anders Carlssondfab34a2008-02-05 23:03:50 +00002234 if (Tok.is(tok::r_paren)) {
Chris Lattner64cb4752009-12-20 23:00:41 +00002235 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002236 T.consumeClose();
Chad Rosierdf5faf52012-08-25 00:11:56 +00002237 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2238 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2239 Constraints, Exprs, AsmString.take(),
2240 Clobbers, T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002242
Chris Lattner64cb4752009-12-20 23:00:41 +00002243 // Parse Outputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002244 bool AteExtraColon = false;
2245 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2246 // In C++ mode, parse "::" like ": :".
2247 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattner64cb4752009-12-20 23:00:41 +00002248 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002249
Chris Lattner64056462009-12-20 23:08:04 +00002250 if (!AteExtraColon &&
2251 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00002252 return StmtError();
2253 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002254
Chris Lattner64cb4752009-12-20 23:00:41 +00002255 unsigned NumOutputs = Names.size();
2256
2257 // Parse Inputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002258 if (AteExtraColon ||
2259 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2260 // In C++ mode, parse "::" like ": :".
2261 if (AteExtraColon)
2262 AteExtraColon = false;
2263 else {
2264 AteExtraColon = Tok.is(tok::coloncolon);
2265 ConsumeToken();
2266 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002267
Chris Lattner64056462009-12-20 23:08:04 +00002268 if (!AteExtraColon &&
2269 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00002270 return StmtError();
2271 }
2272
2273 assert(Names.size() == Constraints.size() &&
2274 Constraints.size() == Exprs.size() &&
2275 "Input operand size mismatch!");
2276
2277 unsigned NumInputs = Names.size() - NumOutputs;
2278
2279 // Parse the clobbers, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002280 if (AteExtraColon || Tok.is(tok::colon)) {
2281 if (!AteExtraColon)
2282 ConsumeToken();
Chris Lattner64cb4752009-12-20 23:00:41 +00002283
Chandler Carruth102e1b62010-07-22 07:11:21 +00002284 // Parse the asm-string list for clobbers if present.
2285 if (Tok.isNot(tok::r_paren)) {
2286 while (1) {
John McCall60d7b3a2010-08-24 06:29:42 +00002287 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattner64cb4752009-12-20 23:00:41 +00002288
Chandler Carruth102e1b62010-07-22 07:11:21 +00002289 if (Clobber.isInvalid())
2290 break;
Chris Lattner64cb4752009-12-20 23:00:41 +00002291
Chandler Carruth102e1b62010-07-22 07:11:21 +00002292 Clobbers.push_back(Clobber.release());
Chris Lattner64cb4752009-12-20 23:00:41 +00002293
Chandler Carruth102e1b62010-07-22 07:11:21 +00002294 if (Tok.isNot(tok::comma)) break;
2295 ConsumeToken();
2296 }
Chris Lattner64cb4752009-12-20 23:00:41 +00002297 }
2298 }
2299
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002300 T.consumeClose();
Chad Rosierdf5faf52012-08-25 00:11:56 +00002301 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2302 NumInputs, Names.data(), Constraints, Exprs,
2303 AsmString.take(), Clobbers,
2304 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002305}
2306
2307/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattner64cb4752009-12-20 23:00:41 +00002308/// asm-statement, assuming the leading ':' token was eaten.
Reid Spencer5f016e22007-07-11 17:01:13 +00002309///
2310/// [GNU] asm-operands:
2311/// asm-operand
2312/// asm-operands ',' asm-operand
2313///
2314/// [GNU] asm-operand:
2315/// asm-string-literal '(' expression ')'
2316/// '[' identifier ']' asm-string-literal '(' expression ')'
2317///
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00002318//
2319// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002320bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002321 SmallVectorImpl<Expr *> &Constraints,
2322 SmallVectorImpl<Expr *> &Exprs) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 // 'asm-operands' isn't present?
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002324 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002325 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002326
2327 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 // Read the [id] if present.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002329 if (Tok.is(tok::l_square)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002330 BalancedDelimiterTracker T(*this, tok::l_square);
2331 T.consumeOpen();
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002333 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002334 Diag(Tok, diag::err_expected_ident);
2335 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002336 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 }
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Anders Carlssonb235fc22007-11-22 01:36:19 +00002339 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner69efba72007-10-29 04:06:22 +00002340 ConsumeToken();
Anders Carlssonb235fc22007-11-22 01:36:19 +00002341
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002342 Names.push_back(II);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002343 T.consumeClose();
Anders Carlssonb235fc22007-11-22 01:36:19 +00002344 } else
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002345 Names.push_back(0);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002346
John McCall60d7b3a2010-08-24 06:29:42 +00002347 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002348 if (Constraint.isInvalid()) {
Anders Carlssonb235fc22007-11-22 01:36:19 +00002349 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002350 return true;
Anders Carlssonb235fc22007-11-22 01:36:19 +00002351 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002352 Constraints.push_back(Constraint.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00002353
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002354 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00002355 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002357 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002359
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 // Read the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002361 BalancedDelimiterTracker T(*this, tok::l_paren);
2362 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00002363 ExprResult Res(ParseExpression());
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002364 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002365 if (Res.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002366 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002367 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002368 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002369 Exprs.push_back(Res.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 // Eat the comma and continue parsing if it exists.
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002371 if (Tok.isNot(tok::comma)) return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 ConsumeToken();
2373 }
2374}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002375
Douglas Gregorc9977d02011-03-16 17:05:57 +00002376Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00002377 assert(Tok.is(tok::l_brace));
2378 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002379
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00002380 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1a5bd5d2012-11-19 21:13:18 +00002381 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002382 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00002383 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002384 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002385
John McCallf312b1e2010-08-26 23:41:50 +00002386 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2387 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002389 // Do not enter a scope for the brace, as the arguments are in the same scope
2390 // (the function body) as the body itself. Instead, just read the statement
2391 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00002392 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00002393
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002394 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002395 if (FnBody.isInvalid()) {
2396 Sema::CompoundScopeRAII CompoundScope(Actions);
Mike Stump1eb44332009-09-09 15:08:12 +00002397 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002398 MultiStmtArg(), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002399 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00002400
Douglas Gregorc9977d02011-03-16 17:05:57 +00002401 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002402 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00002403}
Sebastian Redla0fd8652008-12-21 16:41:36 +00002404
Sebastian Redld3a413d2009-04-26 20:35:05 +00002405/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2406///
2407/// function-try-block:
2408/// 'try' ctor-initializer[opt] compound-statement handler-seq
2409///
Douglas Gregorc9977d02011-03-16 17:05:57 +00002410Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00002411 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2412 SourceLocation TryLoc = ConsumeToken();
2413
John McCallf312b1e2010-08-26 23:41:50 +00002414 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2415 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00002416
2417 // Constructor initializer list?
2418 if (Tok.is(tok::colon))
2419 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00002420 else
2421 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002422
Richard Smith1a5bd5d2012-11-19 21:13:18 +00002423 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2424 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002425 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00002426 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002427 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002428
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002429 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikiec4027c82012-11-10 01:04:23 +00002430 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redld3a413d2009-04-26 20:35:05 +00002431 // If we failed to parse the try-catch, we just give the function an empty
2432 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002433 if (FnBody.isInvalid()) {
2434 Sema::CompoundScopeRAII CompoundScope(Actions);
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002435 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002436 MultiStmtArg(), false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002437 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00002438
Douglas Gregorc9977d02011-03-16 17:05:57 +00002439 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002440 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redld3a413d2009-04-26 20:35:05 +00002441}
2442
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002443bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002444 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002445 assert(SkipFunctionBodies &&
2446 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002447
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00002448 if (!PP.isCodeCompletionEnabled()) {
2449 ConsumeBrace();
2450 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false);
2451 return true;
2452 }
2453
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002454 // We're in code-completion mode. Skip parsing for all function bodies unless
2455 // the body contains the code-completion point.
2456 TentativeParsingAction PA(*this);
2457 ConsumeBrace();
2458 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00002459 /*StopAtCodeCompletion=*/true)) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002460 PA.Commit();
2461 return true;
2462 }
2463
2464 PA.Revert();
2465 return false;
2466}
2467
Sebastian Redla0fd8652008-12-21 16:41:36 +00002468/// ParseCXXTryBlock - Parse a C++ try-block.
2469///
2470/// try-block:
2471/// 'try' compound-statement handler-seq
2472///
Richard Smith534986f2012-04-14 00:33:13 +00002473StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002474 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2475
2476 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002477 return ParseCXXTryBlockCommon(TryLoc);
2478}
2479
2480/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2481/// function-try-block.
2482///
2483/// try-block:
2484/// 'try' compound-statement handler-seq
2485///
2486/// function-try-block:
2487/// 'try' ctor-initializer[opt] compound-statement handler-seq
2488///
2489/// handler-seq:
2490/// handler handler-seq[opt]
2491///
John Wiegley28bbe4b2011-04-28 01:08:34 +00002492/// [Borland] try-block:
2493/// 'try' compound-statement seh-except-block
2494/// 'try' compound-statment seh-finally-block
2495///
David Blaikiec4027c82012-11-10 01:04:23 +00002496StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002497 if (Tok.isNot(tok::l_brace))
2498 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Sean Huntbbd37c62009-11-21 08:43:09 +00002499 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002500
2501 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikiee5afdcf2012-11-13 18:51:45 +00002502 Scope::DeclScope | Scope::TryScope |
2503 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002504 if (TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002505 return TryBlock;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002506
John Wiegley28bbe4b2011-04-28 01:08:34 +00002507 // Borland allows SEH-handlers with 'try'
Chad Rosierb6604462012-07-10 21:35:27 +00002508
Richard Smith534986f2012-04-14 00:33:13 +00002509 if ((Tok.is(tok::identifier) &&
2510 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2511 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002512 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2513 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00002514 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002515 SourceLocation Loc = ConsumeToken();
2516 Handler = ParseSEHExceptBlock(Loc);
2517 }
2518 else {
2519 SourceLocation Loc = ConsumeToken();
2520 Handler = ParseSEHFinallyBlock(Loc);
2521 }
2522 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002523 return Handler;
John McCall7f040a92010-12-24 02:08:15 +00002524
John Wiegley28bbe4b2011-04-28 01:08:34 +00002525 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2526 TryLoc,
2527 TryBlock.take(),
2528 Handler.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002529 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00002530 else {
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002531 StmtVector Handlers;
Richard Smith534986f2012-04-14 00:33:13 +00002532 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00002533 MaybeParseCXX11Attributes(attrs);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002534 ProhibitAttributes(attrs);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002535
John Wiegley28bbe4b2011-04-28 01:08:34 +00002536 if (Tok.isNot(tok::kw_catch))
2537 return StmtError(Diag(Tok, diag::err_expected_catch));
2538 while (Tok.is(tok::kw_catch)) {
David Blaikiec4027c82012-11-10 01:04:23 +00002539 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley28bbe4b2011-04-28 01:08:34 +00002540 if (!Handler.isInvalid())
2541 Handlers.push_back(Handler.release());
2542 }
2543 // Don't bother creating the full statement if we don't have any usable
2544 // handlers.
2545 if (Handlers.empty())
2546 return StmtError();
2547
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002548 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(),Handlers);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002549 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002550}
2551
2552/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2553///
Richard Smith4cd81c52013-01-29 09:02:09 +00002554/// handler:
2555/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +00002556///
Richard Smith4cd81c52013-01-29 09:02:09 +00002557/// exception-declaration:
2558/// attribute-specifier-seq[opt] type-specifier-seq declarator
2559/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2560/// '...'
Sebastian Redla0fd8652008-12-21 16:41:36 +00002561///
David Blaikiec4027c82012-11-10 01:04:23 +00002562StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002563 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2564
2565 SourceLocation CatchLoc = ConsumeToken();
2566
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002567 BalancedDelimiterTracker T(*this, tok::l_paren);
2568 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redla0fd8652008-12-21 16:41:36 +00002569 return StmtError();
2570
2571 // C++ 3.3.2p3:
2572 // The name in a catch exception-declaration is local to the handler and
2573 // shall not be redeclared in the outermost block of the handler.
David Blaikiec4027c82012-11-10 01:04:23 +00002574 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikiee5afdcf2012-11-13 18:51:45 +00002575 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002576
2577 // exception-declaration is equivalent to '...' or a parameter-declaration
2578 // without default arguments.
John McCalld226f652010-08-21 09:40:31 +00002579 Decl *ExceptionDecl = 0;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002580 if (Tok.isNot(tok::ellipsis)) {
Richard Smith4cd81c52013-01-29 09:02:09 +00002581 ParsedAttributesWithRange Attributes(AttrFactory);
2582 MaybeParseCXX11Attributes(Attributes);
2583
John McCall0b7e6782011-03-24 11:26:52 +00002584 DeclSpec DS(AttrFactory);
Richard Smith4cd81c52013-01-29 09:02:09 +00002585 DS.takeAttributesFrom(Attributes);
2586
Sebastian Redl4b07b292008-12-22 19:15:10 +00002587 if (ParseCXXTypeSpecifierSeq(DS))
2588 return StmtError();
Richard Smith4cd81c52013-01-29 09:02:09 +00002589
Sebastian Redla0fd8652008-12-21 16:41:36 +00002590 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2591 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002592 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002593 } else
2594 ConsumeToken();
2595
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002596 T.consumeClose();
2597 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002598 return StmtError();
2599
2600 if (Tok.isNot(tok::l_brace))
2601 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2602
Sean Huntbbd37c62009-11-21 08:43:09 +00002603 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002604 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002605 if (Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002606 return Block;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002607
John McCall9ae2f072010-08-23 23:25:46 +00002608 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002609}
Francois Pichet1e862692011-05-06 20:48:22 +00002610
2611void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002612 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002613 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002614 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002615
Douglas Gregor3896fc52011-10-24 22:31:10 +00002616 // Handle dependent statements by parsing the braces as a compound statement.
2617 // This is not the same behavior as Visual C++, which don't treat this as a
2618 // compound statement, but for Clang's type checking we can't have anything
2619 // inside these braces escaping to the surrounding code.
2620 if (Result.Behavior == IEB_Dependent) {
2621 if (!Tok.is(tok::l_brace)) {
2622 Diag(Tok, diag::err_expected_lbrace);
Richard Smith534986f2012-04-14 00:33:13 +00002623 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002624 }
Richard Smith534986f2012-04-14 00:33:13 +00002625
2626 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002627 if (Compound.isInvalid())
2628 return;
Richard Smith534986f2012-04-14 00:33:13 +00002629
Douglas Gregorba0513d2011-10-25 01:33:02 +00002630 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2631 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002632 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002633 Result.Name,
2634 Compound.get());
2635 if (DepResult.isUsable())
2636 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002637 return;
2638 }
Richard Smith534986f2012-04-14 00:33:13 +00002639
Douglas Gregor3896fc52011-10-24 22:31:10 +00002640 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2641 if (Braces.consumeOpen()) {
Francois Pichet1e862692011-05-06 20:48:22 +00002642 Diag(Tok, diag::err_expected_lbrace);
2643 return;
2644 }
Francois Pichet1e862692011-05-06 20:48:22 +00002645
Douglas Gregor3896fc52011-10-24 22:31:10 +00002646 switch (Result.Behavior) {
2647 case IEB_Parse:
2648 // Parse the statements below.
2649 break;
Chad Rosierb6604462012-07-10 21:35:27 +00002650
Douglas Gregor3896fc52011-10-24 22:31:10 +00002651 case IEB_Dependent:
2652 llvm_unreachable("Dependent case handled above");
Chad Rosierb6604462012-07-10 21:35:27 +00002653
Douglas Gregor3896fc52011-10-24 22:31:10 +00002654 case IEB_Skip:
2655 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002656 return;
2657 }
2658
2659 // Condition is true, parse the statements.
2660 while (Tok.isNot(tok::r_brace)) {
2661 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2662 if (R.isUsable())
2663 Stmts.push_back(R.release());
2664 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002665 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002666}