blob: b74ab2556911bf9df92862f234a7679876ed9204 [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:
306 return HandlePragmaCaptured();
307
Alexey Bataeva769e072013-03-22 06:34:35 +0000308 case tok::annot_pragma_openmp:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000309 return ParseOpenMPDeclarativeOrExecutableDirective();
310
Sebastian Redlb219c902008-12-21 16:41:36 +0000311 }
312
Chris Lattner503fadc2006-08-10 05:45:44 +0000313 // If we reached this code, the statement must end in a semicolon.
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000314 if (Tok.is(tok::semi)) {
Chris Lattner503fadc2006-08-10 05:45:44 +0000315 ConsumeToken();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000316 } else if (!Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000317 // If the result was valid, then we do want to diagnose this. Use
318 // ExpectAndConsume to emit the diagnostic, even though we know it won't
319 // succeed.
320 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000321 // Skip until we see a } or ;, but don't eat it.
322 SkipUntil(tok::r_brace, true, true);
Chris Lattner503fadc2006-08-10 05:45:44 +0000323 }
Mike Stump11289f42009-09-09 15:08:12 +0000324
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000325 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000326}
327
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000328/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000329StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000330 // If a case keyword is missing, this is where it should be inserted.
331 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000332
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000333 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000334 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000335 if (Expr.isInvalid()) {
336 // If the expression is invalid, skip ahead to the next semicolon or '}'.
337 // Not doing this opens us up to the possibility of infinite loops if
338 // ParseExpression does not consume any tokens.
339 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
340 if (Tok.is(tok::semi))
341 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000342 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000343 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000344
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000345 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
346 Actions.CheckCaseExpression(Expr.get())) {
347 // If a constant expression is followed by a colon inside a switch block,
348 // suggest a missing case keyword.
349 Diag(OldToken, diag::err_expected_case_before_expression)
350 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000351
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000352 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000353 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000354 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000355
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000356 // Otherwise, eat the semicolon.
357 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000358 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000359}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000360
Richard Smithc202b282012-04-14 00:33:13 +0000361StmtResult Parser::ParseSEHTryBlock() {
John Wiegley1c0675e2011-04-28 01:08:34 +0000362 assert(Tok.is(tok::kw___try) && "Expected '__try'");
363 SourceLocation Loc = ConsumeToken();
364 return ParseSEHTryBlockCommon(Loc);
365}
366
367/// ParseSEHTryBlockCommon
368///
369/// seh-try-block:
370/// '__try' compound-statement seh-handler
371///
372/// seh-handler:
373/// seh-except-block
374/// seh-finally-block
375///
376StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
377 if(Tok.isNot(tok::l_brace))
378 return StmtError(Diag(Tok,diag::err_expected_lbrace));
379
Joao Matos566359c2012-09-04 17:49:35 +0000380 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000381 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000382 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000383
384 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000385 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000386 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000387 SourceLocation Loc = ConsumeToken();
388 Handler = ParseSEHExceptBlock(Loc);
389 } else if (Tok.is(tok::kw___finally)) {
390 SourceLocation Loc = ConsumeToken();
391 Handler = ParseSEHFinallyBlock(Loc);
392 } else {
393 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
394 }
395
396 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000397 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000398
399 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
400 TryLoc,
401 TryBlock.take(),
402 Handler.take());
403}
404
405/// ParseSEHExceptBlock - Handle __except
406///
407/// seh-except-block:
408/// '__except' '(' seh-filter-expression ')' compound-statement
409///
410StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
411 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
412 raii2(Ident___exception_code, false),
413 raii3(Ident_GetExceptionCode, false);
414
415 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
416 return StmtError();
417
418 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000421 Ident__exception_info->setIsPoisoned(false);
422 Ident___exception_info->setIsPoisoned(false);
423 Ident_GetExceptionInfo->setIsPoisoned(false);
424 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000425 ExprResult FilterExpr(ParseExpression());
Francois Pichetbfaf4772011-04-28 03:14:31 +0000426
David Blaikiebbafb8a2012-03-11 07:00:24 +0000427 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000428 Ident__exception_info->setIsPoisoned(true);
429 Ident___exception_info->setIsPoisoned(true);
430 Ident_GetExceptionInfo->setIsPoisoned(true);
431 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000432
433 if(FilterExpr.isInvalid())
434 return StmtError();
435
436 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
437 return StmtError();
438
Richard Smithc202b282012-04-14 00:33:13 +0000439 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000440
441 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000442 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000443
444 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
445}
446
447/// ParseSEHFinallyBlock - Handle __finally
448///
449/// seh-finally-block:
450/// '__finally' compound-statement
451///
452StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
453 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
454 raii2(Ident___abnormal_termination, false),
455 raii3(Ident_AbnormalTermination, false);
456
Richard Smithc202b282012-04-14 00:33:13 +0000457 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000458 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000459 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000460
461 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000462}
463
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000464/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000465///
466/// labeled-statement:
467/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000468/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000469///
Richard Smithc202b282012-04-14 00:33:13 +0000470StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000471 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
472 "Not an identifier!");
473
474 Token IdentTok = Tok; // Save the whole token.
475 ConsumeToken(); // eat the identifier.
476
477 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000478
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000479 // identifier ':' statement
480 SourceLocation ColonLoc = ConsumeToken();
481
Richard Smithc202b282012-04-14 00:33:13 +0000482 // Read label attributes, if present. attrs will contain both C++11 and GNU
483 // attributes (if present) after this point.
John McCall53fa7142010-12-24 02:08:15 +0000484 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000485
John McCalldadc5752010-08-24 06:29:42 +0000486 StmtResult SubStmt(ParseStatement());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000487
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000488 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000489 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000490 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000491
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000492 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
493 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000494 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000495 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000496 attrs.clear();
497 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000498
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000499 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
500 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000501}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000502
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000503/// ParseCaseStatement
504/// labeled-statement:
505/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000506/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000507///
Richard Smithc202b282012-04-14 00:33:13 +0000508StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000509 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattner34a22092009-03-04 04:23:07 +0000511 // It is very very common for code to contain many case statements recursively
512 // nested, as in (but usually without indentation):
513 // case 1:
514 // case 2:
515 // case 3:
516 // case 4:
517 // case 5: etc.
518 //
519 // Parsing this naively works, but is both inefficient and can cause us to run
520 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000521 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000522 // but all the grossness is constrained to ParseCaseStatement (and some
523 // wierdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000524
Chris Lattner34a22092009-03-04 04:23:07 +0000525 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
526 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000527 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattner34a22092009-03-04 04:23:07 +0000529 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
530 // gets updated each time a new case is parsed, and whose body is unset so
531 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieu3481fcd2011-09-09 02:16:15 +0000532 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000533
Chris Lattner34a22092009-03-04 04:23:07 +0000534 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000535 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000536 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000537 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
538 ConsumeToken(); // eat the 'case'.
Mike Stump11289f42009-09-09 15:08:12 +0000539
Douglas Gregord328d572009-09-21 18:10:23 +0000540 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000541 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000542 cutOffParsing();
543 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000544 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000545
Chris Lattner125c0ee2009-12-10 00:38:54 +0000546 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
547 /// Disable this form of error recovery while we're parsing the case
548 /// expression.
549 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000550
Richard Trieu2c850c02011-04-21 21:44:26 +0000551 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
552 MissingCase = false;
Chris Lattner34a22092009-03-04 04:23:07 +0000553 if (LHS.isInvalid()) {
Chris Lattner476c3ad2006-08-13 22:09:58 +0000554 SkipUntil(tok::colon);
Sebastian Redl042ad952008-12-11 19:30:53 +0000555 return StmtError();
Chris Lattner476c3ad2006-08-13 22:09:58 +0000556 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000557
Chris Lattner34a22092009-03-04 04:23:07 +0000558 // GNU case range extension.
559 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000560 ExprResult RHS;
Chris Lattner34a22092009-03-04 04:23:07 +0000561 if (Tok.is(tok::ellipsis)) {
562 Diag(Tok, diag::ext_gnu_case_range);
563 DotDotDotLoc = ConsumeToken();
Sebastian Redl042ad952008-12-11 19:30:53 +0000564
Chris Lattner34a22092009-03-04 04:23:07 +0000565 RHS = ParseConstantExpression();
566 if (RHS.isInvalid()) {
567 SkipUntil(tok::colon);
568 return StmtError();
569 }
570 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000571
Chris Lattner125c0ee2009-12-10 00:38:54 +0000572 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000573
John McCall0140bfe2011-01-22 09:28:32 +0000574 if (Tok.is(tok::colon)) {
575 ColonLoc = ConsumeToken();
576
577 // Treat "case blah;" as a typo for "case blah:".
578 } else if (Tok.is(tok::semi)) {
579 ColonLoc = ConsumeToken();
580 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
581 << FixItHint::CreateReplacement(ColonLoc, ":");
582 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000583 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
584 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
585 << FixItHint::CreateInsertion(ExpectedLoc, ":");
586 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000587 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000588
John McCalldadc5752010-08-24 06:29:42 +0000589 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000590 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
591 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000592
Chris Lattner34a22092009-03-04 04:23:07 +0000593 // If we had a sema error parsing this case, then just ignore it and
594 // continue parsing the sub-stmt.
595 if (Case.isInvalid()) {
596 if (TopLevelCase.isInvalid()) // No parsed case stmts.
597 return ParseStatement();
598 // Otherwise, just don't add it as a nested case.
599 } else {
600 // If this is the first case statement we parsed, it becomes TopLevelCase.
601 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000602 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000603 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000604 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000605 else
John McCallb268a282010-08-23 23:25:46 +0000606 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000607 DeepestParsedCaseStmt = NextDeepest;
608 }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattner34a22092009-03-04 04:23:07 +0000610 // Handle all case statements.
611 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000612
Chris Lattner34a22092009-03-04 04:23:07 +0000613 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump11289f42009-09-09 15:08:12 +0000614
Chris Lattner34a22092009-03-04 04:23:07 +0000615 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000616 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000617
Chris Lattner34a22092009-03-04 04:23:07 +0000618 if (Tok.isNot(tok::r_brace)) {
619 SubStmt = ParseStatement();
620 } else {
621 // Nicely diagnose the common error "switch (X) { case 4: }", which is
622 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000623 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000624 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
625 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner34a22092009-03-04 04:23:07 +0000626 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000627 }
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattner34a22092009-03-04 04:23:07 +0000629 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000630 if (SubStmt.isInvalid())
Chris Lattner34a22092009-03-04 04:23:07 +0000631 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattner34a22092009-03-04 04:23:07 +0000633 // Install the body into the most deeply-nested case.
John McCallb268a282010-08-23 23:25:46 +0000634 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl042ad952008-12-11 19:30:53 +0000635
Chris Lattner34a22092009-03-04 04:23:07 +0000636 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000637 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000638}
639
640/// ParseDefaultStatement
641/// labeled-statement:
642/// 'default' ':' statement
643/// Note that this does not parse the 'statement' at the end.
644///
Richard Smithc202b282012-04-14 00:33:13 +0000645StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000646 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000647 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000648
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000649 SourceLocation ColonLoc;
John McCall0140bfe2011-01-22 09:28:32 +0000650 if (Tok.is(tok::colon)) {
651 ColonLoc = ConsumeToken();
652
653 // Treat "default;" as a typo for "default:".
654 } else if (Tok.is(tok::semi)) {
655 ColonLoc = ConsumeToken();
656 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
657 << FixItHint::CreateReplacement(ColonLoc, ":");
658 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000659 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
660 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
661 << FixItHint::CreateInsertion(ExpectedLoc, ":");
662 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000663 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000664
Richard Smith1002d102012-02-17 01:35:32 +0000665 StmtResult SubStmt;
666
667 if (Tok.isNot(tok::r_brace)) {
668 SubStmt = ParseStatement();
669 } else {
670 // Diagnose the common error "switch (X) {... default: }", which is
671 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000672 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000673 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
674 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
675 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000676 }
677
Richard Smith1002d102012-02-17 01:35:32 +0000678 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000679 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000680 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000681
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000682 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000683 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000684}
685
Richard Smithc202b282012-04-14 00:33:13 +0000686StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
687 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000688}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000689
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000690/// ParseCompoundStatement - Parse a "{}" block.
691///
692/// compound-statement: [C99 6.8.2]
693/// { block-item-list[opt] }
694/// [GNU] { label-declarations block-item-list } [TODO]
695///
696/// block-item-list:
697/// block-item
698/// block-item-list block-item
699///
700/// block-item:
701/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000702/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000703/// statement
704/// [OMP] openmp-directive [TODO]
705///
706/// [GNU] label-declarations:
707/// [GNU] label-declaration
708/// [GNU] label-declarations label-declaration
709///
710/// [GNU] label-declaration:
711/// [GNU] '__label__' identifier-list ';'
712///
713/// [OMP] openmp-directive: [TODO]
714/// [OMP] barrier-directive
715/// [OMP] flush-directive
Chris Lattner30f910e2006-10-16 05:52:41 +0000716///
Richard Smithc202b282012-04-14 00:33:13 +0000717StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000718 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000719 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000720
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000721 // Enter a scope to hold everything within the compound stmt. Compound
722 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000723 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000724
725 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000726 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000727}
728
Lang Hames2954cea2012-11-03 22:29:05 +0000729/// Parse any pragmas at the start of the compound expression. We handle these
730/// separately since some pragmas (FP_CONTRACT) must appear before any C
731/// statement in the compound, but may be intermingled with other pragmas.
732void Parser::ParseCompoundStatementLeadingPragmas() {
733 bool checkForPragmas = true;
734 while (checkForPragmas) {
735 switch (Tok.getKind()) {
736 case tok::annot_pragma_vis:
737 HandlePragmaVisibility();
738 break;
739 case tok::annot_pragma_pack:
740 HandlePragmaPack();
741 break;
742 case tok::annot_pragma_msstruct:
743 HandlePragmaMSStruct();
744 break;
745 case tok::annot_pragma_align:
746 HandlePragmaAlign();
747 break;
748 case tok::annot_pragma_weak:
749 HandlePragmaWeak();
750 break;
751 case tok::annot_pragma_weakalias:
752 HandlePragmaWeakAlias();
753 break;
754 case tok::annot_pragma_redefine_extname:
755 HandlePragmaRedefineExtname();
756 break;
757 case tok::annot_pragma_opencl_extension:
758 HandlePragmaOpenCLExtension();
759 break;
760 case tok::annot_pragma_fp_contract:
761 HandlePragmaFPContract();
762 break;
763 default:
764 checkForPragmas = false;
765 break;
766 }
767 }
768
769}
770
Chris Lattnerf2978802007-01-21 06:52:16 +0000771/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000772/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000773/// consume the '}' at the end of the block. It does not manipulate the scope
774/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000775StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000776 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000777 Tok.getLocation(),
778 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000779
780 // Record the state of the FP_CONTRACT pragma, restore on leaving the
781 // compound statement.
782 Sema::FPContractStateRAII SaveFPContractState(Actions);
783
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000784 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000785 BalancedDelimiterTracker T(*this, tok::l_brace);
786 if (T.consumeOpen())
787 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000788
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000789 Sema::CompoundScopeRAII CompoundScope(Actions);
790
Lang Hames2954cea2012-11-03 22:29:05 +0000791 // Parse any pragmas at the beginning of the compound statement.
792 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000793
Lang Hames2954cea2012-11-03 22:29:05 +0000794 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000795
Chris Lattner43e7f312011-02-18 02:08:43 +0000796 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
797 // only allowed at the start of a compound stmt regardless of the language.
798 while (Tok.is(tok::kw___label__)) {
799 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000800
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000801 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000802 while (1) {
803 if (Tok.isNot(tok::identifier)) {
804 Diag(Tok, diag::err_expected_ident);
805 break;
806 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000807
Chris Lattner43e7f312011-02-18 02:08:43 +0000808 IdentifierInfo *II = Tok.getIdentifierInfo();
809 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000810 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000811
Chris Lattner43e7f312011-02-18 02:08:43 +0000812 if (!Tok.is(tok::comma))
813 break;
814 ConsumeToken();
815 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000816
John McCall084e83d2011-03-24 11:26:52 +0000817 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000818 DeclGroupPtrTy Res =
819 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000820 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000821
Chris Lattner02f1b612012-04-28 16:12:17 +0000822 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000823 if (R.isUsable())
824 Stmts.push_back(R.release());
825 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000826
Chris Lattner43e7f312011-02-18 02:08:43 +0000827 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000828 if (Tok.is(tok::annot_pragma_unused)) {
829 HandlePragmaUnused();
830 continue;
831 }
832
David Blaikiebbafb8a2012-03-11 07:00:24 +0000833 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet4a7de3e2011-05-06 20:48:22 +0000834 Tok.is(tok::kw___if_not_exists))) {
835 ParseMicrosoftIfExistsStatement(Stmts);
836 continue;
837 }
838
John McCalldadc5752010-08-24 06:29:42 +0000839 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000840 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000841 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000842 } else {
843 // __extension__ can start declarations and it can also be a unary
844 // operator for expressions. Consume multiple __extension__ markers here
845 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000846 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000847 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000848 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000849 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000850
John McCall084e83d2011-03-24 11:26:52 +0000851 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000852 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000853
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000854 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +0000855 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +0000856 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +0000857 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +0000858 ExtensionRAIIObject O(Diags);
859
Chris Lattner49836b42009-04-02 04:16:50 +0000860 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000861 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
862 Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000863 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000864 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000865 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000866 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +0000867 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +0000868
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000869 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000870 SkipUntil(tok::semi);
871 continue;
872 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +0000873
Alexis Hunt96d5c762009-11-21 08:43:09 +0000874 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +0000875 // Eat the semicolon at the end of stmt and convert the expr into a
876 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000877 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000878 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000879 }
880 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000881
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000882 if (R.isUsable())
Sebastian Redld9f7b1c2008-12-10 00:02:53 +0000883 Stmts.push_back(R.release());
Chris Lattner30f910e2006-10-16 05:52:41 +0000884 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000885
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000886 SourceLocation CloseLoc = Tok.getLocation();
887
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000888 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +0000889 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000890 // Recover by creating a compound statement with what we parsed so far,
891 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +0000892 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +0000893
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000894 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000895 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000896}
Chris Lattnerc951dae2006-08-10 04:23:57 +0000897
Chris Lattnerc0081db2008-12-12 06:31:07 +0000898/// ParseParenExprOrCondition:
899/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +0000900/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +0000901///
902/// This function parses and performs error recovery on the specified condition
903/// or expression (depending on whether we're in C++ or C mode). This function
904/// goes out of its way to recover well. It returns true if there was a parser
905/// error (the right paren couldn't be found), which indicates that the caller
906/// should try to recover harder. It returns false if the condition is
907/// successfully parsed. Note that a successful parse can still have semantic
908/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +0000909bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +0000910 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +0000911 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000912 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000913 BalancedDelimiterTracker T(*this, tok::l_paren);
914 T.consumeOpen();
915
David Blaikiebbafb8a2012-03-11 07:00:24 +0000916 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +0000917 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000918 else {
919 ExprResult = ParseExpression();
John McCall48871652010-08-21 09:40:31 +0000920 DeclResult = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000921
Douglas Gregore60e41a2010-05-06 17:25:47 +0000922 // If required, convert to a boolean value.
923 if (!ExprResult.isInvalid() && ConvertToBoolean)
924 ExprResult
John McCallb268a282010-08-23 23:25:46 +0000925 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000926 }
Mike Stump11289f42009-09-09 15:08:12 +0000927
Chris Lattnerc0081db2008-12-12 06:31:07 +0000928 // If the parser was confused by the condition and we don't have a ')', try to
929 // recover by skipping ahead to a semi and bailing out. If condexp is
930 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +0000931 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +0000932 SkipUntil(tok::semi);
933 // Skipping may have stopped if it found the containing ')'. If so, we can
934 // continue parsing the if statement.
935 if (Tok.isNot(tok::r_paren))
936 return true;
937 }
Mike Stump11289f42009-09-09 15:08:12 +0000938
Chris Lattnerc0081db2008-12-12 06:31:07 +0000939 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000940 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +0000941
Chris Lattner70d44982012-04-28 16:24:20 +0000942 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
943 // that all callers are looking for a statement after the condition, so ")"
944 // isn't valid.
945 while (Tok.is(tok::r_paren)) {
946 Diag(Tok, diag::err_extraneous_rparen_in_condition)
947 << FixItHint::CreateRemoval(Tok.getLocation());
948 ConsumeParen();
949 }
Chad Rosier67055f52012-07-10 21:35:27 +0000950
Chris Lattnerc0081db2008-12-12 06:31:07 +0000951 return false;
952}
953
954
Chris Lattnerc951dae2006-08-10 04:23:57 +0000955/// ParseIfStatement
956/// if-statement: [C99 6.8.4.1]
957/// 'if' '(' expression ')' statement
958/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +0000959/// [C++] 'if' '(' condition ')' statement
960/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +0000961///
Richard Smithc202b282012-04-14 00:33:13 +0000962StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000963 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000964 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +0000965
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000966 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +0000967 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +0000968 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +0000969 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +0000970 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +0000971
David Blaikiebbafb8a2012-03-11 07:00:24 +0000972 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000973
Chris Lattner2dd1b722007-08-26 23:08:06 +0000974 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
975 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000976 //
977 // C++ 6.4p3:
978 // A name introduced by a declaration in a condition is in scope from its
979 // point of declaration until the end of the substatements controlled by the
980 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +0000981 // C++ 3.3.2p4:
982 // Names declared in the for-init-statement, and in the condition of if,
983 // while, for, and switch statements are local to the if, while, for, or
984 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000985 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +0000986 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +0000987
Chris Lattnerc951dae2006-08-10 04:23:57 +0000988 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +0000989 ExprResult CondExp;
John McCall48871652010-08-21 09:40:31 +0000990 Decl *CondVar = 0;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000991 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +0000992 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +0000993
David Blaikiea5696df2012-05-16 04:20:04 +0000994 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +0000995
Chris Lattner8fb26252007-08-22 05:28:50 +0000996 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +0000997 // there is no compound stmt. C90 does not have this clause. We only do this
998 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000999 //
1000 // C++ 6.4p1:
1001 // The substatement in a selection-statement (each substatement, in the else
1002 // form of the if statement) implicitly defines a local scope.
1003 //
1004 // For C++ we create a scope for the condition and a new scope for
1005 // substatements because:
1006 // -When the 'then' scope exits, we want the condition declaration to still be
1007 // active for the 'else' scope too.
1008 // -Sema will detect name clashes by considering declarations of a
1009 // 'ControlScope' as part of its direct subscope.
1010 // -If we wanted the condition and substatement to be in the same scope, we
1011 // would have to notify ParseStatement not to create a new scope. It's
1012 // simpler to let it create a new scope.
1013 //
Mike Stump11289f42009-09-09 15:08:12 +00001014 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001015 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001016
Chris Lattner5c5808a2007-10-29 05:08:52 +00001017 // Read the 'then' stmt.
1018 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001019
1020 SourceLocation InnerStatementTrailingElseLoc;
1021 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001022
Chris Lattner37e54f42007-08-22 05:16:28 +00001023 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001024 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001025
Chris Lattnerc951dae2006-08-10 04:23:57 +00001026 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001027 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001028 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001029 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001030
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001031 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001032 if (TrailingElseLoc)
1033 *TrailingElseLoc = Tok.getLocation();
1034
Chris Lattneraf635312006-10-16 06:06:51 +00001035 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001036 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001037
Chris Lattner8fb26252007-08-22 05:28:50 +00001038 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001039 // there is no compound stmt. C90 does not have this clause. We only do
1040 // this if the body isn't a compound statement to avoid push/pop in common
1041 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001042 //
1043 // C++ 6.4p1:
1044 // The substatement in a selection-statement (each substatement, in the else
1045 // form of the if statement) implicitly defines a local scope.
1046 //
Sebastian Redl042ad952008-12-11 19:30:53 +00001047 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001048 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001049
Chris Lattner30f910e2006-10-16 05:52:41 +00001050 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001051
Chris Lattner37e54f42007-08-22 05:16:28 +00001052 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001053 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001054 } else if (Tok.is(tok::code_completion)) {
1055 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001056 cutOffParsing();
1057 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001058 } else if (InnerStatementTrailingElseLoc.isValid()) {
1059 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001060 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001061
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001062 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001063
Chris Lattner5c5808a2007-10-29 05:08:52 +00001064 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001065 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001066 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001067 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1068 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1069 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001070 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001071 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001072 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001073
Chris Lattner5c5808a2007-10-29 05:08:52 +00001074 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001075 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001076 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001077 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001078 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001079
John McCallb268a282010-08-23 23:25:46 +00001080 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001081 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001082}
1083
Chris Lattner9075bd72006-08-10 04:59:57 +00001084/// ParseSwitchStatement
1085/// switch-statement:
1086/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001087/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001088StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001089 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001090 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001091
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001092 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001093 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001094 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001095 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001096 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001097
David Blaikiebbafb8a2012-03-11 07:00:24 +00001098 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001099
Chris Lattner2dd1b722007-08-26 23:08:06 +00001100 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1101 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001102 //
1103 // C++ 6.4p3:
1104 // A name introduced by a declaration in a condition is in scope from its
1105 // point of declaration until the end of the substatements controlled by the
1106 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001107 // C++ 3.3.2p4:
1108 // Names declared in the for-init-statement, and in the condition of if,
1109 // while, for, and switch statements are local to the if, while, for, or
1110 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001111 //
Richard Trieu2c850c02011-04-21 21:44:26 +00001112 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001113 if (C99orCXX)
1114 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001115 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001116
Chris Lattner9075bd72006-08-10 04:59:57 +00001117 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001118 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001119 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001120 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001121 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001122
John McCalldadc5752010-08-24 06:29:42 +00001123 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001124 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001125
Douglas Gregore60e41a2010-05-06 17:25:47 +00001126 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001127 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001128 // FIXME: This is not optimal recovery, but parsing the body is more
1129 // dangerous due to the presence of case and default statements, which
1130 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001131 if (Tok.is(tok::l_brace)) {
1132 ConsumeBrace();
1133 SkipUntil(tok::r_brace, false, false);
1134 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001135 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001136 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001137 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001138
Chris Lattner8fb26252007-08-22 05:28:50 +00001139 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001140 // there is no compound stmt. C90 does not have this clause. We only do this
1141 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001142 //
1143 // C++ 6.4p1:
1144 // The substatement in a selection-statement (each substatement, in the else
1145 // form of the if statement) implicitly defines a local scope.
1146 //
1147 // See comments in ParseIfStatement for why we create a scope for the
1148 // condition and a new scope for substatement in C++.
1149 //
Mike Stump11289f42009-09-09 15:08:12 +00001150 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001151 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001152
Chris Lattner9075bd72006-08-10 04:59:57 +00001153 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001154 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001155
Chris Lattner8fd2d012010-01-24 01:50:29 +00001156 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001157 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001158 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001159
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001160 if (Body.isInvalid()) {
Chris Lattner8fd2d012010-01-24 01:50:29 +00001161 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001162
1163 // Put the synthesized null statement on the same line as the end of switch
1164 // condition.
1165 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1166 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1167 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001168
John McCallb268a282010-08-23 23:25:46 +00001169 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001170}
1171
1172/// ParseWhileStatement
1173/// while-statement: [C99 6.8.5.1]
1174/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001175/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001176StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001177 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001178 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001179 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001180
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001181 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001182 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001183 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001184 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001185 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001186
David Blaikiebbafb8a2012-03-11 07:00:24 +00001187 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001188
Chris Lattner2dd1b722007-08-26 23:08:06 +00001189 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1190 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001191 //
1192 // C++ 6.4p3:
1193 // A name introduced by a declaration in a condition is in scope from its
1194 // point of declaration until the end of the substatements controlled by the
1195 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001196 // C++ 3.3.2p4:
1197 // Names declared in the for-init-statement, and in the condition of if,
1198 // while, for, and switch statements are local to the if, while, for, or
1199 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001200 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001201 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001202 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001203 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1204 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001205 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001206 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1207 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001208
Chris Lattner9075bd72006-08-10 04:59:57 +00001209 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001210 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001211 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001212 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001213 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001214
David Blaikiea5696df2012-05-16 04:20:04 +00001215 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattner8fb26252007-08-22 05:28:50 +00001217 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001218 // there is no compound stmt. C90 does not have this clause. We only do this
1219 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001220 //
1221 // C++ 6.5p2:
1222 // The substatement in an iteration-statement implicitly defines a local scope
1223 // which is entered and exited each time through the loop.
1224 //
1225 // See comments in ParseIfStatement for why we create a scope for the
1226 // condition and a new scope for substatement in C++.
1227 //
Mike Stump11289f42009-09-09 15:08:12 +00001228 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001229 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001230
Chris Lattner9075bd72006-08-10 04:59:57 +00001231 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001232 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001233
Chris Lattner8fb26252007-08-22 05:28:50 +00001234 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001235 InnerScope.Exit();
1236 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001237
John McCall48871652010-08-21 09:40:31 +00001238 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001239 return StmtError();
1240
John McCallb268a282010-08-23 23:25:46 +00001241 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001242}
1243
1244/// ParseDoStatement
1245/// do-statement: [C99 6.8.5.2]
1246/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001247/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001248StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001249 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001250 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001251
Chris Lattner2dd1b722007-08-26 23:08:06 +00001252 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1253 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001254 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001255 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001256 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001257 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001258 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001259
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001260 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001261
Chris Lattner8fb26252007-08-22 05:28:50 +00001262 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001263 // there is no compound stmt. C90 does not have this clause. We only do this
1264 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001265 //
1266 // C++ 6.5p2:
1267 // The substatement in an iteration-statement implicitly defines a local scope
1268 // which is entered and exited each time through the loop.
1269 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001270 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001271 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001272 Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001273
Chris Lattner9075bd72006-08-10 04:59:57 +00001274 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001275 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001276
Chris Lattner8fb26252007-08-22 05:28:50 +00001277 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001278 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001279
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001280 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001281 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001282 Diag(Tok, diag::err_expected_while);
Chris Lattner03c40412008-11-23 23:17:07 +00001283 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner0046de12008-11-13 18:52:53 +00001284 SkipUntil(tok::semi, false, true);
1285 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001286 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001287 }
Chris Lattneraf635312006-10-16 06:06:51 +00001288 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001289
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001290 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001291 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner0046de12008-11-13 18:52:53 +00001292 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001293 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001294 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001295
Chris Lattner10da53c2008-12-12 06:35:28 +00001296 // Parse the parenthesized condition.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001297 BalancedDelimiterTracker T(*this, tok::l_paren);
1298 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001299
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001300 // FIXME: Do not just parse the attribute contents and throw them away
1301 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001302 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001303 ProhibitAttributes(attrs);
1304
John McCalldadc5752010-08-24 06:29:42 +00001305 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001306 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001307 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001308
Sebastian Redlb62406f2008-12-11 19:48:14 +00001309 if (Cond.isInvalid() || Body.isInvalid())
1310 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001311
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001312 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1313 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001314}
1315
1316/// ParseForStatement
1317/// for-statement: [C99 6.8.5.3]
1318/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1319/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001320/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1321/// [C++] statement
Richard Smith02e85f32011-04-14 22:09:26 +00001322/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001323/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1324/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001325///
1326/// [C++] for-init-statement:
1327/// [C++] expression-statement
1328/// [C++] simple-declaration
1329///
Richard Smith02e85f32011-04-14 22:09:26 +00001330/// [C++0x] for-range-declaration:
1331/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1332/// [C++0x] for-range-initializer:
1333/// [C++0x] expression
1334/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001335StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001336 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001337 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001338
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001339 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001340 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001341 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001342 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001343 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001344
Chad Rosier67055f52012-07-10 21:35:27 +00001345 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1346 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001347
Chris Lattner2dd1b722007-08-26 23:08:06 +00001348 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1349 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001350 //
1351 // C++ 6.4p3:
1352 // A name introduced by a declaration in a condition is in scope from its
1353 // point of declaration until the end of the substatements controlled by the
1354 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001355 // C++ 3.3.2p4:
1356 // Names declared in the for-init-statement, and in the condition of if,
1357 // while, for, and switch statements are local to the if, while, for, or
1358 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001359 // C++ 6.5.3p1:
1360 // Names declared in the for-init-statement are in the same declarative-region
1361 // as those declared in the condition.
1362 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001363 unsigned ScopeFlags;
Chris Lattner934074c2009-04-22 00:54:41 +00001364 if (C99orCXXorObjC)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001365 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1366 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001367 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001368 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1369
1370 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001371
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001372 BalancedDelimiterTracker T(*this, tok::l_paren);
1373 T.consumeOpen();
1374
John McCalldadc5752010-08-24 06:29:42 +00001375 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001376
Richard Smith02e85f32011-04-14 22:09:26 +00001377 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001378 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001379 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001380 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001381 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001382 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001383 FullExprArg ThirdPart(Actions);
John McCall48871652010-08-21 09:40:31 +00001384 Decl *SecondVar = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001385
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001386 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001387 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001388 C99orCXXorObjC? Sema::PCC_ForInit
1389 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001390 cutOffParsing();
1391 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001392 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001393
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001394 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001395 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001396
Chris Lattner9075bd72006-08-10 04:59:57 +00001397 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001398 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001399 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001400 // no first part, eat the ';'.
1401 ConsumeToken();
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001402 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001403 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001404 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001405 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001406
Richard Smith02e85f32011-04-14 22:09:26 +00001407 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001408 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001409 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1410
Chris Lattner49836b42009-04-02 04:16:50 +00001411 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +00001412 StmtVector Stmts;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001413 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smith02e85f32011-04-14 22:09:26 +00001414 DeclEnd, attrs, false,
1415 MightBeForRangeStmt ?
1416 &ForRangeInit : 0);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001417 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001418
Richard Smith02e85f32011-04-14 22:09:26 +00001419 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001420 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001421 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001422
Richard Smith02e85f32011-04-14 22:09:26 +00001423 ForRange = true;
1424 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001425 ConsumeToken();
1426 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001427 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001428 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001429 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001430
Douglas Gregor68762e72010-08-23 21:17:50 +00001431 if (Tok.is(tok::code_completion)) {
1432 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001433 cutOffParsing();
1434 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001435 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001436 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001437 } else {
1438 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001439 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001440 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001441 ProhibitAttributes(attrs);
Chris Lattner89c50c62006-08-11 06:41:18 +00001442 Value = ParseExpression();
Chris Lattner71e23ce2006-11-04 20:18:38 +00001443
John McCall34376a62010-12-04 03:47:34 +00001444 ForEach = isTokIdentifier_in();
1445
Chris Lattnercd68f642007-06-27 01:06:29 +00001446 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001447 if (!Value.isInvalid()) {
1448 if (ForEach)
1449 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1450 else
Richard Smith945f8d32013-01-14 22:39:08 +00001451 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001452 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001453
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001454 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001455 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001456 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001457 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001458
Douglas Gregor68762e72010-08-23 21:17:50 +00001459 if (Tok.is(tok::code_completion)) {
1460 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001461 cutOffParsing();
1462 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001463 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001464 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001465 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001466 // User tried to write the reasonable, but ill-formed, for-range-statement
1467 // for (expr : expr) { ... }
1468 Diag(Tok, diag::err_for_range_expected_decl)
1469 << FirstPart.get()->getSourceRange();
1470 SkipUntil(tok::r_paren, false, true);
1471 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001472 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001473 if (!Value.isInvalid()) {
1474 Diag(Tok, diag::err_expected_semi_for);
1475 } else {
1476 // Skip until semicolon or rparen, don't consume it.
1477 SkipUntil(tok::r_paren, true, true);
1478 if (Tok.is(tok::semi))
1479 ConsumeToken();
1480 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001481 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001482 }
Richard Smith02e85f32011-04-14 22:09:26 +00001483 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001484 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001485 // Parse the second part of the for specifier.
1486 if (Tok.is(tok::semi)) { // for (...;;
1487 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001488 } else if (Tok.is(tok::r_paren)) {
1489 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001490 } else {
John McCalldadc5752010-08-24 06:29:42 +00001491 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001492 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001493 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1494 else {
1495 Second = ParseExpression();
1496 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001497 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001498 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001499 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001500 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001501 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001502 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001503
Douglas Gregor230a7e62011-02-17 03:38:46 +00001504 if (Tok.isNot(tok::semi)) {
1505 if (!SecondPartIsInvalid || SecondVar)
1506 Diag(Tok, diag::err_expected_semi_for);
1507 else
1508 // Skip until semicolon or rparen, don't consume it.
1509 SkipUntil(tok::r_paren, true, true);
1510 }
1511
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001512 if (Tok.is(tok::semi)) {
1513 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001514 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001515
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001516 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001517 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001518 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001519 // FIXME: The C++11 standard doesn't actually say that this is a
1520 // discarded-value expression, but it clearly should be.
1521 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001522 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001523 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001524 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001525 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001526
Richard Smith02e85f32011-04-14 22:09:26 +00001527 // We need to perform most of the semantic analysis for a C++0x for-range
1528 // statememt before parsing the body, in order to be able to deduce the type
1529 // of an auto-typed loop variable.
1530 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001531 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001532
John McCall53848232011-07-27 01:07:15 +00001533 if (ForRange) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001534 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smith02e85f32011-04-14 22:09:26 +00001535 ForRangeInit.ColonLoc,
1536 ForRangeInit.RangeExpr.get(),
Richard Smitha05b3b52012-09-20 21:52:32 +00001537 T.getCloseLocation(),
1538 Sema::BFRK_Build);
Richard Smith02e85f32011-04-14 22:09:26 +00001539
John McCall53848232011-07-27 01:07:15 +00001540
1541 // Similarly, we need to do the semantic analysis for a for-range
1542 // statement immediately in order to close over temporaries correctly.
1543 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001544 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001545 FirstPart.take(),
Chad Rosier67055f52012-07-10 21:35:27 +00001546 Collection.take(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001547 T.getCloseLocation());
John McCall53848232011-07-27 01:07:15 +00001548 }
1549
Chris Lattner8fb26252007-08-22 05:28:50 +00001550 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001551 // there is no compound stmt. C90 does not have this clause. We only do this
1552 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001553 //
1554 // C++ 6.5p2:
1555 // The substatement in an iteration-statement implicitly defines a local scope
1556 // which is entered and exited each time through the loop.
1557 //
1558 // See comments in ParseIfStatement for why we create a scope for
1559 // for-init-statement/condition and a new scope for substatement in C++.
1560 //
Mike Stump11289f42009-09-09 15:08:12 +00001561 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner934074c2009-04-22 00:54:41 +00001562 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001563
Chris Lattner9075bd72006-08-10 04:59:57 +00001564 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001565 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001566
Chris Lattner8fb26252007-08-22 05:28:50 +00001567 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001568 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001569
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001570 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001571 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001572
1573 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001574 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001575
Richard Smith02e85f32011-04-14 22:09:26 +00001576 if (ForEach)
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001577 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1578 Body.take());
Mike Stump11289f42009-09-09 15:08:12 +00001579
Richard Smith02e85f32011-04-14 22:09:26 +00001580 if (ForRange)
1581 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1582
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001583 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1584 SecondPart, SecondVar, ThirdPart,
1585 T.getCloseLocation(), Body.take());
Chris Lattner9075bd72006-08-10 04:59:57 +00001586}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001587
Chris Lattner503fadc2006-08-10 05:45:44 +00001588/// ParseGotoStatement
1589/// jump-statement:
1590/// 'goto' identifier ';'
1591/// [GNU] 'goto' '*' expression ';'
1592///
1593/// Note: this lets the caller parse the end ';'.
1594///
Richard Smithc202b282012-04-14 00:33:13 +00001595StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001596 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001597 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001598
John McCalldadc5752010-08-24 06:29:42 +00001599 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001600 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001601 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1602 Tok.getLocation());
1603 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001604 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001605 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001606 // GNU indirect goto extension.
1607 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001608 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001609 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001610 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Chris Lattnera0927ce2006-08-12 16:59:03 +00001611 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001612 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001613 }
John McCallb268a282010-08-23 23:25:46 +00001614 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001615 } else {
1616 Diag(Tok, diag::err_expected_ident);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001617 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001618 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001619
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001620 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001621}
1622
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001623/// ParseContinueStatement
1624/// jump-statement:
1625/// 'continue' ';'
1626///
1627/// Note: this lets the caller parse the end ';'.
1628///
Richard Smithc202b282012-04-14 00:33:13 +00001629StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001630 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001631 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001632}
1633
1634/// ParseBreakStatement
1635/// jump-statement:
1636/// 'break' ';'
1637///
1638/// Note: this lets the caller parse the end ';'.
1639///
Richard Smithc202b282012-04-14 00:33:13 +00001640StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001641 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001642 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001643}
1644
Chris Lattner503fadc2006-08-10 05:45:44 +00001645/// ParseReturnStatement
1646/// jump-statement:
1647/// 'return' expression[opt] ';'
Richard Smithc202b282012-04-14 00:33:13 +00001648StmtResult Parser::ParseReturnStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001649 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001650 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001651
John McCalldadc5752010-08-24 06:29:42 +00001652 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001653 if (Tok.isNot(tok::semi)) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001654 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001655 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001656 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001657 return StmtError();
1658 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001659
David Blaikiebbafb8a2012-03-11 07:00:24 +00001660 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001661 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001662 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001663 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001664 diag::warn_cxx98_compat_generalized_initializer_lists :
1665 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001666 << R.get()->getSourceRange();
1667 } else
1668 R = ParseExpression();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001669 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Chris Lattnera0927ce2006-08-12 16:59:03 +00001670 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001671 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001672 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001673 }
John McCallb268a282010-08-23 23:25:46 +00001674 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Chris Lattner503fadc2006-08-10 05:45:44 +00001675}
Chris Lattner0116c472006-08-15 06:03:28 +00001676
John McCallf413f5e2013-05-03 00:10:13 +00001677namespace {
1678 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1679 Parser &TheParser;
1680 SourceLocation AsmLoc;
1681 StringRef AsmString;
1682
1683 /// The tokens we streamed into AsmString and handed off to MC.
1684 ArrayRef<Token> AsmToks;
1685
1686 /// The offset of each token in AsmToks within AsmString.
1687 ArrayRef<unsigned> AsmTokOffsets;
1688
1689 public:
1690 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1691 StringRef AsmString,
1692 ArrayRef<Token> Toks,
1693 ArrayRef<unsigned> Offsets)
1694 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1695 AsmToks(Toks), AsmTokOffsets(Offsets) {
1696 assert(AsmToks.size() == AsmTokOffsets.size());
1697 }
1698
1699 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1700 InlineAsmIdentifierInfo &Info,
1701 bool IsUnevaluatedContext) {
1702 // Collect the desired tokens.
1703 SmallVector<Token, 16> LineToks;
1704 const Token *FirstOrigToken = 0;
1705 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1706
1707 unsigned NumConsumedToks;
1708 ExprResult Result =
1709 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1710 IsUnevaluatedContext);
1711
1712 // If we consumed the entire line, tell MC that.
1713 // Also do this if we consumed nothing as a way of reporting failure.
1714 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1715 // By not modifying LineBuf, we're implicitly consuming it all.
1716
1717 // Otherwise, consume up to the original tokens.
1718 } else {
1719 assert(FirstOrigToken && "not using original tokens?");
1720
1721 // Since we're using original tokens, apply that offset.
1722 assert(FirstOrigToken[NumConsumedToks].getLocation()
1723 == LineToks[NumConsumedToks].getLocation());
1724 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1725 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1726
1727 // The total length we've consumed is the relative offset
1728 // of the last token we consumed plus its length.
1729 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1730 + AsmToks[LastIndex].getLength()
1731 - AsmTokOffsets[FirstIndex]);
1732 LineBuf = LineBuf.substr(0, TotalOffset);
1733 }
1734
1735 // Initialize the "decl" with the lookup result.
1736 Info.OpDecl = static_cast<void*>(Result.take());
1737 return Info.OpDecl;
1738 }
1739
1740 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1741 unsigned &Offset) {
1742 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1743 Offset, AsmLoc);
1744 }
1745
1746 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1747 void *Context) {
1748 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1749 }
1750
1751 private:
1752 /// Collect the appropriate tokens for the given string.
1753 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1754 const Token *&FirstOrigToken) const {
1755 // For now, assert that the string we're working with is a substring
1756 // of what we gave to MC. This lets us use the original tokens.
1757 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1758 !std::less<const char*>()(AsmString.end(), Str.end()));
1759
1760 // Try to find a token whose offset matches the first token.
1761 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1762 const unsigned *FirstTokOffset
1763 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1764 FirstCharOffset);
1765
1766 // For now, assert that the start of the string exactly
1767 // corresponds to the start of a token.
1768 assert(*FirstTokOffset == FirstCharOffset);
1769
1770 // Use all the original tokens for this line. (We assume the
1771 // end of the line corresponds cleanly to a token break.)
1772 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1773 FirstOrigToken = &AsmToks[FirstTokIndex];
1774 unsigned LastCharOffset = Str.end() - AsmString.begin();
1775 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1776 if (AsmTokOffsets[i] >= LastCharOffset) break;
1777 TempToks.push_back(AsmToks[i]);
1778 }
1779 }
1780
1781 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1782 // Compute an offset into the inline asm buffer.
1783 // FIXME: This isn't right if .macro is involved (but hopefully, no
1784 // real-world code does that).
1785 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1786 const llvm::MemoryBuffer *LBuf =
1787 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1788 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1789
1790 // Figure out which token that offset points into.
1791 const unsigned *TokOffsetPtr =
1792 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1793 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1794 unsigned TokOffset = *TokOffsetPtr;
1795
1796 // If we come up with an answer which seems sane, use it; otherwise,
1797 // just point at the __asm keyword.
1798 // FIXME: Assert the answer is sane once we handle .macro correctly.
1799 SourceLocation Loc = AsmLoc;
1800 if (TokIndex < AsmToks.size()) {
1801 const Token &Tok = AsmToks[TokIndex];
1802 Loc = Tok.getLocation();
1803 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1804 }
1805 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1806 << D.getMessage();
1807 }
1808 };
1809}
1810
1811/// Parse an identifier in an MS-style inline assembly block.
1812///
1813/// \param CastInfo - a void* so that we don't have to teach Parser.h
1814/// about the actual type.
1815ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1816 unsigned &NumLineToksConsumed,
1817 void *CastInfo,
1818 bool IsUnevaluatedContext) {
1819 llvm::InlineAsmIdentifierInfo &Info =
1820 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1821
1822 // Push a fake token on the end so that we don't overrun the token
1823 // stream. We use ';' because it expression-parsing should never
1824 // overrun it.
1825 const tok::TokenKind EndOfStream = tok::semi;
1826 Token EndOfStreamTok;
1827 EndOfStreamTok.startToken();
1828 EndOfStreamTok.setKind(EndOfStream);
1829 LineToks.push_back(EndOfStreamTok);
1830
1831 // Also copy the current token over.
1832 LineToks.push_back(Tok);
1833
1834 PP.EnterTokenStream(LineToks.begin(),
1835 LineToks.size(),
1836 /*disable macros*/ true,
1837 /*owns tokens*/ false);
1838
1839 // Clear the current token and advance to the first token in LineToks.
1840 ConsumeAnyToken();
1841
1842 // Parse an optional scope-specifier if we're in C++.
1843 CXXScopeSpec SS;
1844 if (getLangOpts().CPlusPlus) {
1845 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1846 }
1847
1848 // Require an identifier here.
1849 SourceLocation TemplateKWLoc;
1850 UnqualifiedId Id;
1851 bool Invalid = ParseUnqualifiedId(SS,
1852 /*EnteringContext=*/false,
1853 /*AllowDestructorName=*/false,
1854 /*AllowConstructorName=*/false,
1855 /*ObjectType=*/ ParsedType(),
1856 TemplateKWLoc,
1857 Id);
1858
1859 // If we've run into the poison token we inserted before, or there
1860 // was a parsing error, then claim the entire line.
1861 if (Invalid || Tok.is(EndOfStream)) {
1862 NumLineToksConsumed = LineToks.size() - 2;
1863
1864 // Otherwise, claim up to the start of the next token.
1865 } else {
1866 // Figure out how many tokens we are into LineToks.
1867 unsigned LineIndex = 0;
1868 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1869 LineIndex++;
1870 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1871 }
1872
1873 NumLineToksConsumed = LineIndex;
1874 }
1875
1876 // Finally, restore the old parsing state by consuming all the
1877 // tokens we staged before, implicitly killing off the
1878 // token-lexer we pushed.
1879 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1880 ConsumeAnyToken();
1881 }
1882 ConsumeToken(EndOfStream);
1883
1884 // Leave LineToks in its original state.
1885 LineToks.pop_back();
1886 LineToks.pop_back();
1887
1888 // Perform the lookup.
1889 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1890 IsUnevaluatedContext);
1891}
1892
1893/// Turn a sequence of our tokens back into a string that we can hand
1894/// to the MC asm parser.
1895static bool buildMSAsmString(Preprocessor &PP,
1896 SourceLocation AsmLoc,
1897 ArrayRef<Token> AsmToks,
1898 SmallVectorImpl<unsigned> &TokOffsets,
1899 SmallString<512> &Asm) {
1900 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1901
1902 // Is this the start of a new assembly statement?
1903 bool isNewStatement = true;
1904
1905 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1906 const Token &Tok = AsmToks[i];
1907
1908 // Start each new statement with a newline and a tab.
1909 if (!isNewStatement &&
1910 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1911 Asm += "\n\t";
1912 isNewStatement = true;
1913 }
1914
1915 // Preserve the existence of leading whitespace except at the
1916 // start of a statement.
1917 if (!isNewStatement && Tok.hasLeadingSpace())
1918 Asm += ' ';
1919
1920 // Remember the offset of this token.
1921 TokOffsets.push_back(Asm.size());
1922
1923 // Don't actually write '__asm' into the assembly stream.
1924 if (Tok.is(tok::kw_asm)) {
1925 // Complain about __asm at the end of the stream.
1926 if (i + 1 == e) {
1927 PP.Diag(AsmLoc, diag::err_asm_empty);
1928 return true;
1929 }
1930
1931 continue;
1932 }
1933
1934 // Append the spelling of the token.
1935 SmallString<32> SpellingBuffer;
1936 bool SpellingInvalid = false;
1937 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
1938 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
1939
1940 // We are no longer at the start of a statement.
1941 isNewStatement = false;
1942 }
1943
1944 // Ensure that the buffer is null-terminated.
1945 Asm.push_back('\0');
1946 Asm.pop_back();
1947
1948 assert(TokOffsets.size() == AsmToks.size());
1949 return false;
1950}
1951
Eli Friedmana4b02c32011-09-30 01:13:51 +00001952/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1953/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier32503022012-06-11 20:47:18 +00001954///
1955/// [MS] ms-asm-statement:
1956/// ms-asm-block
1957/// ms-asm-block ms-asm-statement
1958///
1959/// [MS] ms-asm-block:
1960/// '__asm' ms-asm-line '\n'
1961/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1962///
1963/// [MS] ms-asm-instruction-block
1964/// ms-asm-line
1965/// ms-asm-line '\n' ms-asm-instruction-block
1966///
Eli Friedmana4b02c32011-09-30 01:13:51 +00001967StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1968 SourceManager &SrcMgr = PP.getSourceManager();
1969 SourceLocation EndLoc = AsmLoc;
Chad Rosier32503022012-06-11 20:47:18 +00001970 SmallVector<Token, 4> AsmToks;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00001971
1972 bool InBraces = false;
1973 unsigned short savedBraceCount = 0;
1974 bool InAsmComment = false;
1975 FileID FID;
1976 unsigned LineNo = 0;
1977 unsigned NumTokensRead = 0;
1978 SourceLocation LBraceLoc;
1979
1980 if (Tok.is(tok::l_brace)) {
1981 // Braced inline asm: consume the opening brace.
1982 InBraces = true;
1983 savedBraceCount = BraceCount;
1984 EndLoc = LBraceLoc = ConsumeBrace();
1985 ++NumTokensRead;
1986 } else {
1987 // Single-line inline asm; compute which line it is on.
1988 std::pair<FileID, unsigned> ExpAsmLoc =
1989 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1990 FID = ExpAsmLoc.first;
1991 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1992 }
1993
1994 SourceLocation TokLoc = Tok.getLocation();
Eli Friedmana4b02c32011-09-30 01:13:51 +00001995 do {
Chad Rosierc97a6bb2012-08-14 19:22:06 +00001996 // If we hit EOF, we're done, period.
1997 if (Tok.is(tok::eof))
Eli Friedmana4b02c32011-09-30 01:13:51 +00001998 break;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00001999
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002000 if (!InAsmComment && Tok.is(tok::semi)) {
2001 // A semicolon in an asm is the start of a comment.
2002 InAsmComment = true;
2003 if (InBraces) {
2004 // Compute which line the comment is on.
2005 std::pair<FileID, unsigned> ExpSemiLoc =
2006 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2007 FID = ExpSemiLoc.first;
2008 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2009 }
2010 } else if (!InBraces || InAsmComment) {
2011 // If end-of-line is significant, check whether this token is on a
2012 // new line.
2013 std::pair<FileID, unsigned> ExpLoc =
2014 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2015 if (ExpLoc.first != FID ||
2016 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2017 // If this is a single-line __asm, we're done.
2018 if (!InBraces)
2019 break;
2020 // We're no longer in a comment.
2021 InAsmComment = false;
2022 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2023 // Single-line asm always ends when a closing brace is seen.
2024 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2025 // does MSVC do here?
2026 break;
2027 }
2028 }
2029 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2030 BraceCount == (savedBraceCount + 1)) {
2031 // Consume the closing brace, and finish
2032 EndLoc = ConsumeBrace();
2033 break;
2034 }
2035
2036 // Consume the next token; make sure we don't modify the brace count etc.
2037 // if we are in a comment.
2038 EndLoc = TokLoc;
2039 if (InAsmComment)
2040 PP.Lex(Tok);
2041 else {
2042 AsmToks.push_back(Tok);
2043 ConsumeAnyToken();
2044 }
2045 TokLoc = Tok.getLocation();
2046 ++NumTokensRead;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002047 } while (1);
Chad Rosier32503022012-06-11 20:47:18 +00002048
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002049 if (InBraces && BraceCount != savedBraceCount) {
2050 // __asm without closing brace (this can happen at EOF).
2051 Diag(Tok, diag::err_expected_rbrace);
2052 Diag(LBraceLoc, diag::note_matching) << "{";
2053 return StmtError();
2054 } else if (NumTokensRead == 0) {
2055 // Empty __asm.
2056 Diag(Tok, diag::err_expected_lbrace);
2057 return StmtError();
2058 }
2059
John McCallf413f5e2013-05-03 00:10:13 +00002060 // Okay, prepare to use MC to parse the assembly.
2061 SmallVector<StringRef, 4> ConstraintRefs;
2062 SmallVector<Expr*, 4> Exprs;
2063 SmallVector<StringRef, 4> ClobberRefs;
2064
2065 // We need an actual supported target.
2066 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2067 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
2068 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2069 ArchTy != llvm::Triple::x86_64);
2070 if (UnsupportedArch)
2071 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
2072
2073 // If we don't support assembly, or the assembly is empty, we don't
2074 // need to instantiate the AsmParser, etc.
2075 if (UnsupportedArch || AsmToks.empty()) {
2076 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2077 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2078 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2079 }
2080
2081 // Expand the tokens into a string buffer.
2082 SmallString<512> AsmString;
2083 SmallVector<unsigned, 8> TokOffsets;
2084 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2085 return StmtError();
2086
2087 // Find the target and create the target specific parser.
2088 std::string Error;
2089 const std::string &TT = TheTriple.getTriple();
2090 const llvm::Target *TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2091
John McCallf413f5e2013-05-03 00:10:13 +00002092 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
Rafael Espindola77056232013-05-13 01:24:18 +00002093 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002094 // Get the instruction descriptor.
2095 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
John McCallf413f5e2013-05-03 00:10:13 +00002096 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2097 OwningPtr<llvm::MCSubtargetInfo>
2098 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2099
2100 llvm::SourceMgr TempSrcMgr;
Bill Wendlingda1e3e72013-06-18 07:22:05 +00002101 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallf413f5e2013-05-03 00:10:13 +00002102 llvm::MemoryBuffer *Buffer =
2103 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2104
2105 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2106 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2107
2108 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2109 OwningPtr<llvm::MCAsmParser>
2110 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2111 OwningPtr<llvm::MCTargetAsmParser>
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002112 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser, *MII));
John McCallf413f5e2013-05-03 00:10:13 +00002113
John McCallf413f5e2013-05-03 00:10:13 +00002114 llvm::MCInstPrinter *IP =
2115 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2116
2117 // Change to the Intel dialect.
2118 Parser->setAssemblerDialect(1);
2119 Parser->setTargetParser(*TargetParser.get());
2120 Parser->setParsingInlineAsm(true);
2121 TargetParser->setParsingInlineAsm(true);
2122
2123 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2124 AsmToks, TokOffsets);
2125 TargetParser->setSemaCallback(&Callback);
2126 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2127 &Callback);
2128
2129 unsigned NumOutputs;
2130 unsigned NumInputs;
2131 std::string AsmStringIR;
2132 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2133 SmallVector<std::string, 4> Constraints;
2134 SmallVector<std::string, 4> Clobbers;
2135 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2136 NumOutputs, NumInputs, OpExprs, Constraints,
2137 Clobbers, MII, IP, Callback))
2138 return StmtError();
2139
2140 // Build the vector of clobber StringRefs.
2141 unsigned NumClobbers = Clobbers.size();
2142 ClobberRefs.resize(NumClobbers);
2143 for (unsigned i = 0; i != NumClobbers; ++i)
2144 ClobberRefs[i] = StringRef(Clobbers[i]);
2145
2146 // Recast the void pointers and build the vector of constraint StringRefs.
2147 unsigned NumExprs = NumOutputs + NumInputs;
2148 ConstraintRefs.resize(NumExprs);
2149 Exprs.resize(NumExprs);
2150 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2151 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2152 if (!OpExpr)
2153 return StmtError();
2154
2155 // Need address of variable.
2156 if (OpExprs[i].second)
2157 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2158 .take();
2159
2160 ConstraintRefs[i] = StringRef(Constraints[i]);
2161 Exprs[i] = OpExpr;
2162 }
2163
Chad Rosierc6c71332012-08-06 20:03:45 +00002164 // FIXME: We should be passing source locations for better diagnostics.
John McCallf413f5e2013-05-03 00:10:13 +00002165 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2166 NumOutputs, NumInputs,
2167 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002168}
2169
Chris Lattner0116c472006-08-15 06:03:28 +00002170/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff69e8f9e2008-02-11 23:15:56 +00002171/// asm-statement:
2172/// gnu-asm-statement
2173/// ms-asm-statement
2174///
2175/// [GNU] gnu-asm-statement:
Chris Lattner0116c472006-08-15 06:03:28 +00002176/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2177///
2178/// [GNU] asm-argument:
2179/// asm-string-literal
2180/// asm-string-literal ':' asm-operands[opt]
2181/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2182/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2183/// ':' asm-clobbers
2184///
2185/// [GNU] asm-clobbers:
2186/// asm-string-literal
2187/// asm-clobbers ',' asm-string-literal
2188///
John McCalldadc5752010-08-24 06:29:42 +00002189StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002190 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattner73c56c02007-10-29 04:04:16 +00002191 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002192
Chad Rosierc8e56e82012-12-05 21:08:21 +00002193 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosier67055f52012-07-10 21:35:27 +00002194 !isTypeQualifier()) {
Steve Naroffb2c80c72008-02-07 03:50:06 +00002195 msAsm = true;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002196 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002197 }
John McCall084e83d2011-03-24 11:26:52 +00002198 DeclSpec DS(AttrFactory);
Chris Lattner0116c472006-08-15 06:03:28 +00002199 SourceLocation Loc = Tok.getLocation();
Alexis Hunt96d5c762009-11-21 08:43:09 +00002200 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002201
Chris Lattner0116c472006-08-15 06:03:28 +00002202 // GNU asms accept, but warn, about type-qualifiers other than volatile.
Chris Lattnera925dc62006-11-28 04:33:46 +00002203 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner6d29c102008-11-18 07:48:38 +00002204 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Chris Lattnera925dc62006-11-28 04:33:46 +00002205 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner6d29c102008-11-18 07:48:38 +00002206 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith8e1ac332013-03-28 01:55:44 +00002207 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2208 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2209 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redlb62406f2008-12-11 19:48:14 +00002210
Chris Lattner0116c472006-08-15 06:03:28 +00002211 // Remember if this was a volatile asm.
Anders Carlsson660bdd12007-11-23 23:12:25 +00002212 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002213 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002214 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Chris Lattner0116c472006-08-15 06:03:28 +00002215 SkipUntil(tok::r_paren);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002216 return StmtError();
Chris Lattner0116c472006-08-15 06:03:28 +00002217 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002218 BalancedDelimiterTracker T(*this, tok::l_paren);
2219 T.consumeOpen();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002220
John McCalldadc5752010-08-24 06:29:42 +00002221 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002222 if (AsmString.isInvalid()) {
Richard Smithd67aea22012-03-06 03:21:47 +00002223 // Consume up to and including the closing paren.
2224 T.skipToEnd();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002225 return StmtError();
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002226 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002227
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002228 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002229 ExprVector Constraints;
2230 ExprVector Exprs;
2231 ExprVector Clobbers;
Chris Lattner0116c472006-08-15 06:03:28 +00002232
Anders Carlsson19fe1162008-02-05 23:03:50 +00002233 if (Tok.is(tok::r_paren)) {
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002234 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002235 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002236 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2237 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2238 Constraints, Exprs, AsmString.take(),
2239 Clobbers, T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002240 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002241
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002242 // Parse Outputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002243 bool AteExtraColon = false;
2244 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2245 // In C++ mode, parse "::" like ": :".
2246 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002247 ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002248
Chris Lattner15768502009-12-20 23:08:04 +00002249 if (!AteExtraColon &&
2250 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002251 return StmtError();
2252 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002253
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002254 unsigned NumOutputs = Names.size();
2255
2256 // Parse Inputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002257 if (AteExtraColon ||
2258 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2259 // In C++ mode, parse "::" like ": :".
2260 if (AteExtraColon)
2261 AteExtraColon = false;
2262 else {
2263 AteExtraColon = Tok.is(tok::coloncolon);
2264 ConsumeToken();
2265 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002266
Chris Lattner15768502009-12-20 23:08:04 +00002267 if (!AteExtraColon &&
2268 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002269 return StmtError();
2270 }
2271
2272 assert(Names.size() == Constraints.size() &&
2273 Constraints.size() == Exprs.size() &&
2274 "Input operand size mismatch!");
2275
2276 unsigned NumInputs = Names.size() - NumOutputs;
2277
2278 // Parse the clobbers, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002279 if (AteExtraColon || Tok.is(tok::colon)) {
2280 if (!AteExtraColon)
2281 ConsumeToken();
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002282
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002283 // Parse the asm-string list for clobbers if present.
2284 if (Tok.isNot(tok::r_paren)) {
2285 while (1) {
John McCalldadc5752010-08-24 06:29:42 +00002286 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002287
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002288 if (Clobber.isInvalid())
2289 break;
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002290
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002291 Clobbers.push_back(Clobber.release());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002292
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002293 if (Tok.isNot(tok::comma)) break;
2294 ConsumeToken();
2295 }
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002296 }
2297 }
2298
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002299 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002300 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2301 NumInputs, Names.data(), Constraints, Exprs,
2302 AsmString.take(), Clobbers,
2303 T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002304}
2305
2306/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002307/// asm-statement, assuming the leading ':' token was eaten.
Chris Lattner0116c472006-08-15 06:03:28 +00002308///
2309/// [GNU] asm-operands:
2310/// asm-operand
2311/// asm-operands ',' asm-operand
2312///
2313/// [GNU] asm-operand:
2314/// asm-string-literal '(' expression ')'
2315/// '[' identifier ']' asm-string-literal '(' expression ')'
2316///
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00002317//
2318// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002319bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieu2bd04012011-09-09 02:00:50 +00002320 SmallVectorImpl<Expr *> &Constraints,
2321 SmallVectorImpl<Expr *> &Exprs) {
Chris Lattner0116c472006-08-15 06:03:28 +00002322 // 'asm-operands' isn't present?
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002323 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002324 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002325
2326 while (1) {
Chris Lattner0116c472006-08-15 06:03:28 +00002327 // Read the [id] if present.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002328 if (Tok.is(tok::l_square)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002329 BalancedDelimiterTracker T(*this, tok::l_square);
2330 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00002331
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002332 if (Tok.isNot(tok::identifier)) {
Chris Lattner0116c472006-08-15 06:03:28 +00002333 Diag(Tok, diag::err_expected_ident);
2334 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002335 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002336 }
Mike Stump11289f42009-09-09 15:08:12 +00002337
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002338 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner645ff3f2007-10-29 04:06:22 +00002339 ConsumeToken();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002340
Anders Carlsson9a020f92010-01-30 22:25:16 +00002341 Names.push_back(II);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002342 T.consumeClose();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002343 } else
Anders Carlsson9a020f92010-01-30 22:25:16 +00002344 Names.push_back(0);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002345
John McCalldadc5752010-08-24 06:29:42 +00002346 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002347 if (Constraint.isInvalid()) {
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002348 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002349 return true;
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002350 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002351 Constraints.push_back(Constraint.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002352
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002353 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002354 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Chris Lattner0116c472006-08-15 06:03:28 +00002355 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002356 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002357 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002358
Chris Lattner0116c472006-08-15 06:03:28 +00002359 // Read the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002360 BalancedDelimiterTracker T(*this, tok::l_paren);
2361 T.consumeOpen();
John McCalldadc5752010-08-24 06:29:42 +00002362 ExprResult Res(ParseExpression());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002363 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002364 if (Res.isInvalid()) {
Chris Lattner0116c472006-08-15 06:03:28 +00002365 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002366 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002367 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002368 Exprs.push_back(Res.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002369 // Eat the comma and continue parsing if it exists.
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002370 if (Tok.isNot(tok::comma)) return false;
Chris Lattner0116c472006-08-15 06:03:28 +00002371 ConsumeToken();
2372 }
2373}
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002374
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002375Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002376 assert(Tok.is(tok::l_brace));
2377 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002378
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00002379 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00002380 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002381 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002382 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002383 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002384
John McCallfaf5fb42010-08-26 23:41:50 +00002385 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2386 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002387
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002388 // Do not enter a scope for the brace, as the arguments are in the same scope
2389 // (the function body) as the body itself. Instead, just read the statement
2390 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002391 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002392
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002393 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002394 if (FnBody.isInvalid()) {
2395 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002396 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002397 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002398
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002399 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002400 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002401}
Sebastian Redlb219c902008-12-21 16:41:36 +00002402
Sebastian Redla7b98a72009-04-26 20:35:05 +00002403/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2404///
2405/// function-try-block:
2406/// 'try' ctor-initializer[opt] compound-statement handler-seq
2407///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002408Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002409 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2410 SourceLocation TryLoc = ConsumeToken();
2411
John McCallfaf5fb42010-08-26 23:41:50 +00002412 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2413 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002414
2415 // Constructor initializer list?
2416 if (Tok.is(tok::colon))
2417 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002418 else
2419 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002420
Richard Smith1ab34b32012-11-19 21:13:18 +00002421 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2422 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002423 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002424 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002425 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002426
Sebastian Redld98ecd62009-04-26 21:08:36 +00002427 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002428 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00002429 // If we failed to parse the try-catch, we just give the function an empty
2430 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002431 if (FnBody.isInvalid()) {
2432 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002433 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002434 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002435
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002436 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002437 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002438}
2439
Erik Verbruggen6e922512012-04-12 10:11:59 +00002440bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002441 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00002442 assert(SkipFunctionBodies &&
2443 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002444
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002445 if (!PP.isCodeCompletionEnabled()) {
2446 ConsumeBrace();
2447 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false);
2448 return true;
2449 }
2450
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002451 // We're in code-completion mode. Skip parsing for all function bodies unless
2452 // the body contains the code-completion point.
2453 TentativeParsingAction PA(*this);
2454 ConsumeBrace();
2455 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002456 /*StopAtCodeCompletion=*/true)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002457 PA.Commit();
2458 return true;
2459 }
2460
2461 PA.Revert();
2462 return false;
2463}
2464
Sebastian Redlb219c902008-12-21 16:41:36 +00002465/// ParseCXXTryBlock - Parse a C++ try-block.
2466///
2467/// try-block:
2468/// 'try' compound-statement handler-seq
2469///
Richard Smithc202b282012-04-14 00:33:13 +00002470StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002471 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2472
2473 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002474 return ParseCXXTryBlockCommon(TryLoc);
2475}
2476
2477/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2478/// function-try-block.
2479///
2480/// try-block:
2481/// 'try' compound-statement handler-seq
2482///
2483/// function-try-block:
2484/// 'try' ctor-initializer[opt] compound-statement handler-seq
2485///
2486/// handler-seq:
2487/// handler handler-seq[opt]
2488///
John Wiegley1c0675e2011-04-28 01:08:34 +00002489/// [Borland] try-block:
2490/// 'try' compound-statement seh-except-block
2491/// 'try' compound-statment seh-finally-block
2492///
David Blaikie1c9c9042012-11-10 01:04:23 +00002493StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002494 if (Tok.isNot(tok::l_brace))
2495 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Alexis Hunt96d5c762009-11-21 08:43:09 +00002496 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002497
2498 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikie3403feb2012-11-13 18:51:45 +00002499 Scope::DeclScope | Scope::TryScope |
2500 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002501 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002502 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002503
John Wiegley1c0675e2011-04-28 01:08:34 +00002504 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002505
Richard Smithc202b282012-04-14 00:33:13 +00002506 if ((Tok.is(tok::identifier) &&
2507 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2508 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002509 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2510 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002511 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002512 SourceLocation Loc = ConsumeToken();
2513 Handler = ParseSEHExceptBlock(Loc);
2514 }
2515 else {
2516 SourceLocation Loc = ConsumeToken();
2517 Handler = ParseSEHFinallyBlock(Loc);
2518 }
2519 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002520 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002521
John Wiegley1c0675e2011-04-28 01:08:34 +00002522 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2523 TryLoc,
2524 TryBlock.take(),
2525 Handler.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002526 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002527 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002528 StmtVector Handlers;
Richard Smithc202b282012-04-14 00:33:13 +00002529 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002530 MaybeParseCXX11Attributes(attrs);
John Wiegley1c0675e2011-04-28 01:08:34 +00002531 ProhibitAttributes(attrs);
Sebastian Redlb219c902008-12-21 16:41:36 +00002532
John Wiegley1c0675e2011-04-28 01:08:34 +00002533 if (Tok.isNot(tok::kw_catch))
2534 return StmtError(Diag(Tok, diag::err_expected_catch));
2535 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002536 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002537 if (!Handler.isInvalid())
2538 Handlers.push_back(Handler.release());
2539 }
2540 // Don't bother creating the full statement if we don't have any usable
2541 // handlers.
2542 if (Handlers.empty())
2543 return StmtError();
2544
Robert Wilhelmcafda822013-08-22 09:20:03 +00002545 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002546 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002547}
2548
2549/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2550///
Richard Smith1dba27c2013-01-29 09:02:09 +00002551/// handler:
2552/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002553///
Richard Smith1dba27c2013-01-29 09:02:09 +00002554/// exception-declaration:
2555/// attribute-specifier-seq[opt] type-specifier-seq declarator
2556/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2557/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002558///
David Blaikie1c9c9042012-11-10 01:04:23 +00002559StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002560 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2561
2562 SourceLocation CatchLoc = ConsumeToken();
2563
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002564 BalancedDelimiterTracker T(*this, tok::l_paren);
2565 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redlb219c902008-12-21 16:41:36 +00002566 return StmtError();
2567
2568 // C++ 3.3.2p3:
2569 // The name in a catch exception-declaration is local to the handler and
2570 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002571 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002572 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002573
2574 // exception-declaration is equivalent to '...' or a parameter-declaration
2575 // without default arguments.
John McCall48871652010-08-21 09:40:31 +00002576 Decl *ExceptionDecl = 0;
Sebastian Redlb219c902008-12-21 16:41:36 +00002577 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002578 ParsedAttributesWithRange Attributes(AttrFactory);
2579 MaybeParseCXX11Attributes(Attributes);
2580
John McCall084e83d2011-03-24 11:26:52 +00002581 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002582 DS.takeAttributesFrom(Attributes);
2583
Sebastian Redl54c04d42008-12-22 19:15:10 +00002584 if (ParseCXXTypeSpecifierSeq(DS))
2585 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002586
Sebastian Redlb219c902008-12-21 16:41:36 +00002587 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2588 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002589 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002590 } else
2591 ConsumeToken();
2592
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002593 T.consumeClose();
2594 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002595 return StmtError();
2596
2597 if (Tok.isNot(tok::l_brace))
2598 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2599
Alexis Hunt96d5c762009-11-21 08:43:09 +00002600 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002601 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002602 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002603 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002604
John McCallb268a282010-08-23 23:25:46 +00002605 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002606}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002607
2608void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002609 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002610 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002611 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002612
Douglas Gregor43edb322011-10-24 22:31:10 +00002613 // Handle dependent statements by parsing the braces as a compound statement.
2614 // This is not the same behavior as Visual C++, which don't treat this as a
2615 // compound statement, but for Clang's type checking we can't have anything
2616 // inside these braces escaping to the surrounding code.
2617 if (Result.Behavior == IEB_Dependent) {
2618 if (!Tok.is(tok::l_brace)) {
2619 Diag(Tok, diag::err_expected_lbrace);
Richard Smithc202b282012-04-14 00:33:13 +00002620 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002621 }
Richard Smithc202b282012-04-14 00:33:13 +00002622
2623 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002624 if (Compound.isInvalid())
2625 return;
Richard Smithc202b282012-04-14 00:33:13 +00002626
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002627 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2628 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002629 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002630 Result.Name,
2631 Compound.get());
2632 if (DepResult.isUsable())
2633 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002634 return;
2635 }
Richard Smithc202b282012-04-14 00:33:13 +00002636
Douglas Gregor43edb322011-10-24 22:31:10 +00002637 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2638 if (Braces.consumeOpen()) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002639 Diag(Tok, diag::err_expected_lbrace);
2640 return;
2641 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002642
Douglas Gregor43edb322011-10-24 22:31:10 +00002643 switch (Result.Behavior) {
2644 case IEB_Parse:
2645 // Parse the statements below.
2646 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002647
Douglas Gregor43edb322011-10-24 22:31:10 +00002648 case IEB_Dependent:
2649 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002650
Douglas Gregor43edb322011-10-24 22:31:10 +00002651 case IEB_Skip:
2652 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002653 return;
2654 }
2655
2656 // Condition is true, parse the statements.
2657 while (Tok.isNot(tok::r_brace)) {
2658 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2659 if (R.isUsable())
2660 Stmts.push_back(R.release());
2661 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002662 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002663}