blob: 8084a8fa5e71bc08707ec7b9aa7922ed7bfe4646 [file] [log] [blame]
Chris Lattner7ad0fbe2006-11-05 07:46:30 +00001//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
Chris Lattner0ccd51e2006-08-09 05:47:47 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner0ccd51e2006-08-09 05:47:47 +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 Lattner8a9a97a2009-12-10 00:21:05 +000016#include "RAIIObjectsForParser.h"
John McCallf413f5e2013-05-03 00:10:13 +000017#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/PrettyStackTrace.h"
20#include "clang/Basic/SourceManager.h"
John McCallf413f5e2013-05-03 00:10:13 +000021#include "clang/Basic/TargetInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
John McCallfaf5fb42010-08-26 23:41:50 +000023#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/Scope.h"
Richard Smith4f605af2012-08-18 00:55:03 +000025#include "clang/Sema/TypoCorrection.h"
John McCallf413f5e2013-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 Rosier32503022012-06-11 20:47:18 +000037#include "llvm/ADT/SmallString.h"
Chris Lattner0ccd51e2006-08-09 05:47:47 +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 Kyrtzidisdee82912008-09-07 18:58:01 +000056/// [C++] declaration-statement
Sebastian Redlb219c902008-12-21 16:41:36 +000057/// [C++] try-block
John Wiegley1c0675e2011-04-28 01:08:34 +000058/// [MS] seh-try-block
Fariborz Jahanian90814572007-10-04 20:19:06 +000059/// [OBC] objc-throw-statement
60/// [OBC] objc-try-catch-statement
Fariborz Jahanianf89ca382008-01-29 18:21:32 +000061/// [OBC] objc-synchronized-statement
Chris Lattner0116c472006-08-15 06:03:28 +000062/// [GNU] asm-statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +000063/// [OMP] openmp-construct [TODO]
64///
65/// labeled-statement:
66/// identifier ':' statement
67/// 'case' constant-expression ':' statement
68/// 'default' ':' statement
69///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000070/// selection-statement:
71/// if-statement
72/// switch-statement
73///
74/// iteration-statement:
75/// while-statement
76/// do-statement
77/// for-statement
78///
Chris Lattner9075bd72006-08-10 04:59:57 +000079/// expression-statement:
80/// expression[opt] ';'
81///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000082/// jump-statement:
83/// 'goto' identifier ';'
84/// 'continue' ';'
85/// 'break' ';'
86/// 'return' expression[opt] ';'
Chris Lattner503fadc2006-08-10 05:45:44 +000087/// [GNU] 'goto' '*' expression ';'
Chris Lattner0ccd51e2006-08-09 05:47:47 +000088///
Fariborz Jahanian90814572007-10-04 20:19:06 +000089/// [OBC] objc-throw-statement:
90/// [OBC] '@' 'throw' expression ';'
Mike Stump11289f42009-09-09 15:08:12 +000091/// [OBC] '@' 'throw' ';'
92///
John McCalldadc5752010-08-24 06:29:42 +000093StmtResult
Nico Weber3cef1082011-12-22 23:26:17 +000094Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
95 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000096
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +000097 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +000098
Richard Smithc202b282012-04-14 00:33:13 +000099 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000100 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
Richard Smithc202b282012-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;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000120
Chris Lattner503fadc2006-08-10 05:45:44 +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 Gregor0e7dde52011-04-24 05:37:28 +0000124Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000125 tok::TokenKind Kind = Tok.getKind();
126 SourceLocation AtLoc;
127 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000128 case tok::at: // May be a @try or @throw statement
129 {
Richard Smithc202b282012-04-14 00:33:13 +0000130 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000131 AtLoc = ConsumeToken(); // consume @
Sebastian Redlbab9a4b2008-12-11 20:12:42 +0000132 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000133 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000134
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000135 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000136 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000137 cutOffParsing();
138 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000139
Douglas Gregor0e7dde52011-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 Kyrtzidis07b8b632008-07-12 21:04:42 +0000143 // identifier ':' statement
Richard Smithc202b282012-04-14 00:33:13 +0000144 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000145 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000146
Richard Smith4f605af2012-08-18 00:55:03 +0000147 // Look up the identifier, and typo-correct it to a keyword if it's not
148 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000149 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-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 Gregor0e7dde52011-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 Smith4f605af2012-08-18 00:55:03 +0000174 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000175
Richard Smith4f605af2012-08-18 00:55:03 +0000176 // If the identifier was typo-corrected, try again.
177 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000178 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000179 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000180
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000181 // Fall through
182 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000183
Chris Lattner803802d2009-03-24 17:04:48 +0000184 default: {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000185 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000186 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek5eec2b02010-11-10 05:59:39 +0000187 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000188 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000189 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000190 }
191
192 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000193 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000194 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000195 }
Mike Stump11289f42009-09-09 15:08:12 +0000196
Richard Smithc202b282012-04-14 00:33:13 +0000197 return ParseExprStatement();
Chris Lattner803802d2009-03-24 17:04:48 +0000198 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000199
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000200 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000201 return ParseCaseStatement();
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000202 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000203 return ParseDefaultStatement();
Sebastian Redl042ad952008-12-11 19:30:53 +0000204
Chris Lattner9075bd72006-08-10 04:59:57 +0000205 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000206 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000207 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000208 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
209 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000210 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000211
Chris Lattner9075bd72006-08-10 04:59:57 +0000212 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000213 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000214 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000215 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000216
Chris Lattner9075bd72006-08-10 04:59:57 +0000217 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000218 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000219 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000220 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000221 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000222 break;
223 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000224 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000225
226 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000227 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000228 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000229 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000230 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000231 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000232 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000233 break;
234 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000235 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000236 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000237 break;
238 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000239 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000240 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000241 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000242
Sebastian Redlb219c902008-12-21 16:41:36 +0000243 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000244 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000245 bool msAsm = false;
246 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000247 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000248 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000249 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000250 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000251 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000252
Sebastian Redlb219c902008-12-21 16:41:36 +0000253 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000254 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000255
256 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000257 ProhibitAttributes(Attrs); // TODO: is it correct?
258 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000259
260 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000261 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000262 HandlePragmaVisibility();
263 return StmtEmpty();
264
265 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000266 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000267 HandlePragmaPack();
268 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000269
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000270 case tok::annot_pragma_msstruct:
271 ProhibitAttributes(Attrs);
272 HandlePragmaMSStruct();
273 return StmtEmpty();
274
Eli Friedmanae8ee252012-10-08 23:52:38 +0000275 case tok::annot_pragma_align:
276 ProhibitAttributes(Attrs);
277 HandlePragmaAlign();
278 return StmtEmpty();
279
Eli Friedmanbbbbac62012-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 Friedman68be1642012-10-04 02:36:51 +0000295 case tok::annot_pragma_fp_contract:
Lang Hamesa930e712012-10-21 01:10:01 +0000296 Diag(Tok, diag::err_pragma_fp_contract_scope);
297 ConsumeToken();
298 return StmtError();
299
Eli Friedman68be1642012-10-04 02:36:51 +0000300 case tok::annot_pragma_opencl_extension:
301 ProhibitAttributes(Attrs);
302 HandlePragmaOpenCLExtension();
303 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000304
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000305 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000306 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000307 return HandlePragmaCaptured();
308
Alexey Bataeva769e072013-03-22 06:34:35 +0000309 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000310 ProhibitAttributes(Attrs);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000311 return ParseOpenMPDeclarativeOrExecutableDirective();
312
Sebastian Redlb219c902008-12-21 16:41:36 +0000313 }
314
Chris Lattner503fadc2006-08-10 05:45:44 +0000315 // If we reached this code, the statement must end in a semicolon.
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000316 if (Tok.is(tok::semi)) {
Chris Lattner503fadc2006-08-10 05:45:44 +0000317 ConsumeToken();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000318 } else if (!Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000319 // If the result was valid, then we do want to diagnose this. Use
320 // ExpectAndConsume to emit the diagnostic, even though we know it won't
321 // succeed.
322 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000323 // Skip until we see a } or ;, but don't eat it.
324 SkipUntil(tok::r_brace, true, true);
Chris Lattner503fadc2006-08-10 05:45:44 +0000325 }
Mike Stump11289f42009-09-09 15:08:12 +0000326
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000327 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000328}
329
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000330/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000331StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000332 // If a case keyword is missing, this is where it should be inserted.
333 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000334
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000335 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000336 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000337 if (Expr.isInvalid()) {
338 // If the expression is invalid, skip ahead to the next semicolon or '}'.
339 // Not doing this opens us up to the possibility of infinite loops if
340 // ParseExpression does not consume any tokens.
341 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
342 if (Tok.is(tok::semi))
343 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000344 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000345 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000346
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000347 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
348 Actions.CheckCaseExpression(Expr.get())) {
349 // If a constant expression is followed by a colon inside a switch block,
350 // suggest a missing case keyword.
351 Diag(OldToken, diag::err_expected_case_before_expression)
352 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000353
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000354 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000355 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000356 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000357
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000358 // Otherwise, eat the semicolon.
359 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000360 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000361}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000362
Richard Smithc202b282012-04-14 00:33:13 +0000363StmtResult Parser::ParseSEHTryBlock() {
John Wiegley1c0675e2011-04-28 01:08:34 +0000364 assert(Tok.is(tok::kw___try) && "Expected '__try'");
365 SourceLocation Loc = ConsumeToken();
366 return ParseSEHTryBlockCommon(Loc);
367}
368
369/// ParseSEHTryBlockCommon
370///
371/// seh-try-block:
372/// '__try' compound-statement seh-handler
373///
374/// seh-handler:
375/// seh-except-block
376/// seh-finally-block
377///
378StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
379 if(Tok.isNot(tok::l_brace))
380 return StmtError(Diag(Tok,diag::err_expected_lbrace));
381
Joao Matos566359c2012-09-04 17:49:35 +0000382 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000383 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000384 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000385
386 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000387 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000388 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000389 SourceLocation Loc = ConsumeToken();
390 Handler = ParseSEHExceptBlock(Loc);
391 } else if (Tok.is(tok::kw___finally)) {
392 SourceLocation Loc = ConsumeToken();
393 Handler = ParseSEHFinallyBlock(Loc);
394 } else {
395 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
396 }
397
398 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000399 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000400
401 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
402 TryLoc,
403 TryBlock.take(),
404 Handler.take());
405}
406
407/// ParseSEHExceptBlock - Handle __except
408///
409/// seh-except-block:
410/// '__except' '(' seh-filter-expression ')' compound-statement
411///
412StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
413 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
414 raii2(Ident___exception_code, false),
415 raii3(Ident_GetExceptionCode, false);
416
417 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
418 return StmtError();
419
420 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
421
David Blaikiebbafb8a2012-03-11 07:00:24 +0000422 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000423 Ident__exception_info->setIsPoisoned(false);
424 Ident___exception_info->setIsPoisoned(false);
425 Ident_GetExceptionInfo->setIsPoisoned(false);
426 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000427 ExprResult FilterExpr(ParseExpression());
Francois Pichetbfaf4772011-04-28 03:14:31 +0000428
David Blaikiebbafb8a2012-03-11 07:00:24 +0000429 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000430 Ident__exception_info->setIsPoisoned(true);
431 Ident___exception_info->setIsPoisoned(true);
432 Ident_GetExceptionInfo->setIsPoisoned(true);
433 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000434
435 if(FilterExpr.isInvalid())
436 return StmtError();
437
438 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
439 return StmtError();
440
Richard Smithc202b282012-04-14 00:33:13 +0000441 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000442
443 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000444 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000445
446 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
447}
448
449/// ParseSEHFinallyBlock - Handle __finally
450///
451/// seh-finally-block:
452/// '__finally' compound-statement
453///
454StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
455 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
456 raii2(Ident___abnormal_termination, false),
457 raii3(Ident_AbnormalTermination, false);
458
Richard Smithc202b282012-04-14 00:33:13 +0000459 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000460 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000461 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000462
463 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000464}
465
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000466/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000467///
468/// labeled-statement:
469/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000470/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000471///
Richard Smithc202b282012-04-14 00:33:13 +0000472StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000473 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
474 "Not an identifier!");
475
476 Token IdentTok = Tok; // Save the whole token.
477 ConsumeToken(); // eat the identifier.
478
479 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000480
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000481 // identifier ':' statement
482 SourceLocation ColonLoc = ConsumeToken();
483
Richard Smithc202b282012-04-14 00:33:13 +0000484 // Read label attributes, if present. attrs will contain both C++11 and GNU
485 // attributes (if present) after this point.
John McCall53fa7142010-12-24 02:08:15 +0000486 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000487
John McCalldadc5752010-08-24 06:29:42 +0000488 StmtResult SubStmt(ParseStatement());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000489
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000490 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000491 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000492 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000493
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000494 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
495 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000496 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000497 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000498 attrs.clear();
499 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000500
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000501 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
502 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000503}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000504
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000505/// ParseCaseStatement
506/// labeled-statement:
507/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000508/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000509///
Richard Smithc202b282012-04-14 00:33:13 +0000510StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000511 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000512
Chris Lattner34a22092009-03-04 04:23:07 +0000513 // It is very very common for code to contain many case statements recursively
514 // nested, as in (but usually without indentation):
515 // case 1:
516 // case 2:
517 // case 3:
518 // case 4:
519 // case 5: etc.
520 //
521 // Parsing this naively works, but is both inefficient and can cause us to run
522 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000523 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000524 // but all the grossness is constrained to ParseCaseStatement (and some
525 // wierdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000526
Chris Lattner34a22092009-03-04 04:23:07 +0000527 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
528 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000529 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattner34a22092009-03-04 04:23:07 +0000531 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
532 // gets updated each time a new case is parsed, and whose body is unset so
533 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieu3481fcd2011-09-09 02:16:15 +0000534 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattner34a22092009-03-04 04:23:07 +0000536 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000537 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000538 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000539 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
540 ConsumeToken(); // eat the 'case'.
Mike Stump11289f42009-09-09 15:08:12 +0000541
Douglas Gregord328d572009-09-21 18:10:23 +0000542 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000543 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000544 cutOffParsing();
545 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000546 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000547
Chris Lattner125c0ee2009-12-10 00:38:54 +0000548 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
549 /// Disable this form of error recovery while we're parsing the case
550 /// expression.
551 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000552
Richard Trieu2c850c02011-04-21 21:44:26 +0000553 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
554 MissingCase = false;
Chris Lattner34a22092009-03-04 04:23:07 +0000555 if (LHS.isInvalid()) {
Chris Lattner476c3ad2006-08-13 22:09:58 +0000556 SkipUntil(tok::colon);
Sebastian Redl042ad952008-12-11 19:30:53 +0000557 return StmtError();
Chris Lattner476c3ad2006-08-13 22:09:58 +0000558 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000559
Chris Lattner34a22092009-03-04 04:23:07 +0000560 // GNU case range extension.
561 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000562 ExprResult RHS;
Chris Lattner34a22092009-03-04 04:23:07 +0000563 if (Tok.is(tok::ellipsis)) {
564 Diag(Tok, diag::ext_gnu_case_range);
565 DotDotDotLoc = ConsumeToken();
Sebastian Redl042ad952008-12-11 19:30:53 +0000566
Chris Lattner34a22092009-03-04 04:23:07 +0000567 RHS = ParseConstantExpression();
568 if (RHS.isInvalid()) {
569 SkipUntil(tok::colon);
570 return StmtError();
571 }
572 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000573
Chris Lattner125c0ee2009-12-10 00:38:54 +0000574 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000575
John McCall0140bfe2011-01-22 09:28:32 +0000576 if (Tok.is(tok::colon)) {
577 ColonLoc = ConsumeToken();
578
579 // Treat "case blah;" as a typo for "case blah:".
580 } else if (Tok.is(tok::semi)) {
581 ColonLoc = ConsumeToken();
582 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
583 << FixItHint::CreateReplacement(ColonLoc, ":");
584 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000585 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
586 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
587 << FixItHint::CreateInsertion(ExpectedLoc, ":");
588 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000589 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000590
John McCalldadc5752010-08-24 06:29:42 +0000591 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000592 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
593 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000594
Chris Lattner34a22092009-03-04 04:23:07 +0000595 // If we had a sema error parsing this case, then just ignore it and
596 // continue parsing the sub-stmt.
597 if (Case.isInvalid()) {
598 if (TopLevelCase.isInvalid()) // No parsed case stmts.
599 return ParseStatement();
600 // Otherwise, just don't add it as a nested case.
601 } else {
602 // If this is the first case statement we parsed, it becomes TopLevelCase.
603 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000604 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000605 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000606 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000607 else
John McCallb268a282010-08-23 23:25:46 +0000608 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000609 DeepestParsedCaseStmt = NextDeepest;
610 }
Mike Stump11289f42009-09-09 15:08:12 +0000611
Chris Lattner34a22092009-03-04 04:23:07 +0000612 // Handle all case statements.
613 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000614
Chris Lattner34a22092009-03-04 04:23:07 +0000615 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump11289f42009-09-09 15:08:12 +0000616
Chris Lattner34a22092009-03-04 04:23:07 +0000617 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000618 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000619
Chris Lattner34a22092009-03-04 04:23:07 +0000620 if (Tok.isNot(tok::r_brace)) {
621 SubStmt = ParseStatement();
622 } else {
623 // Nicely diagnose the common error "switch (X) { case 4: }", which is
624 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000625 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000626 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
627 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner34a22092009-03-04 04:23:07 +0000628 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000629 }
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattner34a22092009-03-04 04:23:07 +0000631 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000632 if (SubStmt.isInvalid())
Chris Lattner34a22092009-03-04 04:23:07 +0000633 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000634
Chris Lattner34a22092009-03-04 04:23:07 +0000635 // Install the body into the most deeply-nested case.
John McCallb268a282010-08-23 23:25:46 +0000636 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl042ad952008-12-11 19:30:53 +0000637
Chris Lattner34a22092009-03-04 04:23:07 +0000638 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000639 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000640}
641
642/// ParseDefaultStatement
643/// labeled-statement:
644/// 'default' ':' statement
645/// Note that this does not parse the 'statement' at the end.
646///
Richard Smithc202b282012-04-14 00:33:13 +0000647StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000648 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000649 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000650
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000651 SourceLocation ColonLoc;
John McCall0140bfe2011-01-22 09:28:32 +0000652 if (Tok.is(tok::colon)) {
653 ColonLoc = ConsumeToken();
654
655 // Treat "default;" as a typo for "default:".
656 } else if (Tok.is(tok::semi)) {
657 ColonLoc = ConsumeToken();
658 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
659 << FixItHint::CreateReplacement(ColonLoc, ":");
660 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000661 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
662 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
663 << FixItHint::CreateInsertion(ExpectedLoc, ":");
664 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000665 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000666
Richard Smith1002d102012-02-17 01:35:32 +0000667 StmtResult SubStmt;
668
669 if (Tok.isNot(tok::r_brace)) {
670 SubStmt = ParseStatement();
671 } else {
672 // Diagnose the common error "switch (X) {... default: }", which is
673 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000674 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000675 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
676 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
677 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000678 }
679
Richard Smith1002d102012-02-17 01:35:32 +0000680 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000681 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000682 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000683
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000684 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000685 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000686}
687
Richard Smithc202b282012-04-14 00:33:13 +0000688StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
689 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000690}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000691
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000692/// ParseCompoundStatement - Parse a "{}" block.
693///
694/// compound-statement: [C99 6.8.2]
695/// { block-item-list[opt] }
696/// [GNU] { label-declarations block-item-list } [TODO]
697///
698/// block-item-list:
699/// block-item
700/// block-item-list block-item
701///
702/// block-item:
703/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000704/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000705/// statement
706/// [OMP] openmp-directive [TODO]
707///
708/// [GNU] label-declarations:
709/// [GNU] label-declaration
710/// [GNU] label-declarations label-declaration
711///
712/// [GNU] label-declaration:
713/// [GNU] '__label__' identifier-list ';'
714///
715/// [OMP] openmp-directive: [TODO]
716/// [OMP] barrier-directive
717/// [OMP] flush-directive
Chris Lattner30f910e2006-10-16 05:52:41 +0000718///
Richard Smithc202b282012-04-14 00:33:13 +0000719StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000720 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000721 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000722
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000723 // Enter a scope to hold everything within the compound stmt. Compound
724 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000725 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000726
727 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000728 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000729}
730
Lang Hames2954cea2012-11-03 22:29:05 +0000731/// Parse any pragmas at the start of the compound expression. We handle these
732/// separately since some pragmas (FP_CONTRACT) must appear before any C
733/// statement in the compound, but may be intermingled with other pragmas.
734void Parser::ParseCompoundStatementLeadingPragmas() {
735 bool checkForPragmas = true;
736 while (checkForPragmas) {
737 switch (Tok.getKind()) {
738 case tok::annot_pragma_vis:
739 HandlePragmaVisibility();
740 break;
741 case tok::annot_pragma_pack:
742 HandlePragmaPack();
743 break;
744 case tok::annot_pragma_msstruct:
745 HandlePragmaMSStruct();
746 break;
747 case tok::annot_pragma_align:
748 HandlePragmaAlign();
749 break;
750 case tok::annot_pragma_weak:
751 HandlePragmaWeak();
752 break;
753 case tok::annot_pragma_weakalias:
754 HandlePragmaWeakAlias();
755 break;
756 case tok::annot_pragma_redefine_extname:
757 HandlePragmaRedefineExtname();
758 break;
759 case tok::annot_pragma_opencl_extension:
760 HandlePragmaOpenCLExtension();
761 break;
762 case tok::annot_pragma_fp_contract:
763 HandlePragmaFPContract();
764 break;
765 default:
766 checkForPragmas = false;
767 break;
768 }
769 }
770
771}
772
Chris Lattnerf2978802007-01-21 06:52:16 +0000773/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000774/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000775/// consume the '}' at the end of the block. It does not manipulate the scope
776/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000777StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000778 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000779 Tok.getLocation(),
780 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000781
782 // Record the state of the FP_CONTRACT pragma, restore on leaving the
783 // compound statement.
784 Sema::FPContractStateRAII SaveFPContractState(Actions);
785
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000786 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000787 BalancedDelimiterTracker T(*this, tok::l_brace);
788 if (T.consumeOpen())
789 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000790
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000791 Sema::CompoundScopeRAII CompoundScope(Actions);
792
Lang Hames2954cea2012-11-03 22:29:05 +0000793 // Parse any pragmas at the beginning of the compound statement.
794 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000795
Lang Hames2954cea2012-11-03 22:29:05 +0000796 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000797
Chris Lattner43e7f312011-02-18 02:08:43 +0000798 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
799 // only allowed at the start of a compound stmt regardless of the language.
800 while (Tok.is(tok::kw___label__)) {
801 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000802
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000803 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000804 while (1) {
805 if (Tok.isNot(tok::identifier)) {
806 Diag(Tok, diag::err_expected_ident);
807 break;
808 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000809
Chris Lattner43e7f312011-02-18 02:08:43 +0000810 IdentifierInfo *II = Tok.getIdentifierInfo();
811 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000812 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000813
Chris Lattner43e7f312011-02-18 02:08:43 +0000814 if (!Tok.is(tok::comma))
815 break;
816 ConsumeToken();
817 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000818
John McCall084e83d2011-03-24 11:26:52 +0000819 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000820 DeclGroupPtrTy Res =
821 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000822 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000823
Chris Lattner02f1b612012-04-28 16:12:17 +0000824 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000825 if (R.isUsable())
826 Stmts.push_back(R.release());
827 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000828
Chris Lattner43e7f312011-02-18 02:08:43 +0000829 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000830 if (Tok.is(tok::annot_pragma_unused)) {
831 HandlePragmaUnused();
832 continue;
833 }
834
David Blaikiebbafb8a2012-03-11 07:00:24 +0000835 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet4a7de3e2011-05-06 20:48:22 +0000836 Tok.is(tok::kw___if_not_exists))) {
837 ParseMicrosoftIfExistsStatement(Stmts);
838 continue;
839 }
840
John McCalldadc5752010-08-24 06:29:42 +0000841 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000842 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000843 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000844 } else {
845 // __extension__ can start declarations and it can also be a unary
846 // operator for expressions. Consume multiple __extension__ markers here
847 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000848 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000849 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000850 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000851 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000852
John McCall084e83d2011-03-24 11:26:52 +0000853 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000854 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000855
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000856 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +0000857 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +0000858 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +0000859 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +0000860 ExtensionRAIIObject O(Diags);
861
Chris Lattner49836b42009-04-02 04:16:50 +0000862 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000863 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
864 Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000865 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000866 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000867 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000868 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +0000869 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +0000870
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000871 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000872 SkipUntil(tok::semi);
873 continue;
874 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +0000875
Alexis Hunt96d5c762009-11-21 08:43:09 +0000876 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +0000877 // Eat the semicolon at the end of stmt and convert the expr into a
878 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000879 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000880 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000881 }
882 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000883
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000884 if (R.isUsable())
Sebastian Redld9f7b1c2008-12-10 00:02:53 +0000885 Stmts.push_back(R.release());
Chris Lattner30f910e2006-10-16 05:52:41 +0000886 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000887
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000888 SourceLocation CloseLoc = Tok.getLocation();
889
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000890 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +0000891 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000892 // Recover by creating a compound statement with what we parsed so far,
893 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +0000894 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +0000895
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000896 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000897 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000898}
Chris Lattnerc951dae2006-08-10 04:23:57 +0000899
Chris Lattnerc0081db2008-12-12 06:31:07 +0000900/// ParseParenExprOrCondition:
901/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +0000902/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +0000903///
904/// This function parses and performs error recovery on the specified condition
905/// or expression (depending on whether we're in C++ or C mode). This function
906/// goes out of its way to recover well. It returns true if there was a parser
907/// error (the right paren couldn't be found), which indicates that the caller
908/// should try to recover harder. It returns false if the condition is
909/// successfully parsed. Note that a successful parse can still have semantic
910/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +0000911bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +0000912 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +0000913 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000914 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000915 BalancedDelimiterTracker T(*this, tok::l_paren);
916 T.consumeOpen();
917
David Blaikiebbafb8a2012-03-11 07:00:24 +0000918 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +0000919 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000920 else {
921 ExprResult = ParseExpression();
John McCall48871652010-08-21 09:40:31 +0000922 DeclResult = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000923
Douglas Gregore60e41a2010-05-06 17:25:47 +0000924 // If required, convert to a boolean value.
925 if (!ExprResult.isInvalid() && ConvertToBoolean)
926 ExprResult
John McCallb268a282010-08-23 23:25:46 +0000927 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000928 }
Mike Stump11289f42009-09-09 15:08:12 +0000929
Chris Lattnerc0081db2008-12-12 06:31:07 +0000930 // If the parser was confused by the condition and we don't have a ')', try to
931 // recover by skipping ahead to a semi and bailing out. If condexp is
932 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +0000933 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +0000934 SkipUntil(tok::semi);
935 // Skipping may have stopped if it found the containing ')'. If so, we can
936 // continue parsing the if statement.
937 if (Tok.isNot(tok::r_paren))
938 return true;
939 }
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattnerc0081db2008-12-12 06:31:07 +0000941 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000942 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +0000943
Chris Lattner70d44982012-04-28 16:24:20 +0000944 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
945 // that all callers are looking for a statement after the condition, so ")"
946 // isn't valid.
947 while (Tok.is(tok::r_paren)) {
948 Diag(Tok, diag::err_extraneous_rparen_in_condition)
949 << FixItHint::CreateRemoval(Tok.getLocation());
950 ConsumeParen();
951 }
Chad Rosier67055f52012-07-10 21:35:27 +0000952
Chris Lattnerc0081db2008-12-12 06:31:07 +0000953 return false;
954}
955
956
Chris Lattnerc951dae2006-08-10 04:23:57 +0000957/// ParseIfStatement
958/// if-statement: [C99 6.8.4.1]
959/// 'if' '(' expression ')' statement
960/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +0000961/// [C++] 'if' '(' condition ')' statement
962/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +0000963///
Richard Smithc202b282012-04-14 00:33:13 +0000964StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000965 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000966 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +0000967
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000968 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +0000969 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +0000970 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +0000971 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +0000972 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +0000973
David Blaikiebbafb8a2012-03-11 07:00:24 +0000974 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000975
Chris Lattner2dd1b722007-08-26 23:08:06 +0000976 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
977 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000978 //
979 // C++ 6.4p3:
980 // A name introduced by a declaration in a condition is in scope from its
981 // point of declaration until the end of the substatements controlled by the
982 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +0000983 // C++ 3.3.2p4:
984 // Names declared in the for-init-statement, and in the condition of if,
985 // while, for, and switch statements are local to the if, while, for, or
986 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000987 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +0000988 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +0000989
Chris Lattnerc951dae2006-08-10 04:23:57 +0000990 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +0000991 ExprResult CondExp;
John McCall48871652010-08-21 09:40:31 +0000992 Decl *CondVar = 0;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000993 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +0000994 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +0000995
David Blaikiea5696df2012-05-16 04:20:04 +0000996 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattner8fb26252007-08-22 05:28:50 +0000998 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +0000999 // there is no compound stmt. C90 does not have this clause. We only do this
1000 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001001 //
1002 // C++ 6.4p1:
1003 // The substatement in a selection-statement (each substatement, in the else
1004 // form of the if statement) implicitly defines a local scope.
1005 //
1006 // For C++ we create a scope for the condition and a new scope for
1007 // substatements because:
1008 // -When the 'then' scope exits, we want the condition declaration to still be
1009 // active for the 'else' scope too.
1010 // -Sema will detect name clashes by considering declarations of a
1011 // 'ControlScope' as part of its direct subscope.
1012 // -If we wanted the condition and substatement to be in the same scope, we
1013 // would have to notify ParseStatement not to create a new scope. It's
1014 // simpler to let it create a new scope.
1015 //
Mike Stump11289f42009-09-09 15:08:12 +00001016 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001017 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001018
Chris Lattner5c5808a2007-10-29 05:08:52 +00001019 // Read the 'then' stmt.
1020 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001021
1022 SourceLocation InnerStatementTrailingElseLoc;
1023 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001024
Chris Lattner37e54f42007-08-22 05:16:28 +00001025 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001026 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001027
Chris Lattnerc951dae2006-08-10 04:23:57 +00001028 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001029 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001030 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001031 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001032
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001033 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001034 if (TrailingElseLoc)
1035 *TrailingElseLoc = Tok.getLocation();
1036
Chris Lattneraf635312006-10-16 06:06:51 +00001037 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001038 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001039
Chris Lattner8fb26252007-08-22 05:28:50 +00001040 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001041 // there is no compound stmt. C90 does not have this clause. We only do
1042 // this if the body isn't a compound statement to avoid push/pop in common
1043 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001044 //
1045 // C++ 6.4p1:
1046 // The substatement in a selection-statement (each substatement, in the else
1047 // form of the if statement) implicitly defines a local scope.
1048 //
Sebastian Redl042ad952008-12-11 19:30:53 +00001049 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001050 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001051
Chris Lattner30f910e2006-10-16 05:52:41 +00001052 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001053
Chris Lattner37e54f42007-08-22 05:16:28 +00001054 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001055 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001056 } else if (Tok.is(tok::code_completion)) {
1057 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001058 cutOffParsing();
1059 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001060 } else if (InnerStatementTrailingElseLoc.isValid()) {
1061 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001062 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001063
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001064 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001065
Chris Lattner5c5808a2007-10-29 05:08:52 +00001066 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001067 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001068 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001069 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1070 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1071 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001072 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001073 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001074 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001075
Chris Lattner5c5808a2007-10-29 05:08:52 +00001076 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001077 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001078 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001079 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001080 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001081
John McCallb268a282010-08-23 23:25:46 +00001082 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001083 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001084}
1085
Chris Lattner9075bd72006-08-10 04:59:57 +00001086/// ParseSwitchStatement
1087/// switch-statement:
1088/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001089/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001090StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001091 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001092 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001093
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001094 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001095 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001096 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001097 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001098 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001099
David Blaikiebbafb8a2012-03-11 07:00:24 +00001100 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001101
Chris Lattner2dd1b722007-08-26 23:08:06 +00001102 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1103 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001104 //
1105 // C++ 6.4p3:
1106 // A name introduced by a declaration in a condition is in scope from its
1107 // point of declaration until the end of the substatements controlled by the
1108 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001109 // C++ 3.3.2p4:
1110 // Names declared in the for-init-statement, and in the condition of if,
1111 // while, for, and switch statements are local to the if, while, for, or
1112 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001113 //
Richard Trieu2c850c02011-04-21 21:44:26 +00001114 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001115 if (C99orCXX)
1116 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001117 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001118
Chris Lattner9075bd72006-08-10 04:59:57 +00001119 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001120 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001121 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001122 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001123 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001124
John McCalldadc5752010-08-24 06:29:42 +00001125 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001126 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001127
Douglas Gregore60e41a2010-05-06 17:25:47 +00001128 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001129 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001130 // FIXME: This is not optimal recovery, but parsing the body is more
1131 // dangerous due to the presence of case and default statements, which
1132 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001133 if (Tok.is(tok::l_brace)) {
1134 ConsumeBrace();
1135 SkipUntil(tok::r_brace, false, false);
1136 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001137 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001138 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001139 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001140
Chris Lattner8fb26252007-08-22 05:28:50 +00001141 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001142 // there is no compound stmt. C90 does not have this clause. We only do this
1143 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001144 //
1145 // C++ 6.4p1:
1146 // The substatement in a selection-statement (each substatement, in the else
1147 // form of the if statement) implicitly defines a local scope.
1148 //
1149 // See comments in ParseIfStatement for why we create a scope for the
1150 // condition and a new scope for substatement in C++.
1151 //
Mike Stump11289f42009-09-09 15:08:12 +00001152 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001153 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001154
Chris Lattner9075bd72006-08-10 04:59:57 +00001155 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001156 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001157
Chris Lattner8fd2d012010-01-24 01:50:29 +00001158 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001159 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001160 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001161
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001162 if (Body.isInvalid()) {
Chris Lattner8fd2d012010-01-24 01:50:29 +00001163 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001164
1165 // Put the synthesized null statement on the same line as the end of switch
1166 // condition.
1167 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1168 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1169 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001170
John McCallb268a282010-08-23 23:25:46 +00001171 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001172}
1173
1174/// ParseWhileStatement
1175/// while-statement: [C99 6.8.5.1]
1176/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001177/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001178StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001179 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001180 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001181 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001182
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001183 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001184 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001185 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001186 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001187 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001188
David Blaikiebbafb8a2012-03-11 07:00:24 +00001189 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001190
Chris Lattner2dd1b722007-08-26 23:08:06 +00001191 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1192 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001193 //
1194 // C++ 6.4p3:
1195 // A name introduced by a declaration in a condition is in scope from its
1196 // point of declaration until the end of the substatements controlled by the
1197 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001198 // C++ 3.3.2p4:
1199 // Names declared in the for-init-statement, and in the condition of if,
1200 // while, for, and switch statements are local to the if, while, for, or
1201 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001202 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001203 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001204 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001205 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1206 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001207 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001208 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1209 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001210
Chris Lattner9075bd72006-08-10 04:59:57 +00001211 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001212 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001213 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001214 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001215 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001216
David Blaikiea5696df2012-05-16 04:20:04 +00001217 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001218
Chris Lattner8fb26252007-08-22 05:28:50 +00001219 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001220 // there is no compound stmt. C90 does not have this clause. We only do this
1221 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001222 //
1223 // C++ 6.5p2:
1224 // The substatement in an iteration-statement implicitly defines a local scope
1225 // which is entered and exited each time through the loop.
1226 //
1227 // See comments in ParseIfStatement for why we create a scope for the
1228 // condition and a new scope for substatement in C++.
1229 //
Mike Stump11289f42009-09-09 15:08:12 +00001230 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001231 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001232
Chris Lattner9075bd72006-08-10 04:59:57 +00001233 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001234 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001235
Chris Lattner8fb26252007-08-22 05:28:50 +00001236 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001237 InnerScope.Exit();
1238 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001239
John McCall48871652010-08-21 09:40:31 +00001240 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001241 return StmtError();
1242
John McCallb268a282010-08-23 23:25:46 +00001243 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001244}
1245
1246/// ParseDoStatement
1247/// do-statement: [C99 6.8.5.2]
1248/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001249/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001250StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001251 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001252 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001253
Chris Lattner2dd1b722007-08-26 23:08:06 +00001254 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1255 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001256 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001257 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001258 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001259 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001260 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001261
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001262 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001263
Chris Lattner8fb26252007-08-22 05:28:50 +00001264 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001265 // there is no compound stmt. C90 does not have this clause. We only do this
1266 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001267 //
1268 // C++ 6.5p2:
1269 // The substatement in an iteration-statement implicitly defines a local scope
1270 // which is entered and exited each time through the loop.
1271 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001272 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001273 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001274 Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001275
Chris Lattner9075bd72006-08-10 04:59:57 +00001276 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001277 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001278
Chris Lattner8fb26252007-08-22 05:28:50 +00001279 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001280 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001281
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001282 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001283 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001284 Diag(Tok, diag::err_expected_while);
Chris Lattner03c40412008-11-23 23:17:07 +00001285 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner0046de12008-11-13 18:52:53 +00001286 SkipUntil(tok::semi, false, true);
1287 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001288 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001289 }
Chris Lattneraf635312006-10-16 06:06:51 +00001290 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001291
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001292 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001293 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner0046de12008-11-13 18:52:53 +00001294 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001295 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001296 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001297
Chris Lattner10da53c2008-12-12 06:35:28 +00001298 // Parse the parenthesized condition.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001299 BalancedDelimiterTracker T(*this, tok::l_paren);
1300 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001301
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001302 // FIXME: Do not just parse the attribute contents and throw them away
1303 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001304 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001305 ProhibitAttributes(attrs);
1306
John McCalldadc5752010-08-24 06:29:42 +00001307 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001308 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001309 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001310
Sebastian Redlb62406f2008-12-11 19:48:14 +00001311 if (Cond.isInvalid() || Body.isInvalid())
1312 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001313
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001314 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1315 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001316}
1317
1318/// ParseForStatement
1319/// for-statement: [C99 6.8.5.3]
1320/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1321/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001322/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1323/// [C++] statement
Richard Smith02e85f32011-04-14 22:09:26 +00001324/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001325/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1326/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001327///
1328/// [C++] for-init-statement:
1329/// [C++] expression-statement
1330/// [C++] simple-declaration
1331///
Richard Smith02e85f32011-04-14 22:09:26 +00001332/// [C++0x] for-range-declaration:
1333/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1334/// [C++0x] for-range-initializer:
1335/// [C++0x] expression
1336/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001337StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001338 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001339 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001340
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001341 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001342 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001343 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001344 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001345 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001346
Chad Rosier67055f52012-07-10 21:35:27 +00001347 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1348 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001349
Chris Lattner2dd1b722007-08-26 23:08:06 +00001350 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1351 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001352 //
1353 // C++ 6.4p3:
1354 // A name introduced by a declaration in a condition is in scope from its
1355 // point of declaration until the end of the substatements controlled by the
1356 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001357 // C++ 3.3.2p4:
1358 // Names declared in the for-init-statement, and in the condition of if,
1359 // while, for, and switch statements are local to the if, while, for, or
1360 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001361 // C++ 6.5.3p1:
1362 // Names declared in the for-init-statement are in the same declarative-region
1363 // as those declared in the condition.
1364 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001365 unsigned ScopeFlags;
Chris Lattner934074c2009-04-22 00:54:41 +00001366 if (C99orCXXorObjC)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001367 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1368 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001369 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001370 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1371
1372 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001373
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001374 BalancedDelimiterTracker T(*this, tok::l_paren);
1375 T.consumeOpen();
1376
John McCalldadc5752010-08-24 06:29:42 +00001377 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001378
Richard Smith02e85f32011-04-14 22:09:26 +00001379 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001380 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001381 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001382 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001383 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001384 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001385 FullExprArg ThirdPart(Actions);
John McCall48871652010-08-21 09:40:31 +00001386 Decl *SecondVar = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001387
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001388 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001389 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001390 C99orCXXorObjC? Sema::PCC_ForInit
1391 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001392 cutOffParsing();
1393 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001394 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001395
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001396 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001397 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001398
Chris Lattner9075bd72006-08-10 04:59:57 +00001399 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001400 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001401 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001402 // no first part, eat the ';'.
1403 ConsumeToken();
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001404 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001405 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001406 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001407 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001408
Richard Smith02e85f32011-04-14 22:09:26 +00001409 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001410 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001411 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1412
Chris Lattner49836b42009-04-02 04:16:50 +00001413 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +00001414 StmtVector Stmts;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001415 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smith02e85f32011-04-14 22:09:26 +00001416 DeclEnd, attrs, false,
1417 MightBeForRangeStmt ?
1418 &ForRangeInit : 0);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001419 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001420
Richard Smith02e85f32011-04-14 22:09:26 +00001421 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001422 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001423 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001424
Richard Smith02e85f32011-04-14 22:09:26 +00001425 ForRange = true;
1426 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001427 ConsumeToken();
1428 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001429 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001430 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001431 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001432
Douglas Gregor68762e72010-08-23 21:17:50 +00001433 if (Tok.is(tok::code_completion)) {
1434 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001435 cutOffParsing();
1436 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001437 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001438 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001439 } else {
1440 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001441 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001442 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001443 ProhibitAttributes(attrs);
Chris Lattner89c50c62006-08-11 06:41:18 +00001444 Value = ParseExpression();
Chris Lattner71e23ce2006-11-04 20:18:38 +00001445
John McCall34376a62010-12-04 03:47:34 +00001446 ForEach = isTokIdentifier_in();
1447
Chris Lattnercd68f642007-06-27 01:06:29 +00001448 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001449 if (!Value.isInvalid()) {
1450 if (ForEach)
1451 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1452 else
Richard Smith945f8d32013-01-14 22:39:08 +00001453 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001454 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001455
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001456 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001457 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001458 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001459 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001460
Douglas Gregor68762e72010-08-23 21:17:50 +00001461 if (Tok.is(tok::code_completion)) {
1462 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001463 cutOffParsing();
1464 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001465 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001466 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001467 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001468 // User tried to write the reasonable, but ill-formed, for-range-statement
1469 // for (expr : expr) { ... }
1470 Diag(Tok, diag::err_for_range_expected_decl)
1471 << FirstPart.get()->getSourceRange();
1472 SkipUntil(tok::r_paren, false, true);
1473 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001474 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001475 if (!Value.isInvalid()) {
1476 Diag(Tok, diag::err_expected_semi_for);
1477 } else {
1478 // Skip until semicolon or rparen, don't consume it.
1479 SkipUntil(tok::r_paren, true, true);
1480 if (Tok.is(tok::semi))
1481 ConsumeToken();
1482 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001483 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001484 }
Richard Smith02e85f32011-04-14 22:09:26 +00001485 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001486 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001487 // Parse the second part of the for specifier.
1488 if (Tok.is(tok::semi)) { // for (...;;
1489 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001490 } else if (Tok.is(tok::r_paren)) {
1491 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001492 } else {
John McCalldadc5752010-08-24 06:29:42 +00001493 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001494 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001495 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1496 else {
1497 Second = ParseExpression();
1498 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001499 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001500 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001501 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001502 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001503 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001504 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001505
Douglas Gregor230a7e62011-02-17 03:38:46 +00001506 if (Tok.isNot(tok::semi)) {
1507 if (!SecondPartIsInvalid || SecondVar)
1508 Diag(Tok, diag::err_expected_semi_for);
1509 else
1510 // Skip until semicolon or rparen, don't consume it.
1511 SkipUntil(tok::r_paren, true, true);
1512 }
1513
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001514 if (Tok.is(tok::semi)) {
1515 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001516 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001517
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001518 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001519 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001520 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001521 // FIXME: The C++11 standard doesn't actually say that this is a
1522 // discarded-value expression, but it clearly should be.
1523 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001524 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001525 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001526 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001527 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001528
Richard Smith02e85f32011-04-14 22:09:26 +00001529 // We need to perform most of the semantic analysis for a C++0x for-range
1530 // statememt before parsing the body, in order to be able to deduce the type
1531 // of an auto-typed loop variable.
1532 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001533 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001534
John McCall53848232011-07-27 01:07:15 +00001535 if (ForRange) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001536 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smith02e85f32011-04-14 22:09:26 +00001537 ForRangeInit.ColonLoc,
1538 ForRangeInit.RangeExpr.get(),
Richard Smitha05b3b52012-09-20 21:52:32 +00001539 T.getCloseLocation(),
1540 Sema::BFRK_Build);
Richard Smith02e85f32011-04-14 22:09:26 +00001541
John McCall53848232011-07-27 01:07:15 +00001542
1543 // Similarly, we need to do the semantic analysis for a for-range
1544 // statement immediately in order to close over temporaries correctly.
1545 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001546 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001547 FirstPart.take(),
Chad Rosier67055f52012-07-10 21:35:27 +00001548 Collection.take(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001549 T.getCloseLocation());
John McCall53848232011-07-27 01:07:15 +00001550 }
1551
Chris Lattner8fb26252007-08-22 05:28:50 +00001552 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001553 // there is no compound stmt. C90 does not have this clause. We only do this
1554 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001555 //
1556 // C++ 6.5p2:
1557 // The substatement in an iteration-statement implicitly defines a local scope
1558 // which is entered and exited each time through the loop.
1559 //
1560 // See comments in ParseIfStatement for why we create a scope for
1561 // for-init-statement/condition and a new scope for substatement in C++.
1562 //
Mike Stump11289f42009-09-09 15:08:12 +00001563 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner934074c2009-04-22 00:54:41 +00001564 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001565
Chris Lattner9075bd72006-08-10 04:59:57 +00001566 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001567 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001568
Chris Lattner8fb26252007-08-22 05:28:50 +00001569 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001570 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001571
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001572 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001573 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001574
1575 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001576 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001577
Richard Smith02e85f32011-04-14 22:09:26 +00001578 if (ForEach)
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001579 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1580 Body.take());
Mike Stump11289f42009-09-09 15:08:12 +00001581
Richard Smith02e85f32011-04-14 22:09:26 +00001582 if (ForRange)
1583 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1584
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001585 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1586 SecondPart, SecondVar, ThirdPart,
1587 T.getCloseLocation(), Body.take());
Chris Lattner9075bd72006-08-10 04:59:57 +00001588}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001589
Chris Lattner503fadc2006-08-10 05:45:44 +00001590/// ParseGotoStatement
1591/// jump-statement:
1592/// 'goto' identifier ';'
1593/// [GNU] 'goto' '*' expression ';'
1594///
1595/// Note: this lets the caller parse the end ';'.
1596///
Richard Smithc202b282012-04-14 00:33:13 +00001597StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001598 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001599 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001600
John McCalldadc5752010-08-24 06:29:42 +00001601 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001602 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001603 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1604 Tok.getLocation());
1605 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001606 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001607 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001608 // GNU indirect goto extension.
1609 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001610 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001611 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001612 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Chris Lattnera0927ce2006-08-12 16:59:03 +00001613 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001614 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001615 }
John McCallb268a282010-08-23 23:25:46 +00001616 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001617 } else {
1618 Diag(Tok, diag::err_expected_ident);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001619 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001620 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001621
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001622 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001623}
1624
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001625/// ParseContinueStatement
1626/// jump-statement:
1627/// 'continue' ';'
1628///
1629/// Note: this lets the caller parse the end ';'.
1630///
Richard Smithc202b282012-04-14 00:33:13 +00001631StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001632 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001633 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001634}
1635
1636/// ParseBreakStatement
1637/// jump-statement:
1638/// 'break' ';'
1639///
1640/// Note: this lets the caller parse the end ';'.
1641///
Richard Smithc202b282012-04-14 00:33:13 +00001642StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001643 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001644 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001645}
1646
Chris Lattner503fadc2006-08-10 05:45:44 +00001647/// ParseReturnStatement
1648/// jump-statement:
1649/// 'return' expression[opt] ';'
Richard Smithc202b282012-04-14 00:33:13 +00001650StmtResult Parser::ParseReturnStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001651 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001652 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001653
John McCalldadc5752010-08-24 06:29:42 +00001654 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001655 if (Tok.isNot(tok::semi)) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001656 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001657 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001658 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001659 return StmtError();
1660 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001661
David Blaikiebbafb8a2012-03-11 07:00:24 +00001662 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001663 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001664 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001665 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001666 diag::warn_cxx98_compat_generalized_initializer_lists :
1667 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001668 << R.get()->getSourceRange();
1669 } else
1670 R = ParseExpression();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001671 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Chris Lattnera0927ce2006-08-12 16:59:03 +00001672 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001673 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001674 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001675 }
John McCallb268a282010-08-23 23:25:46 +00001676 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Chris Lattner503fadc2006-08-10 05:45:44 +00001677}
Chris Lattner0116c472006-08-15 06:03:28 +00001678
John McCallf413f5e2013-05-03 00:10:13 +00001679namespace {
1680 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1681 Parser &TheParser;
1682 SourceLocation AsmLoc;
1683 StringRef AsmString;
1684
1685 /// The tokens we streamed into AsmString and handed off to MC.
1686 ArrayRef<Token> AsmToks;
1687
1688 /// The offset of each token in AsmToks within AsmString.
1689 ArrayRef<unsigned> AsmTokOffsets;
1690
1691 public:
1692 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1693 StringRef AsmString,
1694 ArrayRef<Token> Toks,
1695 ArrayRef<unsigned> Offsets)
1696 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1697 AsmToks(Toks), AsmTokOffsets(Offsets) {
1698 assert(AsmToks.size() == AsmTokOffsets.size());
1699 }
1700
1701 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1702 InlineAsmIdentifierInfo &Info,
1703 bool IsUnevaluatedContext) {
1704 // Collect the desired tokens.
1705 SmallVector<Token, 16> LineToks;
1706 const Token *FirstOrigToken = 0;
1707 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1708
1709 unsigned NumConsumedToks;
1710 ExprResult Result =
1711 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1712 IsUnevaluatedContext);
1713
1714 // If we consumed the entire line, tell MC that.
1715 // Also do this if we consumed nothing as a way of reporting failure.
1716 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1717 // By not modifying LineBuf, we're implicitly consuming it all.
1718
1719 // Otherwise, consume up to the original tokens.
1720 } else {
1721 assert(FirstOrigToken && "not using original tokens?");
1722
1723 // Since we're using original tokens, apply that offset.
1724 assert(FirstOrigToken[NumConsumedToks].getLocation()
1725 == LineToks[NumConsumedToks].getLocation());
1726 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1727 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1728
1729 // The total length we've consumed is the relative offset
1730 // of the last token we consumed plus its length.
1731 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1732 + AsmToks[LastIndex].getLength()
1733 - AsmTokOffsets[FirstIndex]);
1734 LineBuf = LineBuf.substr(0, TotalOffset);
1735 }
1736
1737 // Initialize the "decl" with the lookup result.
1738 Info.OpDecl = static_cast<void*>(Result.take());
1739 return Info.OpDecl;
1740 }
1741
1742 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1743 unsigned &Offset) {
1744 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1745 Offset, AsmLoc);
1746 }
1747
1748 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1749 void *Context) {
1750 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1751 }
1752
1753 private:
1754 /// Collect the appropriate tokens for the given string.
1755 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1756 const Token *&FirstOrigToken) const {
1757 // For now, assert that the string we're working with is a substring
1758 // of what we gave to MC. This lets us use the original tokens.
1759 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1760 !std::less<const char*>()(AsmString.end(), Str.end()));
1761
1762 // Try to find a token whose offset matches the first token.
1763 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1764 const unsigned *FirstTokOffset
1765 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1766 FirstCharOffset);
1767
1768 // For now, assert that the start of the string exactly
1769 // corresponds to the start of a token.
1770 assert(*FirstTokOffset == FirstCharOffset);
1771
1772 // Use all the original tokens for this line. (We assume the
1773 // end of the line corresponds cleanly to a token break.)
1774 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1775 FirstOrigToken = &AsmToks[FirstTokIndex];
1776 unsigned LastCharOffset = Str.end() - AsmString.begin();
1777 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1778 if (AsmTokOffsets[i] >= LastCharOffset) break;
1779 TempToks.push_back(AsmToks[i]);
1780 }
1781 }
1782
1783 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1784 // Compute an offset into the inline asm buffer.
1785 // FIXME: This isn't right if .macro is involved (but hopefully, no
1786 // real-world code does that).
1787 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1788 const llvm::MemoryBuffer *LBuf =
1789 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1790 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1791
1792 // Figure out which token that offset points into.
1793 const unsigned *TokOffsetPtr =
1794 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1795 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1796 unsigned TokOffset = *TokOffsetPtr;
1797
1798 // If we come up with an answer which seems sane, use it; otherwise,
1799 // just point at the __asm keyword.
1800 // FIXME: Assert the answer is sane once we handle .macro correctly.
1801 SourceLocation Loc = AsmLoc;
1802 if (TokIndex < AsmToks.size()) {
1803 const Token &Tok = AsmToks[TokIndex];
1804 Loc = Tok.getLocation();
1805 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1806 }
1807 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1808 << D.getMessage();
1809 }
1810 };
1811}
1812
1813/// Parse an identifier in an MS-style inline assembly block.
1814///
1815/// \param CastInfo - a void* so that we don't have to teach Parser.h
1816/// about the actual type.
1817ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1818 unsigned &NumLineToksConsumed,
1819 void *CastInfo,
1820 bool IsUnevaluatedContext) {
1821 llvm::InlineAsmIdentifierInfo &Info =
1822 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1823
1824 // Push a fake token on the end so that we don't overrun the token
1825 // stream. We use ';' because it expression-parsing should never
1826 // overrun it.
1827 const tok::TokenKind EndOfStream = tok::semi;
1828 Token EndOfStreamTok;
1829 EndOfStreamTok.startToken();
1830 EndOfStreamTok.setKind(EndOfStream);
1831 LineToks.push_back(EndOfStreamTok);
1832
1833 // Also copy the current token over.
1834 LineToks.push_back(Tok);
1835
1836 PP.EnterTokenStream(LineToks.begin(),
1837 LineToks.size(),
1838 /*disable macros*/ true,
1839 /*owns tokens*/ false);
1840
1841 // Clear the current token and advance to the first token in LineToks.
1842 ConsumeAnyToken();
1843
1844 // Parse an optional scope-specifier if we're in C++.
1845 CXXScopeSpec SS;
1846 if (getLangOpts().CPlusPlus) {
1847 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1848 }
1849
1850 // Require an identifier here.
1851 SourceLocation TemplateKWLoc;
1852 UnqualifiedId Id;
1853 bool Invalid = ParseUnqualifiedId(SS,
1854 /*EnteringContext=*/false,
1855 /*AllowDestructorName=*/false,
1856 /*AllowConstructorName=*/false,
1857 /*ObjectType=*/ ParsedType(),
1858 TemplateKWLoc,
1859 Id);
1860
1861 // If we've run into the poison token we inserted before, or there
1862 // was a parsing error, then claim the entire line.
1863 if (Invalid || Tok.is(EndOfStream)) {
1864 NumLineToksConsumed = LineToks.size() - 2;
1865
1866 // Otherwise, claim up to the start of the next token.
1867 } else {
1868 // Figure out how many tokens we are into LineToks.
1869 unsigned LineIndex = 0;
1870 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1871 LineIndex++;
1872 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1873 }
1874
1875 NumLineToksConsumed = LineIndex;
1876 }
1877
1878 // Finally, restore the old parsing state by consuming all the
1879 // tokens we staged before, implicitly killing off the
1880 // token-lexer we pushed.
1881 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1882 ConsumeAnyToken();
1883 }
1884 ConsumeToken(EndOfStream);
1885
1886 // Leave LineToks in its original state.
1887 LineToks.pop_back();
1888 LineToks.pop_back();
1889
1890 // Perform the lookup.
1891 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1892 IsUnevaluatedContext);
1893}
1894
1895/// Turn a sequence of our tokens back into a string that we can hand
1896/// to the MC asm parser.
1897static bool buildMSAsmString(Preprocessor &PP,
1898 SourceLocation AsmLoc,
1899 ArrayRef<Token> AsmToks,
1900 SmallVectorImpl<unsigned> &TokOffsets,
1901 SmallString<512> &Asm) {
1902 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1903
1904 // Is this the start of a new assembly statement?
1905 bool isNewStatement = true;
1906
1907 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1908 const Token &Tok = AsmToks[i];
1909
1910 // Start each new statement with a newline and a tab.
1911 if (!isNewStatement &&
1912 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1913 Asm += "\n\t";
1914 isNewStatement = true;
1915 }
1916
1917 // Preserve the existence of leading whitespace except at the
1918 // start of a statement.
1919 if (!isNewStatement && Tok.hasLeadingSpace())
1920 Asm += ' ';
1921
1922 // Remember the offset of this token.
1923 TokOffsets.push_back(Asm.size());
1924
1925 // Don't actually write '__asm' into the assembly stream.
1926 if (Tok.is(tok::kw_asm)) {
1927 // Complain about __asm at the end of the stream.
1928 if (i + 1 == e) {
1929 PP.Diag(AsmLoc, diag::err_asm_empty);
1930 return true;
1931 }
1932
1933 continue;
1934 }
1935
1936 // Append the spelling of the token.
1937 SmallString<32> SpellingBuffer;
1938 bool SpellingInvalid = false;
1939 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
1940 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
1941
1942 // We are no longer at the start of a statement.
1943 isNewStatement = false;
1944 }
1945
1946 // Ensure that the buffer is null-terminated.
1947 Asm.push_back('\0');
1948 Asm.pop_back();
1949
1950 assert(TokOffsets.size() == AsmToks.size());
1951 return false;
1952}
1953
Eli Friedmana4b02c32011-09-30 01:13:51 +00001954/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1955/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier32503022012-06-11 20:47:18 +00001956///
1957/// [MS] ms-asm-statement:
1958/// ms-asm-block
1959/// ms-asm-block ms-asm-statement
1960///
1961/// [MS] ms-asm-block:
1962/// '__asm' ms-asm-line '\n'
1963/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1964///
1965/// [MS] ms-asm-instruction-block
1966/// ms-asm-line
1967/// ms-asm-line '\n' ms-asm-instruction-block
1968///
Eli Friedmana4b02c32011-09-30 01:13:51 +00001969StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1970 SourceManager &SrcMgr = PP.getSourceManager();
1971 SourceLocation EndLoc = AsmLoc;
Chad Rosier32503022012-06-11 20:47:18 +00001972 SmallVector<Token, 4> AsmToks;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00001973
1974 bool InBraces = false;
1975 unsigned short savedBraceCount = 0;
1976 bool InAsmComment = false;
1977 FileID FID;
1978 unsigned LineNo = 0;
1979 unsigned NumTokensRead = 0;
1980 SourceLocation LBraceLoc;
1981
1982 if (Tok.is(tok::l_brace)) {
1983 // Braced inline asm: consume the opening brace.
1984 InBraces = true;
1985 savedBraceCount = BraceCount;
1986 EndLoc = LBraceLoc = ConsumeBrace();
1987 ++NumTokensRead;
1988 } else {
1989 // Single-line inline asm; compute which line it is on.
1990 std::pair<FileID, unsigned> ExpAsmLoc =
1991 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1992 FID = ExpAsmLoc.first;
1993 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1994 }
1995
1996 SourceLocation TokLoc = Tok.getLocation();
Eli Friedmana4b02c32011-09-30 01:13:51 +00001997 do {
Chad Rosierc97a6bb2012-08-14 19:22:06 +00001998 // If we hit EOF, we're done, period.
1999 if (Tok.is(tok::eof))
Eli Friedmana4b02c32011-09-30 01:13:51 +00002000 break;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002001
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002002 if (!InAsmComment && Tok.is(tok::semi)) {
2003 // A semicolon in an asm is the start of a comment.
2004 InAsmComment = true;
2005 if (InBraces) {
2006 // Compute which line the comment is on.
2007 std::pair<FileID, unsigned> ExpSemiLoc =
2008 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2009 FID = ExpSemiLoc.first;
2010 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2011 }
2012 } else if (!InBraces || InAsmComment) {
2013 // If end-of-line is significant, check whether this token is on a
2014 // new line.
2015 std::pair<FileID, unsigned> ExpLoc =
2016 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2017 if (ExpLoc.first != FID ||
2018 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2019 // If this is a single-line __asm, we're done.
2020 if (!InBraces)
2021 break;
2022 // We're no longer in a comment.
2023 InAsmComment = false;
2024 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2025 // Single-line asm always ends when a closing brace is seen.
2026 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2027 // does MSVC do here?
2028 break;
2029 }
2030 }
2031 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2032 BraceCount == (savedBraceCount + 1)) {
2033 // Consume the closing brace, and finish
2034 EndLoc = ConsumeBrace();
2035 break;
2036 }
2037
2038 // Consume the next token; make sure we don't modify the brace count etc.
2039 // if we are in a comment.
2040 EndLoc = TokLoc;
2041 if (InAsmComment)
2042 PP.Lex(Tok);
2043 else {
2044 AsmToks.push_back(Tok);
2045 ConsumeAnyToken();
2046 }
2047 TokLoc = Tok.getLocation();
2048 ++NumTokensRead;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002049 } while (1);
Chad Rosier32503022012-06-11 20:47:18 +00002050
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002051 if (InBraces && BraceCount != savedBraceCount) {
2052 // __asm without closing brace (this can happen at EOF).
2053 Diag(Tok, diag::err_expected_rbrace);
2054 Diag(LBraceLoc, diag::note_matching) << "{";
2055 return StmtError();
2056 } else if (NumTokensRead == 0) {
2057 // Empty __asm.
2058 Diag(Tok, diag::err_expected_lbrace);
2059 return StmtError();
2060 }
2061
John McCallf413f5e2013-05-03 00:10:13 +00002062 // Okay, prepare to use MC to parse the assembly.
2063 SmallVector<StringRef, 4> ConstraintRefs;
2064 SmallVector<Expr*, 4> Exprs;
2065 SmallVector<StringRef, 4> ClobberRefs;
2066
2067 // We need an actual supported target.
2068 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2069 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
2070 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2071 ArchTy != llvm::Triple::x86_64);
2072 if (UnsupportedArch)
2073 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
2074
2075 // If we don't support assembly, or the assembly is empty, we don't
2076 // need to instantiate the AsmParser, etc.
2077 if (UnsupportedArch || AsmToks.empty()) {
2078 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2079 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2080 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2081 }
2082
2083 // Expand the tokens into a string buffer.
2084 SmallString<512> AsmString;
2085 SmallVector<unsigned, 8> TokOffsets;
2086 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2087 return StmtError();
2088
2089 // Find the target and create the target specific parser.
2090 std::string Error;
2091 const std::string &TT = TheTriple.getTriple();
2092 const llvm::Target *TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2093
John McCallf413f5e2013-05-03 00:10:13 +00002094 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
Rafael Espindola77056232013-05-13 01:24:18 +00002095 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002096 // Get the instruction descriptor.
2097 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
John McCallf413f5e2013-05-03 00:10:13 +00002098 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2099 OwningPtr<llvm::MCSubtargetInfo>
2100 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2101
2102 llvm::SourceMgr TempSrcMgr;
Bill Wendlingda1e3e72013-06-18 07:22:05 +00002103 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallf413f5e2013-05-03 00:10:13 +00002104 llvm::MemoryBuffer *Buffer =
2105 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2106
2107 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2108 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2109
2110 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2111 OwningPtr<llvm::MCAsmParser>
2112 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2113 OwningPtr<llvm::MCTargetAsmParser>
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002114 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser, *MII));
John McCallf413f5e2013-05-03 00:10:13 +00002115
John McCallf413f5e2013-05-03 00:10:13 +00002116 llvm::MCInstPrinter *IP =
2117 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2118
2119 // Change to the Intel dialect.
2120 Parser->setAssemblerDialect(1);
2121 Parser->setTargetParser(*TargetParser.get());
2122 Parser->setParsingInlineAsm(true);
2123 TargetParser->setParsingInlineAsm(true);
2124
2125 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2126 AsmToks, TokOffsets);
2127 TargetParser->setSemaCallback(&Callback);
2128 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2129 &Callback);
2130
2131 unsigned NumOutputs;
2132 unsigned NumInputs;
2133 std::string AsmStringIR;
2134 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2135 SmallVector<std::string, 4> Constraints;
2136 SmallVector<std::string, 4> Clobbers;
2137 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2138 NumOutputs, NumInputs, OpExprs, Constraints,
2139 Clobbers, MII, IP, Callback))
2140 return StmtError();
2141
2142 // Build the vector of clobber StringRefs.
2143 unsigned NumClobbers = Clobbers.size();
2144 ClobberRefs.resize(NumClobbers);
2145 for (unsigned i = 0; i != NumClobbers; ++i)
2146 ClobberRefs[i] = StringRef(Clobbers[i]);
2147
2148 // Recast the void pointers and build the vector of constraint StringRefs.
2149 unsigned NumExprs = NumOutputs + NumInputs;
2150 ConstraintRefs.resize(NumExprs);
2151 Exprs.resize(NumExprs);
2152 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2153 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2154 if (!OpExpr)
2155 return StmtError();
2156
2157 // Need address of variable.
2158 if (OpExprs[i].second)
2159 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2160 .take();
2161
2162 ConstraintRefs[i] = StringRef(Constraints[i]);
2163 Exprs[i] = OpExpr;
2164 }
2165
Chad Rosierc6c71332012-08-06 20:03:45 +00002166 // FIXME: We should be passing source locations for better diagnostics.
John McCallf413f5e2013-05-03 00:10:13 +00002167 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2168 NumOutputs, NumInputs,
2169 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002170}
2171
Chris Lattner0116c472006-08-15 06:03:28 +00002172/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff69e8f9e2008-02-11 23:15:56 +00002173/// asm-statement:
2174/// gnu-asm-statement
2175/// ms-asm-statement
2176///
2177/// [GNU] gnu-asm-statement:
Chris Lattner0116c472006-08-15 06:03:28 +00002178/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2179///
2180/// [GNU] asm-argument:
2181/// asm-string-literal
2182/// asm-string-literal ':' asm-operands[opt]
2183/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2184/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2185/// ':' asm-clobbers
2186///
2187/// [GNU] asm-clobbers:
2188/// asm-string-literal
2189/// asm-clobbers ',' asm-string-literal
2190///
John McCalldadc5752010-08-24 06:29:42 +00002191StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002192 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattner73c56c02007-10-29 04:04:16 +00002193 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002194
Chad Rosierc8e56e82012-12-05 21:08:21 +00002195 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosier67055f52012-07-10 21:35:27 +00002196 !isTypeQualifier()) {
Steve Naroffb2c80c72008-02-07 03:50:06 +00002197 msAsm = true;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002198 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002199 }
John McCall084e83d2011-03-24 11:26:52 +00002200 DeclSpec DS(AttrFactory);
Chris Lattner0116c472006-08-15 06:03:28 +00002201 SourceLocation Loc = Tok.getLocation();
Alexis Hunt96d5c762009-11-21 08:43:09 +00002202 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002203
Chris Lattner0116c472006-08-15 06:03:28 +00002204 // GNU asms accept, but warn, about type-qualifiers other than volatile.
Chris Lattnera925dc62006-11-28 04:33:46 +00002205 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner6d29c102008-11-18 07:48:38 +00002206 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Chris Lattnera925dc62006-11-28 04:33:46 +00002207 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner6d29c102008-11-18 07:48:38 +00002208 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith8e1ac332013-03-28 01:55:44 +00002209 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2210 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2211 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redlb62406f2008-12-11 19:48:14 +00002212
Chris Lattner0116c472006-08-15 06:03:28 +00002213 // Remember if this was a volatile asm.
Anders Carlsson660bdd12007-11-23 23:12:25 +00002214 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002215 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002216 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Chris Lattner0116c472006-08-15 06:03:28 +00002217 SkipUntil(tok::r_paren);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002218 return StmtError();
Chris Lattner0116c472006-08-15 06:03:28 +00002219 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002220 BalancedDelimiterTracker T(*this, tok::l_paren);
2221 T.consumeOpen();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002222
John McCalldadc5752010-08-24 06:29:42 +00002223 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002224 if (AsmString.isInvalid()) {
Richard Smithd67aea22012-03-06 03:21:47 +00002225 // Consume up to and including the closing paren.
2226 T.skipToEnd();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002227 return StmtError();
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002228 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002229
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002230 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002231 ExprVector Constraints;
2232 ExprVector Exprs;
2233 ExprVector Clobbers;
Chris Lattner0116c472006-08-15 06:03:28 +00002234
Anders Carlsson19fe1162008-02-05 23:03:50 +00002235 if (Tok.is(tok::r_paren)) {
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002236 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002237 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002238 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2239 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2240 Constraints, Exprs, AsmString.take(),
2241 Clobbers, T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002242 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002243
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002244 // Parse Outputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002245 bool AteExtraColon = false;
2246 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2247 // In C++ mode, parse "::" like ": :".
2248 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002249 ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002250
Chris Lattner15768502009-12-20 23:08:04 +00002251 if (!AteExtraColon &&
2252 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002253 return StmtError();
2254 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002255
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002256 unsigned NumOutputs = Names.size();
2257
2258 // Parse Inputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002259 if (AteExtraColon ||
2260 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2261 // In C++ mode, parse "::" like ": :".
2262 if (AteExtraColon)
2263 AteExtraColon = false;
2264 else {
2265 AteExtraColon = Tok.is(tok::coloncolon);
2266 ConsumeToken();
2267 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002268
Chris Lattner15768502009-12-20 23:08:04 +00002269 if (!AteExtraColon &&
2270 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002271 return StmtError();
2272 }
2273
2274 assert(Names.size() == Constraints.size() &&
2275 Constraints.size() == Exprs.size() &&
2276 "Input operand size mismatch!");
2277
2278 unsigned NumInputs = Names.size() - NumOutputs;
2279
2280 // Parse the clobbers, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002281 if (AteExtraColon || Tok.is(tok::colon)) {
2282 if (!AteExtraColon)
2283 ConsumeToken();
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002284
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002285 // Parse the asm-string list for clobbers if present.
2286 if (Tok.isNot(tok::r_paren)) {
2287 while (1) {
John McCalldadc5752010-08-24 06:29:42 +00002288 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002289
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002290 if (Clobber.isInvalid())
2291 break;
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002292
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002293 Clobbers.push_back(Clobber.release());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002294
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002295 if (Tok.isNot(tok::comma)) break;
2296 ConsumeToken();
2297 }
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002298 }
2299 }
2300
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002301 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002302 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2303 NumInputs, Names.data(), Constraints, Exprs,
2304 AsmString.take(), Clobbers,
2305 T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002306}
2307
2308/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002309/// asm-statement, assuming the leading ':' token was eaten.
Chris Lattner0116c472006-08-15 06:03:28 +00002310///
2311/// [GNU] asm-operands:
2312/// asm-operand
2313/// asm-operands ',' asm-operand
2314///
2315/// [GNU] asm-operand:
2316/// asm-string-literal '(' expression ')'
2317/// '[' identifier ']' asm-string-literal '(' expression ')'
2318///
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00002319//
2320// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002321bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieu2bd04012011-09-09 02:00:50 +00002322 SmallVectorImpl<Expr *> &Constraints,
2323 SmallVectorImpl<Expr *> &Exprs) {
Chris Lattner0116c472006-08-15 06:03:28 +00002324 // 'asm-operands' isn't present?
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002325 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002326 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002327
2328 while (1) {
Chris Lattner0116c472006-08-15 06:03:28 +00002329 // Read the [id] if present.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002330 if (Tok.is(tok::l_square)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002331 BalancedDelimiterTracker T(*this, tok::l_square);
2332 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00002333
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002334 if (Tok.isNot(tok::identifier)) {
Chris Lattner0116c472006-08-15 06:03:28 +00002335 Diag(Tok, diag::err_expected_ident);
2336 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002337 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002338 }
Mike Stump11289f42009-09-09 15:08:12 +00002339
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002340 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner645ff3f2007-10-29 04:06:22 +00002341 ConsumeToken();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002342
Anders Carlsson9a020f92010-01-30 22:25:16 +00002343 Names.push_back(II);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002344 T.consumeClose();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002345 } else
Anders Carlsson9a020f92010-01-30 22:25:16 +00002346 Names.push_back(0);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002347
John McCalldadc5752010-08-24 06:29:42 +00002348 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002349 if (Constraint.isInvalid()) {
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002350 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002351 return true;
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002352 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002353 Constraints.push_back(Constraint.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002354
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002355 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002356 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Chris Lattner0116c472006-08-15 06:03:28 +00002357 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002358 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002359 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002360
Chris Lattner0116c472006-08-15 06:03:28 +00002361 // Read the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002362 BalancedDelimiterTracker T(*this, tok::l_paren);
2363 T.consumeOpen();
John McCalldadc5752010-08-24 06:29:42 +00002364 ExprResult Res(ParseExpression());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002365 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002366 if (Res.isInvalid()) {
Chris Lattner0116c472006-08-15 06:03:28 +00002367 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002368 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002369 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002370 Exprs.push_back(Res.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002371 // Eat the comma and continue parsing if it exists.
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002372 if (Tok.isNot(tok::comma)) return false;
Chris Lattner0116c472006-08-15 06:03:28 +00002373 ConsumeToken();
2374 }
2375}
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002376
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002377Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002378 assert(Tok.is(tok::l_brace));
2379 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002380
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00002381 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00002382 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002383 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002384 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002385 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002386
John McCallfaf5fb42010-08-26 23:41:50 +00002387 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2388 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002389
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002390 // Do not enter a scope for the brace, as the arguments are in the same scope
2391 // (the function body) as the body itself. Instead, just read the statement
2392 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002393 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002394
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002395 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002396 if (FnBody.isInvalid()) {
2397 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002398 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002399 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002400
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002401 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002402 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002403}
Sebastian Redlb219c902008-12-21 16:41:36 +00002404
Sebastian Redla7b98a72009-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 Gregora0ff0c32011-03-16 17:05:57 +00002410Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002411 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2412 SourceLocation TryLoc = ConsumeToken();
2413
John McCallfaf5fb42010-08-26 23:41:50 +00002414 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2415 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002416
2417 // Constructor initializer list?
2418 if (Tok.is(tok::colon))
2419 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002420 else
2421 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002422
Richard Smith1ab34b32012-11-19 21:13:18 +00002423 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2424 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002425 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002426 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002427 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002428
Sebastian Redld98ecd62009-04-26 21:08:36 +00002429 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002430 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-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 Gribenko800ddf32012-02-14 22:14:32 +00002433 if (FnBody.isInvalid()) {
2434 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002435 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002436 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002437
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002438 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002439 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002440}
2441
Erik Verbruggen6e922512012-04-12 10:11:59 +00002442bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002443 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00002444 assert(SkipFunctionBodies &&
2445 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002446
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002447 if (!PP.isCodeCompletionEnabled()) {
2448 ConsumeBrace();
2449 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false);
2450 return true;
2451 }
2452
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002453 // We're in code-completion mode. Skip parsing for all function bodies unless
2454 // the body contains the code-completion point.
2455 TentativeParsingAction PA(*this);
2456 ConsumeBrace();
2457 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002458 /*StopAtCodeCompletion=*/true)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002459 PA.Commit();
2460 return true;
2461 }
2462
2463 PA.Revert();
2464 return false;
2465}
2466
Sebastian Redlb219c902008-12-21 16:41:36 +00002467/// ParseCXXTryBlock - Parse a C++ try-block.
2468///
2469/// try-block:
2470/// 'try' compound-statement handler-seq
2471///
Richard Smithc202b282012-04-14 00:33:13 +00002472StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002473 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2474
2475 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002476 return ParseCXXTryBlockCommon(TryLoc);
2477}
2478
2479/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2480/// function-try-block.
2481///
2482/// try-block:
2483/// 'try' compound-statement handler-seq
2484///
2485/// function-try-block:
2486/// 'try' ctor-initializer[opt] compound-statement handler-seq
2487///
2488/// handler-seq:
2489/// handler handler-seq[opt]
2490///
John Wiegley1c0675e2011-04-28 01:08:34 +00002491/// [Borland] try-block:
2492/// 'try' compound-statement seh-except-block
2493/// 'try' compound-statment seh-finally-block
2494///
David Blaikie1c9c9042012-11-10 01:04:23 +00002495StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002496 if (Tok.isNot(tok::l_brace))
2497 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Alexis Hunt96d5c762009-11-21 08:43:09 +00002498 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002499
2500 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikie3403feb2012-11-13 18:51:45 +00002501 Scope::DeclScope | Scope::TryScope |
2502 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002503 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002504 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002505
John Wiegley1c0675e2011-04-28 01:08:34 +00002506 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002507
Richard Smithc202b282012-04-14 00:33:13 +00002508 if ((Tok.is(tok::identifier) &&
2509 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2510 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002511 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2512 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002513 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002514 SourceLocation Loc = ConsumeToken();
2515 Handler = ParseSEHExceptBlock(Loc);
2516 }
2517 else {
2518 SourceLocation Loc = ConsumeToken();
2519 Handler = ParseSEHFinallyBlock(Loc);
2520 }
2521 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002522 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002523
John Wiegley1c0675e2011-04-28 01:08:34 +00002524 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2525 TryLoc,
2526 TryBlock.take(),
2527 Handler.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002528 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002529 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002530 StmtVector Handlers;
Richard Smithc202b282012-04-14 00:33:13 +00002531 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002532 MaybeParseCXX11Attributes(attrs);
John Wiegley1c0675e2011-04-28 01:08:34 +00002533 ProhibitAttributes(attrs);
Sebastian Redlb219c902008-12-21 16:41:36 +00002534
John Wiegley1c0675e2011-04-28 01:08:34 +00002535 if (Tok.isNot(tok::kw_catch))
2536 return StmtError(Diag(Tok, diag::err_expected_catch));
2537 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002538 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002539 if (!Handler.isInvalid())
2540 Handlers.push_back(Handler.release());
2541 }
2542 // Don't bother creating the full statement if we don't have any usable
2543 // handlers.
2544 if (Handlers.empty())
2545 return StmtError();
2546
Robert Wilhelmcafda822013-08-22 09:20:03 +00002547 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002548 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002549}
2550
2551/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2552///
Richard Smith1dba27c2013-01-29 09:02:09 +00002553/// handler:
2554/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002555///
Richard Smith1dba27c2013-01-29 09:02:09 +00002556/// exception-declaration:
2557/// attribute-specifier-seq[opt] type-specifier-seq declarator
2558/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2559/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002560///
David Blaikie1c9c9042012-11-10 01:04:23 +00002561StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002562 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2563
2564 SourceLocation CatchLoc = ConsumeToken();
2565
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002566 BalancedDelimiterTracker T(*this, tok::l_paren);
2567 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redlb219c902008-12-21 16:41:36 +00002568 return StmtError();
2569
2570 // C++ 3.3.2p3:
2571 // The name in a catch exception-declaration is local to the handler and
2572 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002573 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002574 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002575
2576 // exception-declaration is equivalent to '...' or a parameter-declaration
2577 // without default arguments.
John McCall48871652010-08-21 09:40:31 +00002578 Decl *ExceptionDecl = 0;
Sebastian Redlb219c902008-12-21 16:41:36 +00002579 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002580 ParsedAttributesWithRange Attributes(AttrFactory);
2581 MaybeParseCXX11Attributes(Attributes);
2582
John McCall084e83d2011-03-24 11:26:52 +00002583 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002584 DS.takeAttributesFrom(Attributes);
2585
Sebastian Redl54c04d42008-12-22 19:15:10 +00002586 if (ParseCXXTypeSpecifierSeq(DS))
2587 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002588
Sebastian Redlb219c902008-12-21 16:41:36 +00002589 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2590 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002591 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002592 } else
2593 ConsumeToken();
2594
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002595 T.consumeClose();
2596 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002597 return StmtError();
2598
2599 if (Tok.isNot(tok::l_brace))
2600 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2601
Alexis Hunt96d5c762009-11-21 08:43:09 +00002602 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002603 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002604 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002605 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002606
John McCallb268a282010-08-23 23:25:46 +00002607 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002608}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002609
2610void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002611 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002612 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002613 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002614
Douglas Gregor43edb322011-10-24 22:31:10 +00002615 // Handle dependent statements by parsing the braces as a compound statement.
2616 // This is not the same behavior as Visual C++, which don't treat this as a
2617 // compound statement, but for Clang's type checking we can't have anything
2618 // inside these braces escaping to the surrounding code.
2619 if (Result.Behavior == IEB_Dependent) {
2620 if (!Tok.is(tok::l_brace)) {
2621 Diag(Tok, diag::err_expected_lbrace);
Richard Smithc202b282012-04-14 00:33:13 +00002622 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002623 }
Richard Smithc202b282012-04-14 00:33:13 +00002624
2625 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002626 if (Compound.isInvalid())
2627 return;
Richard Smithc202b282012-04-14 00:33:13 +00002628
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002629 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2630 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002631 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002632 Result.Name,
2633 Compound.get());
2634 if (DepResult.isUsable())
2635 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002636 return;
2637 }
Richard Smithc202b282012-04-14 00:33:13 +00002638
Douglas Gregor43edb322011-10-24 22:31:10 +00002639 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2640 if (Braces.consumeOpen()) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002641 Diag(Tok, diag::err_expected_lbrace);
2642 return;
2643 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002644
Douglas Gregor43edb322011-10-24 22:31:10 +00002645 switch (Result.Behavior) {
2646 case IEB_Parse:
2647 // Parse the statements below.
2648 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002649
Douglas Gregor43edb322011-10-24 22:31:10 +00002650 case IEB_Dependent:
2651 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002652
Douglas Gregor43edb322011-10-24 22:31:10 +00002653 case IEB_Skip:
2654 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002655 return;
2656 }
2657
2658 // Condition is true, parse the statements.
2659 while (Tok.isNot(tok::r_brace)) {
2660 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2661 if (R.isUsable())
2662 Stmts.push_back(R.release());
2663 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002664 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002665}