blob: 87074cc09fbbfd65c100e096c8c87377817ca4d2 [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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000026#include "llvm/ADT/SmallString.h"
John McCallf413f5e2013-05-03 00:10:13 +000027#include "llvm/MC/MCAsmInfo.h"
28#include "llvm/MC/MCContext.h"
29#include "llvm/MC/MCObjectFileInfo.h"
30#include "llvm/MC/MCParser/MCAsmParser.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/MC/MCStreamer.h"
33#include "llvm/MC/MCSubtargetInfo.h"
34#include "llvm/MC/MCTargetAsmParser.h"
35#include "llvm/Support/SourceMgr.h"
36#include "llvm/Support/TargetRegistry.h"
37#include "llvm/Support/TargetSelect.h"
Chris Lattner0ccd51e2006-08-09 05:47:47 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// C99 6.8: Statements and Blocks.
42//===----------------------------------------------------------------------===//
43
Richard Smith426a47b2013-10-28 22:04:30 +000044/// \brief Parse a standalone statement (for instance, as the body of an 'if',
45/// 'while', or 'for').
46StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) {
47 StmtResult Res;
48
49 // We may get back a null statement if we found a #pragma. Keep going until
50 // we get an actual statement.
51 do {
52 StmtVector Stmts;
53 Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
54 } while (!Res.isInvalid() && !Res.get());
55
56 return Res;
57}
58
Chris Lattner0ccd51e2006-08-09 05:47:47 +000059/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
60/// StatementOrDeclaration:
61/// statement
62/// declaration
63///
64/// statement:
65/// labeled-statement
66/// compound-statement
67/// expression-statement
68/// selection-statement
69/// iteration-statement
70/// jump-statement
Argyrios Kyrtzidisdee82912008-09-07 18:58:01 +000071/// [C++] declaration-statement
Sebastian Redlb219c902008-12-21 16:41:36 +000072/// [C++] try-block
John Wiegley1c0675e2011-04-28 01:08:34 +000073/// [MS] seh-try-block
Fariborz Jahanian90814572007-10-04 20:19:06 +000074/// [OBC] objc-throw-statement
75/// [OBC] objc-try-catch-statement
Fariborz Jahanianf89ca382008-01-29 18:21:32 +000076/// [OBC] objc-synchronized-statement
Chris Lattner0116c472006-08-15 06:03:28 +000077/// [GNU] asm-statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +000078/// [OMP] openmp-construct [TODO]
79///
80/// labeled-statement:
81/// identifier ':' statement
82/// 'case' constant-expression ':' statement
83/// 'default' ':' statement
84///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000085/// selection-statement:
86/// if-statement
87/// switch-statement
88///
89/// iteration-statement:
90/// while-statement
91/// do-statement
92/// for-statement
93///
Chris Lattner9075bd72006-08-10 04:59:57 +000094/// expression-statement:
95/// expression[opt] ';'
96///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000097/// jump-statement:
98/// 'goto' identifier ';'
99/// 'continue' ';'
100/// 'break' ';'
101/// 'return' expression[opt] ';'
Chris Lattner503fadc2006-08-10 05:45:44 +0000102/// [GNU] 'goto' '*' expression ';'
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000103///
Fariborz Jahanian90814572007-10-04 20:19:06 +0000104/// [OBC] objc-throw-statement:
105/// [OBC] '@' 'throw' expression ';'
Mike Stump11289f42009-09-09 15:08:12 +0000106/// [OBC] '@' 'throw' ';'
107///
John McCalldadc5752010-08-24 06:29:42 +0000108StmtResult
Nico Weber3cef1082011-12-22 23:26:17 +0000109Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
110 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000111
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +0000112 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000113
Richard Smithc202b282012-04-14 00:33:13 +0000114 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000115 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
Richard Smithc202b282012-04-14 00:33:13 +0000116
117 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
118 OnlyStatement, TrailingElseLoc, Attrs);
119
120 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
121 "attributes on empty statement");
122
123 if (Attrs.empty() || Res.isInvalid())
124 return Res;
125
126 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
127}
128
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000129namespace {
130class StatementFilterCCC : public CorrectionCandidateCallback {
131public:
132 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
133 WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) ||
134 nextTok.is(tok::identifier) || nextTok.is(tok::star) ||
135 nextTok.is(tok::amp) || nextTok.is(tok::l_square);
136 WantExpressionKeywords = nextTok.is(tok::l_paren) ||
137 nextTok.is(tok::identifier) ||
138 nextTok.is(tok::arrow) || nextTok.is(tok::period);
139 WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) ||
140 nextTok.is(tok::identifier) ||
141 nextTok.is(tok::l_brace);
142 WantCXXNamedCasts = false;
143 }
144
145 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
146 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
Kaelyn Uhrain07e62722013-10-01 22:00:28 +0000147 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain46b6cdc2013-09-27 19:40:16 +0000148 if (NextToken.is(tok::equal))
149 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain30943ce2013-09-27 23:54:23 +0000150 if (NextToken.is(tok::period) &&
151 candidate.getCorrectionDeclAs<NamespaceDecl>())
152 return false;
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000153 return CorrectionCandidateCallback::ValidateCandidate(candidate);
154 }
155
156private:
157 Token NextToken;
158};
159}
160
Richard Smithc202b282012-04-14 00:33:13 +0000161StmtResult
162Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
163 bool OnlyStatement, SourceLocation *TrailingElseLoc,
164 ParsedAttributesWithRange &Attrs) {
165 const char *SemiError = 0;
166 StmtResult Res;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000167
Chris Lattner503fadc2006-08-10 05:45:44 +0000168 // Cases in this switch statement should fall through if the parser expects
169 // the token to end in a semicolon (in which case SemiError should be set),
170 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000171Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000172 tok::TokenKind Kind = Tok.getKind();
173 SourceLocation AtLoc;
174 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000175 case tok::at: // May be a @try or @throw statement
176 {
Richard Smithc202b282012-04-14 00:33:13 +0000177 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000178 AtLoc = ConsumeToken(); // consume @
Sebastian Redlbab9a4b2008-12-11 20:12:42 +0000179 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000180 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000181
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000182 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000183 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000184 cutOffParsing();
185 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000186
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000187 case tok::identifier: {
188 Token Next = NextToken();
189 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000190 // identifier ':' statement
Richard Smithc202b282012-04-14 00:33:13 +0000191 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000192 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000193
Richard Smith4f605af2012-08-18 00:55:03 +0000194 // Look up the identifier, and typo-correct it to a keyword if it's not
195 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000196 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000197 // Try to limit which sets of keywords should be included in typo
198 // correction based on what the next token is.
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000199 StatementFilterCCC Validator(Next);
200 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
Richard Smith4f605af2012-08-18 00:55:03 +0000201 == ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000202 // Handle errors here by skipping up to the next semicolon or '}', and
203 // eat the semicolon if that's what stopped us.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000204 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000205 if (Tok.is(tok::semi))
206 ConsumeToken();
207 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000208 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000209
Richard Smith4f605af2012-08-18 00:55:03 +0000210 // If the identifier was typo-corrected, try again.
211 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000212 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000213 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000214
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000215 // Fall through
216 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000217
Chris Lattner803802d2009-03-24 17:04:48 +0000218 default: {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000219 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000220 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek5eec2b02010-11-10 05:59:39 +0000221 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000222 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000223 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000224 }
225
226 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000227 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000228 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000229 }
Mike Stump11289f42009-09-09 15:08:12 +0000230
Richard Smithc202b282012-04-14 00:33:13 +0000231 return ParseExprStatement();
Chris Lattner803802d2009-03-24 17:04:48 +0000232 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000233
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000234 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000235 return ParseCaseStatement();
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000236 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000237 return ParseDefaultStatement();
Sebastian Redl042ad952008-12-11 19:30:53 +0000238
Chris Lattner9075bd72006-08-10 04:59:57 +0000239 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000240 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000241 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000242 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
243 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000244 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000245
Chris Lattner9075bd72006-08-10 04:59:57 +0000246 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000247 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000248 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000249 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000250
Chris Lattner9075bd72006-08-10 04:59:57 +0000251 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000252 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000253 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000254 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000255 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000256 break;
257 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000258 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000259
260 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000261 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000262 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000263 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000264 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000265 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000266 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000267 break;
268 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000269 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000270 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000271 break;
272 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000273 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000274 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000275 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000276
Sebastian Redlb219c902008-12-21 16:41:36 +0000277 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000278 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000279 bool msAsm = false;
280 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000281 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000282 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000283 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000284 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000285 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000286
Sebastian Redlb219c902008-12-21 16:41:36 +0000287 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000288 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000289
290 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000291 ProhibitAttributes(Attrs); // TODO: is it correct?
292 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000293
294 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000295 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000296 HandlePragmaVisibility();
297 return StmtEmpty();
298
299 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000300 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000301 HandlePragmaPack();
302 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000303
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000304 case tok::annot_pragma_msstruct:
305 ProhibitAttributes(Attrs);
306 HandlePragmaMSStruct();
307 return StmtEmpty();
308
Eli Friedmanae8ee252012-10-08 23:52:38 +0000309 case tok::annot_pragma_align:
310 ProhibitAttributes(Attrs);
311 HandlePragmaAlign();
312 return StmtEmpty();
313
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000314 case tok::annot_pragma_weak:
315 ProhibitAttributes(Attrs);
316 HandlePragmaWeak();
317 return StmtEmpty();
318
319 case tok::annot_pragma_weakalias:
320 ProhibitAttributes(Attrs);
321 HandlePragmaWeakAlias();
322 return StmtEmpty();
323
324 case tok::annot_pragma_redefine_extname:
325 ProhibitAttributes(Attrs);
326 HandlePragmaRedefineExtname();
327 return StmtEmpty();
328
Eli Friedman68be1642012-10-04 02:36:51 +0000329 case tok::annot_pragma_fp_contract:
Richard Smithca9b0b62013-11-15 21:10:54 +0000330 ProhibitAttributes(Attrs);
Lang Hamesa930e712012-10-21 01:10:01 +0000331 Diag(Tok, diag::err_pragma_fp_contract_scope);
332 ConsumeToken();
333 return StmtError();
334
Eli Friedman68be1642012-10-04 02:36:51 +0000335 case tok::annot_pragma_opencl_extension:
336 ProhibitAttributes(Attrs);
337 HandlePragmaOpenCLExtension();
338 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000339
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000340 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000341 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000342 return HandlePragmaCaptured();
343
Alexey Bataeva769e072013-03-22 06:34:35 +0000344 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000345 ProhibitAttributes(Attrs);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000346 return ParseOpenMPDeclarativeOrExecutableDirective();
347
David Majnemer4bb09802014-02-10 19:50:15 +0000348 case tok::annot_pragma_ms_pointers_to_members:
349 ProhibitAttributes(Attrs);
350 HandlePragmaMSPointersToMembers();
351 return StmtEmpty();
352
Sebastian Redlb219c902008-12-21 16:41:36 +0000353 }
354
Chris Lattner503fadc2006-08-10 05:45:44 +0000355 // If we reached this code, the statement must end in a semicolon.
Alp Toker97650562014-01-10 11:19:30 +0000356 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000357 // If the result was valid, then we do want to diagnose this. Use
358 // ExpectAndConsume to emit the diagnostic, even though we know it won't
359 // succeed.
360 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000361 // Skip until we see a } or ;, but don't eat it.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000362 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner503fadc2006-08-10 05:45:44 +0000363 }
Mike Stump11289f42009-09-09 15:08:12 +0000364
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000365 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000366}
367
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000368/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000369StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000370 // If a case keyword is missing, this is where it should be inserted.
371 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000372
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000373 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000374 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000375 if (Expr.isInvalid()) {
376 // If the expression is invalid, skip ahead to the next semicolon or '}'.
377 // Not doing this opens us up to the possibility of infinite loops if
378 // ParseExpression does not consume any tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000379 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000380 if (Tok.is(tok::semi))
381 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000382 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000383 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000384
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000385 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
386 Actions.CheckCaseExpression(Expr.get())) {
387 // If a constant expression is followed by a colon inside a switch block,
388 // suggest a missing case keyword.
389 Diag(OldToken, diag::err_expected_case_before_expression)
390 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000391
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000392 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000393 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000394 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000395
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000396 // Otherwise, eat the semicolon.
397 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000398 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000399}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000400
Richard Smithc202b282012-04-14 00:33:13 +0000401StmtResult Parser::ParseSEHTryBlock() {
John Wiegley1c0675e2011-04-28 01:08:34 +0000402 assert(Tok.is(tok::kw___try) && "Expected '__try'");
403 SourceLocation Loc = ConsumeToken();
404 return ParseSEHTryBlockCommon(Loc);
405}
406
407/// ParseSEHTryBlockCommon
408///
409/// seh-try-block:
410/// '__try' compound-statement seh-handler
411///
412/// seh-handler:
413/// seh-except-block
414/// seh-finally-block
415///
416StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
417 if(Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000418 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley1c0675e2011-04-28 01:08:34 +0000419
Joao Matos566359c2012-09-04 17:49:35 +0000420 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000421 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000422 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000423
424 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000425 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000426 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000427 SourceLocation Loc = ConsumeToken();
428 Handler = ParseSEHExceptBlock(Loc);
429 } else if (Tok.is(tok::kw___finally)) {
430 SourceLocation Loc = ConsumeToken();
431 Handler = ParseSEHFinallyBlock(Loc);
432 } else {
433 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
434 }
435
436 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000437 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000438
439 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
440 TryLoc,
441 TryBlock.take(),
442 Handler.take());
443}
444
445/// ParseSEHExceptBlock - Handle __except
446///
447/// seh-except-block:
448/// '__except' '(' seh-filter-expression ')' compound-statement
449///
450StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
451 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
452 raii2(Ident___exception_code, false),
453 raii3(Ident_GetExceptionCode, false);
454
Alp Toker383d2c42014-01-01 03:08:43 +0000455 if (ExpectAndConsume(tok::l_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000456 return StmtError();
457
458 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
459
David Blaikiebbafb8a2012-03-11 07:00:24 +0000460 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000461 Ident__exception_info->setIsPoisoned(false);
462 Ident___exception_info->setIsPoisoned(false);
463 Ident_GetExceptionInfo->setIsPoisoned(false);
464 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000465 ExprResult FilterExpr(ParseExpression());
Francois Pichetbfaf4772011-04-28 03:14:31 +0000466
David Blaikiebbafb8a2012-03-11 07:00:24 +0000467 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000468 Ident__exception_info->setIsPoisoned(true);
469 Ident___exception_info->setIsPoisoned(true);
470 Ident_GetExceptionInfo->setIsPoisoned(true);
471 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000472
473 if(FilterExpr.isInvalid())
474 return StmtError();
475
Alp Toker383d2c42014-01-01 03:08:43 +0000476 if (ExpectAndConsume(tok::r_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000477 return StmtError();
478
Richard Smithc202b282012-04-14 00:33:13 +0000479 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000480
481 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000482 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000483
484 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
485}
486
487/// ParseSEHFinallyBlock - Handle __finally
488///
489/// seh-finally-block:
490/// '__finally' compound-statement
491///
492StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
493 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
494 raii2(Ident___abnormal_termination, false),
495 raii3(Ident_AbnormalTermination, false);
496
Richard Smithc202b282012-04-14 00:33:13 +0000497 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000498 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000499 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000500
501 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000502}
503
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000504/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000505///
506/// labeled-statement:
507/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000508/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000509///
Richard Smithc202b282012-04-14 00:33:13 +0000510StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000511 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
512 "Not an identifier!");
513
514 Token IdentTok = Tok; // Save the whole token.
515 ConsumeToken(); // eat the identifier.
516
517 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000518
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000519 // identifier ':' statement
520 SourceLocation ColonLoc = ConsumeToken();
521
Richard Smitha3e01cf2013-11-15 22:45:29 +0000522 // Read label attributes, if present.
523 StmtResult SubStmt;
524 if (Tok.is(tok::kw___attribute)) {
525 ParsedAttributesWithRange TempAttrs(AttrFactory);
526 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000527
Richard Smitha3e01cf2013-11-15 22:45:29 +0000528 // In C++, GNU attributes only apply to the label if they are followed by a
529 // semicolon, to disambiguate label attributes from attributes on a labeled
530 // declaration.
531 //
532 // This doesn't quite match what GCC does; if the attribute list is empty
533 // and followed by a semicolon, GCC will reject (it appears to parse the
534 // attributes as part of a statement in that case). That looks like a bug.
535 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
536 attrs.takeAllFrom(TempAttrs);
537 else if (isDeclarationStatement()) {
538 StmtVector Stmts;
539 // FIXME: We should do this whether or not we have a declaration
540 // statement, but that doesn't work correctly (because ProhibitAttributes
541 // can't handle GNU attributes), so only call it in the one case where
542 // GNU attributes are allowed.
543 SubStmt = ParseStatementOrDeclarationAfterAttributes(
544 Stmts, /*OnlyStmts*/ true, 0, TempAttrs);
545 if (!TempAttrs.empty() && !SubStmt.isInvalid())
546 SubStmt = Actions.ProcessStmtAttributes(
547 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
548 } else {
Alp Toker383d2c42014-01-01 03:08:43 +0000549 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smitha3e01cf2013-11-15 22:45:29 +0000550 }
551 }
552
553 // If we've not parsed a statement yet, parse one now.
554 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
555 SubStmt = ParseStatement();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000556
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000557 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000558 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000559 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000560
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000561 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
562 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000563 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000564 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000565 attrs.clear();
566 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000567
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000568 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
569 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000570}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000571
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000572/// ParseCaseStatement
573/// labeled-statement:
574/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000575/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000576///
Richard Smithc202b282012-04-14 00:33:13 +0000577StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000578 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000579
Chris Lattner34a22092009-03-04 04:23:07 +0000580 // It is very very common for code to contain many case statements recursively
581 // nested, as in (but usually without indentation):
582 // case 1:
583 // case 2:
584 // case 3:
585 // case 4:
586 // case 5: etc.
587 //
588 // Parsing this naively works, but is both inefficient and can cause us to run
589 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000590 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000591 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smitha3e01cf2013-11-15 22:45:29 +0000592 // weirdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000593
Chris Lattner34a22092009-03-04 04:23:07 +0000594 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
595 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000596 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000597
Chris Lattner34a22092009-03-04 04:23:07 +0000598 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
599 // gets updated each time a new case is parsed, and whose body is unset so
600 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieu3481fcd2011-09-09 02:16:15 +0000601 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattner34a22092009-03-04 04:23:07 +0000603 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000604 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000605 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000606 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
607 ConsumeToken(); // eat the 'case'.
Mike Stump11289f42009-09-09 15:08:12 +0000608
Douglas Gregord328d572009-09-21 18:10:23 +0000609 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000610 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000611 cutOffParsing();
612 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000613 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000614
Chris Lattner125c0ee2009-12-10 00:38:54 +0000615 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
616 /// Disable this form of error recovery while we're parsing the case
617 /// expression.
618 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000619
Richard Trieu2c850c02011-04-21 21:44:26 +0000620 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
621 MissingCase = false;
Chris Lattner34a22092009-03-04 04:23:07 +0000622 if (LHS.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000623 SkipUntil(tok::colon, StopAtSemi);
Sebastian Redl042ad952008-12-11 19:30:53 +0000624 return StmtError();
Chris Lattner476c3ad2006-08-13 22:09:58 +0000625 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000626
Chris Lattner34a22092009-03-04 04:23:07 +0000627 // GNU case range extension.
628 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000629 ExprResult RHS;
Alp Tokerec543272013-12-24 09:48:30 +0000630 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
631 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Chris Lattner34a22092009-03-04 04:23:07 +0000632 RHS = ParseConstantExpression();
633 if (RHS.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000634 SkipUntil(tok::colon, StopAtSemi);
Chris Lattner34a22092009-03-04 04:23:07 +0000635 return StmtError();
636 }
637 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000638
Chris Lattner125c0ee2009-12-10 00:38:54 +0000639 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000640
Alp Tokerec543272013-12-24 09:48:30 +0000641 if (TryConsumeToken(tok::colon, ColonLoc)) {
Alp Tokerec543272013-12-24 09:48:30 +0000642 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
Alp Toker97650562014-01-10 11:19:30 +0000643 // Treat "case blah;" as a typo for "case blah:".
Alp Tokerec543272013-12-24 09:48:30 +0000644 Diag(ColonLoc, diag::err_expected_after)
645 << "'case'" << tok::colon
646 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000647 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000648 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000649 Diag(ExpectedLoc, diag::err_expected_after)
650 << "'case'" << tok::colon
651 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000652 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000653 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000654
John McCalldadc5752010-08-24 06:29:42 +0000655 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000656 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
657 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000658
Chris Lattner34a22092009-03-04 04:23:07 +0000659 // If we had a sema error parsing this case, then just ignore it and
660 // continue parsing the sub-stmt.
661 if (Case.isInvalid()) {
662 if (TopLevelCase.isInvalid()) // No parsed case stmts.
663 return ParseStatement();
664 // Otherwise, just don't add it as a nested case.
665 } else {
666 // If this is the first case statement we parsed, it becomes TopLevelCase.
667 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000668 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000669 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000670 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000671 else
John McCallb268a282010-08-23 23:25:46 +0000672 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000673 DeepestParsedCaseStmt = NextDeepest;
674 }
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattner34a22092009-03-04 04:23:07 +0000676 // Handle all case statements.
677 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000678
Chris Lattner34a22092009-03-04 04:23:07 +0000679 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattner34a22092009-03-04 04:23:07 +0000681 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000682 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattner34a22092009-03-04 04:23:07 +0000684 if (Tok.isNot(tok::r_brace)) {
685 SubStmt = ParseStatement();
686 } else {
687 // Nicely diagnose the common error "switch (X) { case 4: }", which is
688 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000689 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000690 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
691 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner34a22092009-03-04 04:23:07 +0000692 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000693 }
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner34a22092009-03-04 04:23:07 +0000695 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000696 if (SubStmt.isInvalid())
Chris Lattner34a22092009-03-04 04:23:07 +0000697 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000698
Chris Lattner34a22092009-03-04 04:23:07 +0000699 // Install the body into the most deeply-nested case.
John McCallb268a282010-08-23 23:25:46 +0000700 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl042ad952008-12-11 19:30:53 +0000701
Chris Lattner34a22092009-03-04 04:23:07 +0000702 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000703 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000704}
705
706/// ParseDefaultStatement
707/// labeled-statement:
708/// 'default' ':' statement
709/// Note that this does not parse the 'statement' at the end.
710///
Richard Smithc202b282012-04-14 00:33:13 +0000711StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000712 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000713 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000714
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000715 SourceLocation ColonLoc;
Alp Tokerec543272013-12-24 09:48:30 +0000716 if (TryConsumeToken(tok::colon, ColonLoc)) {
Alp Tokerec543272013-12-24 09:48:30 +0000717 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
Alp Toker97650562014-01-10 11:19:30 +0000718 // Treat "default;" as a typo for "default:".
Alp Tokerec543272013-12-24 09:48:30 +0000719 Diag(ColonLoc, diag::err_expected_after)
720 << "'default'" << tok::colon
721 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000722 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000723 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000724 Diag(ExpectedLoc, diag::err_expected_after)
725 << "'default'" << tok::colon
726 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000727 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000728 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000729
Richard Smith1002d102012-02-17 01:35:32 +0000730 StmtResult SubStmt;
731
732 if (Tok.isNot(tok::r_brace)) {
733 SubStmt = ParseStatement();
734 } else {
735 // Diagnose the common error "switch (X) {... default: }", which is
736 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000737 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000738 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
739 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
740 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000741 }
742
Richard Smith1002d102012-02-17 01:35:32 +0000743 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000744 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000745 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000746
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000747 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000748 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000749}
750
Richard Smithc202b282012-04-14 00:33:13 +0000751StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
752 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000753}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000754
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000755/// ParseCompoundStatement - Parse a "{}" block.
756///
757/// compound-statement: [C99 6.8.2]
758/// { block-item-list[opt] }
759/// [GNU] { label-declarations block-item-list } [TODO]
760///
761/// block-item-list:
762/// block-item
763/// block-item-list block-item
764///
765/// block-item:
766/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000767/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000768/// statement
769/// [OMP] openmp-directive [TODO]
770///
771/// [GNU] label-declarations:
772/// [GNU] label-declaration
773/// [GNU] label-declarations label-declaration
774///
775/// [GNU] label-declaration:
776/// [GNU] '__label__' identifier-list ';'
777///
778/// [OMP] openmp-directive: [TODO]
779/// [OMP] barrier-directive
780/// [OMP] flush-directive
Chris Lattner30f910e2006-10-16 05:52:41 +0000781///
Richard Smithc202b282012-04-14 00:33:13 +0000782StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000783 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000784 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000785
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000786 // Enter a scope to hold everything within the compound stmt. Compound
787 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000788 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000789
790 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000791 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000792}
793
Lang Hames2954cea2012-11-03 22:29:05 +0000794/// Parse any pragmas at the start of the compound expression. We handle these
795/// separately since some pragmas (FP_CONTRACT) must appear before any C
796/// statement in the compound, but may be intermingled with other pragmas.
797void Parser::ParseCompoundStatementLeadingPragmas() {
798 bool checkForPragmas = true;
799 while (checkForPragmas) {
800 switch (Tok.getKind()) {
801 case tok::annot_pragma_vis:
802 HandlePragmaVisibility();
803 break;
804 case tok::annot_pragma_pack:
805 HandlePragmaPack();
806 break;
807 case tok::annot_pragma_msstruct:
808 HandlePragmaMSStruct();
809 break;
810 case tok::annot_pragma_align:
811 HandlePragmaAlign();
812 break;
813 case tok::annot_pragma_weak:
814 HandlePragmaWeak();
815 break;
816 case tok::annot_pragma_weakalias:
817 HandlePragmaWeakAlias();
818 break;
819 case tok::annot_pragma_redefine_extname:
820 HandlePragmaRedefineExtname();
821 break;
822 case tok::annot_pragma_opencl_extension:
823 HandlePragmaOpenCLExtension();
824 break;
825 case tok::annot_pragma_fp_contract:
826 HandlePragmaFPContract();
827 break;
David Majnemer4bb09802014-02-10 19:50:15 +0000828 case tok::annot_pragma_ms_pointers_to_members:
829 HandlePragmaMSPointersToMembers();
830 break;
Lang Hames2954cea2012-11-03 22:29:05 +0000831 default:
832 checkForPragmas = false;
833 break;
834 }
835 }
836
837}
838
Chris Lattnerf2978802007-01-21 06:52:16 +0000839/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000840/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000841/// consume the '}' at the end of the block. It does not manipulate the scope
842/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000843StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000844 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000845 Tok.getLocation(),
846 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000847
848 // Record the state of the FP_CONTRACT pragma, restore on leaving the
849 // compound statement.
850 Sema::FPContractStateRAII SaveFPContractState(Actions);
851
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000852 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000853 BalancedDelimiterTracker T(*this, tok::l_brace);
854 if (T.consumeOpen())
855 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000856
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000857 Sema::CompoundScopeRAII CompoundScope(Actions);
858
Lang Hames2954cea2012-11-03 22:29:05 +0000859 // Parse any pragmas at the beginning of the compound statement.
860 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000861
Lang Hames2954cea2012-11-03 22:29:05 +0000862 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000863
Chris Lattner43e7f312011-02-18 02:08:43 +0000864 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
865 // only allowed at the start of a compound stmt regardless of the language.
866 while (Tok.is(tok::kw___label__)) {
867 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000868
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000869 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000870 while (1) {
871 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +0000872 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner43e7f312011-02-18 02:08:43 +0000873 break;
874 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000875
Chris Lattner43e7f312011-02-18 02:08:43 +0000876 IdentifierInfo *II = Tok.getIdentifierInfo();
877 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000878 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000879
Alp Tokerec543272013-12-24 09:48:30 +0000880 if (!TryConsumeToken(tok::comma))
Chris Lattner43e7f312011-02-18 02:08:43 +0000881 break;
Chris Lattner43e7f312011-02-18 02:08:43 +0000882 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000883
John McCall084e83d2011-03-24 11:26:52 +0000884 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000885 DeclGroupPtrTy Res =
886 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000887 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000888
Chris Lattner02f1b612012-04-28 16:12:17 +0000889 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000890 if (R.isUsable())
891 Stmts.push_back(R.release());
892 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000893
Richard Smith34f30512013-11-23 04:06:09 +0000894 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000895 if (Tok.is(tok::annot_pragma_unused)) {
896 HandlePragmaUnused();
897 continue;
898 }
899
David Blaikiebbafb8a2012-03-11 07:00:24 +0000900 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet4a7de3e2011-05-06 20:48:22 +0000901 Tok.is(tok::kw___if_not_exists))) {
902 ParseMicrosoftIfExistsStatement(Stmts);
903 continue;
904 }
905
John McCalldadc5752010-08-24 06:29:42 +0000906 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000907 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000908 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000909 } else {
910 // __extension__ can start declarations and it can also be a unary
911 // operator for expressions. Consume multiple __extension__ markers here
912 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000913 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000914 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000915 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000916 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000917
John McCall084e83d2011-03-24 11:26:52 +0000918 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000919 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000920
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000921 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +0000922 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +0000923 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +0000924 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +0000925 ExtensionRAIIObject O(Diags);
926
Chris Lattner49836b42009-04-02 04:16:50 +0000927 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000928 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
929 Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000930 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000931 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000932 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000933 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +0000934 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +0000935
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000936 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000937 SkipUntil(tok::semi);
938 continue;
939 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +0000940
Alexis Hunt96d5c762009-11-21 08:43:09 +0000941 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +0000942 // Eat the semicolon at the end of stmt and convert the expr into a
943 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000944 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000945 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000946 }
947 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000948
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000949 if (R.isUsable())
Sebastian Redld9f7b1c2008-12-10 00:02:53 +0000950 Stmts.push_back(R.release());
Chris Lattner30f910e2006-10-16 05:52:41 +0000951 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000952
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000953 SourceLocation CloseLoc = Tok.getLocation();
954
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000955 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +0000956 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000957 // Recover by creating a compound statement with what we parsed so far,
958 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +0000959 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +0000960
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000961 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000962 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000963}
Chris Lattnerc951dae2006-08-10 04:23:57 +0000964
Chris Lattnerc0081db2008-12-12 06:31:07 +0000965/// ParseParenExprOrCondition:
966/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +0000967/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +0000968///
969/// This function parses and performs error recovery on the specified condition
970/// or expression (depending on whether we're in C++ or C mode). This function
971/// goes out of its way to recover well. It returns true if there was a parser
972/// error (the right paren couldn't be found), which indicates that the caller
973/// should try to recover harder. It returns false if the condition is
974/// successfully parsed. Note that a successful parse can still have semantic
975/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +0000976bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +0000977 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +0000978 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000979 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000980 BalancedDelimiterTracker T(*this, tok::l_paren);
981 T.consumeOpen();
982
David Blaikiebbafb8a2012-03-11 07:00:24 +0000983 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +0000984 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000985 else {
986 ExprResult = ParseExpression();
John McCall48871652010-08-21 09:40:31 +0000987 DeclResult = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000988
Douglas Gregore60e41a2010-05-06 17:25:47 +0000989 // If required, convert to a boolean value.
990 if (!ExprResult.isInvalid() && ConvertToBoolean)
991 ExprResult
John McCallb268a282010-08-23 23:25:46 +0000992 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Chris Lattnerc0081db2008-12-12 06:31:07 +0000995 // If the parser was confused by the condition and we don't have a ')', try to
996 // recover by skipping ahead to a semi and bailing out. If condexp is
997 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +0000998 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +0000999 SkipUntil(tok::semi);
1000 // Skipping may have stopped if it found the containing ')'. If so, we can
1001 // continue parsing the if statement.
1002 if (Tok.isNot(tok::r_paren))
1003 return true;
1004 }
Mike Stump11289f42009-09-09 15:08:12 +00001005
Chris Lattnerc0081db2008-12-12 06:31:07 +00001006 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001007 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +00001008
Chris Lattner70d44982012-04-28 16:24:20 +00001009 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1010 // that all callers are looking for a statement after the condition, so ")"
1011 // isn't valid.
1012 while (Tok.is(tok::r_paren)) {
1013 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1014 << FixItHint::CreateRemoval(Tok.getLocation());
1015 ConsumeParen();
1016 }
Chad Rosier67055f52012-07-10 21:35:27 +00001017
Chris Lattnerc0081db2008-12-12 06:31:07 +00001018 return false;
1019}
1020
1021
Chris Lattnerc951dae2006-08-10 04:23:57 +00001022/// ParseIfStatement
1023/// if-statement: [C99 6.8.4.1]
1024/// 'if' '(' expression ')' statement
1025/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001026/// [C++] 'if' '(' condition ')' statement
1027/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +00001028///
Richard Smithc202b282012-04-14 00:33:13 +00001029StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001030 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001031 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +00001032
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001033 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001034 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +00001035 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +00001036 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +00001037 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001038
David Blaikiebbafb8a2012-03-11 07:00:24 +00001039 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001040
Chris Lattner2dd1b722007-08-26 23:08:06 +00001041 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1042 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001043 //
1044 // C++ 6.4p3:
1045 // A name introduced by a declaration in a condition is in scope from its
1046 // point of declaration until the end of the substatements controlled by the
1047 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001048 // C++ 3.3.2p4:
1049 // Names declared in the for-init-statement, and in the condition of if,
1050 // while, for, and switch statements are local to the if, while, for, or
1051 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001052 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001053 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001054
Chris Lattnerc951dae2006-08-10 04:23:57 +00001055 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001056 ExprResult CondExp;
John McCall48871652010-08-21 09:40:31 +00001057 Decl *CondVar = 0;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001058 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001059 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001060
David Blaikiea5696df2012-05-16 04:20:04 +00001061 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001062
Chris Lattner8fb26252007-08-22 05:28:50 +00001063 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001064 // there is no compound stmt. C90 does not have this clause. We only do this
1065 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001066 //
1067 // C++ 6.4p1:
1068 // The substatement in a selection-statement (each substatement, in the else
1069 // form of the if statement) implicitly defines a local scope.
1070 //
1071 // For C++ we create a scope for the condition and a new scope for
1072 // substatements because:
1073 // -When the 'then' scope exits, we want the condition declaration to still be
1074 // active for the 'else' scope too.
1075 // -Sema will detect name clashes by considering declarations of a
1076 // 'ControlScope' as part of its direct subscope.
1077 // -If we wanted the condition and substatement to be in the same scope, we
1078 // would have to notify ParseStatement not to create a new scope. It's
1079 // simpler to let it create a new scope.
1080 //
Mike Stump11289f42009-09-09 15:08:12 +00001081 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001082 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001083
Chris Lattner5c5808a2007-10-29 05:08:52 +00001084 // Read the 'then' stmt.
1085 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001086
1087 SourceLocation InnerStatementTrailingElseLoc;
1088 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001089
Chris Lattner37e54f42007-08-22 05:16:28 +00001090 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001091 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001092
Chris Lattnerc951dae2006-08-10 04:23:57 +00001093 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001094 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001095 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001096 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001097
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001098 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001099 if (TrailingElseLoc)
1100 *TrailingElseLoc = Tok.getLocation();
1101
Chris Lattneraf635312006-10-16 06:06:51 +00001102 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001103 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001104
Chris Lattner8fb26252007-08-22 05:28:50 +00001105 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001106 // there is no compound stmt. C90 does not have this clause. We only do
1107 // this if the body isn't a compound statement to avoid push/pop in common
1108 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001109 //
1110 // C++ 6.4p1:
1111 // The substatement in a selection-statement (each substatement, in the else
1112 // form of the if statement) implicitly defines a local scope.
1113 //
Sebastian Redl042ad952008-12-11 19:30:53 +00001114 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001115 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001116
Chris Lattner30f910e2006-10-16 05:52:41 +00001117 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001118
Chris Lattner37e54f42007-08-22 05:16:28 +00001119 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001120 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001121 } else if (Tok.is(tok::code_completion)) {
1122 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001123 cutOffParsing();
1124 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001125 } else if (InnerStatementTrailingElseLoc.isValid()) {
1126 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001127 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001128
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001129 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001130
Chris Lattner5c5808a2007-10-29 05:08:52 +00001131 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001132 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001133 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001134 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1135 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1136 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001137 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001138 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001139 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001140
Chris Lattner5c5808a2007-10-29 05:08:52 +00001141 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001142 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001143 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001144 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001145 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001146
John McCallb268a282010-08-23 23:25:46 +00001147 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001148 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001149}
1150
Chris Lattner9075bd72006-08-10 04:59:57 +00001151/// ParseSwitchStatement
1152/// switch-statement:
1153/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001154/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001155StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001156 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001157 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001158
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001159 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001160 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001161 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001162 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001163 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001164
David Blaikiebbafb8a2012-03-11 07:00:24 +00001165 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001166
Chris Lattner2dd1b722007-08-26 23:08:06 +00001167 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1168 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001169 //
1170 // C++ 6.4p3:
1171 // A name introduced by a declaration in a condition is in scope from its
1172 // point of declaration until the end of the substatements controlled by the
1173 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001174 // C++ 3.3.2p4:
1175 // Names declared in the for-init-statement, and in the condition of if,
1176 // while, for, and switch statements are local to the if, while, for, or
1177 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001178 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001179 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001180 if (C99orCXX)
1181 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001182 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001183
Chris Lattner9075bd72006-08-10 04:59:57 +00001184 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001185 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001186 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001187 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001188 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001189
John McCalldadc5752010-08-24 06:29:42 +00001190 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001191 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001192
Douglas Gregore60e41a2010-05-06 17:25:47 +00001193 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001194 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001195 // FIXME: This is not optimal recovery, but parsing the body is more
1196 // dangerous due to the presence of case and default statements, which
1197 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001198 if (Tok.is(tok::l_brace)) {
1199 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001200 SkipUntil(tok::r_brace);
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001201 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001202 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001203 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001204 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001205
Chris Lattner8fb26252007-08-22 05:28:50 +00001206 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001207 // there is no compound stmt. C90 does not have this clause. We only do this
1208 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001209 //
1210 // C++ 6.4p1:
1211 // The substatement in a selection-statement (each substatement, in the else
1212 // form of the if statement) implicitly defines a local scope.
1213 //
1214 // See comments in ParseIfStatement for why we create a scope for the
1215 // condition and a new scope for substatement in C++.
1216 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001217 getCurScope()->AddFlags(Scope::BreakScope);
Mike Stump11289f42009-09-09 15:08:12 +00001218 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001219 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001220
Chris Lattner9075bd72006-08-10 04:59:57 +00001221 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001222 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001223
Chris Lattner8fd2d012010-01-24 01:50:29 +00001224 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001225 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001226 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001227
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001228 if (Body.isInvalid()) {
Chris Lattner8fd2d012010-01-24 01:50:29 +00001229 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001230
1231 // Put the synthesized null statement on the same line as the end of switch
1232 // condition.
1233 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1234 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1235 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001236
John McCallb268a282010-08-23 23:25:46 +00001237 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001238}
1239
1240/// ParseWhileStatement
1241/// while-statement: [C99 6.8.5.1]
1242/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001243/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001244StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001245 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001246 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001247 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001248
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001249 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001250 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001251 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001252 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001253 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001254
David Blaikiebbafb8a2012-03-11 07:00:24 +00001255 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001256
Chris Lattner2dd1b722007-08-26 23:08:06 +00001257 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1258 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001259 //
1260 // C++ 6.4p3:
1261 // A name introduced by a declaration in a condition is in scope from its
1262 // point of declaration until the end of the substatements controlled by the
1263 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001264 // C++ 3.3.2p4:
1265 // Names declared in the for-init-statement, and in the condition of if,
1266 // while, for, and switch statements are local to the if, while, for, or
1267 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001268 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001269 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001270 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001271 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1272 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001273 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001274 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1275 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001276
Chris Lattner9075bd72006-08-10 04:59:57 +00001277 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001278 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001279 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001280 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001281 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001282
David Blaikiea5696df2012-05-16 04:20:04 +00001283 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001284
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001285 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001286 // there is no compound stmt. C90 does not have this clause. We only do this
1287 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001288 //
1289 // C++ 6.5p2:
1290 // The substatement in an iteration-statement implicitly defines a local scope
1291 // which is entered and exited each time through the loop.
1292 //
1293 // See comments in ParseIfStatement for why we create a scope for the
1294 // condition and a new scope for substatement in C++.
1295 //
Mike Stump11289f42009-09-09 15:08:12 +00001296 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001297 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001298
Chris Lattner9075bd72006-08-10 04:59:57 +00001299 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001300 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001301
Chris Lattner8fb26252007-08-22 05:28:50 +00001302 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001303 InnerScope.Exit();
1304 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001305
John McCall48871652010-08-21 09:40:31 +00001306 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001307 return StmtError();
1308
John McCallb268a282010-08-23 23:25:46 +00001309 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001310}
1311
1312/// ParseDoStatement
1313/// do-statement: [C99 6.8.5.2]
1314/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001315/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001316StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001317 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001318 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001319
Chris Lattner2dd1b722007-08-26 23:08:06 +00001320 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1321 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001322 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001323 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001324 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001325 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001326 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001327
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001328 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001329
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001330 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001331 // there is no compound stmt. C90 does not have this clause. We only do this
1332 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001333 //
1334 // C++ 6.5p2:
1335 // The substatement in an iteration-statement implicitly defines a local scope
1336 // which is entered and exited each time through the loop.
1337 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001338 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001339 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001340 Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001341
Chris Lattner9075bd72006-08-10 04:59:57 +00001342 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001343 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001344
Chris Lattner8fb26252007-08-22 05:28:50 +00001345 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001346 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001347
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001348 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001349 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001350 Diag(Tok, diag::err_expected_while);
Alp Tokerec543272013-12-24 09:48:30 +00001351 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001352 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner0046de12008-11-13 18:52:53 +00001353 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001354 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001355 }
Chris Lattneraf635312006-10-16 06:06:51 +00001356 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001357
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001358 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001359 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001360 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001361 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001362 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001363
Richard Smithc2c8bb82013-10-15 01:34:54 +00001364 // Parse the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001365 BalancedDelimiterTracker T(*this, tok::l_paren);
1366 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001367
Richard Smithc2c8bb82013-10-15 01:34:54 +00001368 // A do-while expression is not a condition, so can't have attributes.
1369 DiagnoseAndSkipCXX11Attributes();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001370
John McCalldadc5752010-08-24 06:29:42 +00001371 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001372 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001373 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001374
Sebastian Redlb62406f2008-12-11 19:48:14 +00001375 if (Cond.isInvalid() || Body.isInvalid())
1376 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001377
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001378 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1379 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001380}
1381
1382/// ParseForStatement
1383/// for-statement: [C99 6.8.5.3]
1384/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1385/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001386/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1387/// [C++] statement
Richard Smith02e85f32011-04-14 22:09:26 +00001388/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001389/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1390/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001391///
1392/// [C++] for-init-statement:
1393/// [C++] expression-statement
1394/// [C++] simple-declaration
1395///
Richard Smith02e85f32011-04-14 22:09:26 +00001396/// [C++0x] for-range-declaration:
1397/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1398/// [C++0x] for-range-initializer:
1399/// [C++0x] expression
1400/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001401StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001402 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001403 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001404
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001405 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001406 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001407 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001408 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001409 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001410
Chad Rosier67055f52012-07-10 21:35:27 +00001411 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1412 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001413
Chris Lattner2dd1b722007-08-26 23:08:06 +00001414 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1415 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001416 //
1417 // C++ 6.4p3:
1418 // A name introduced by a declaration in a condition is in scope from its
1419 // point of declaration until the end of the substatements controlled by the
1420 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001421 // C++ 3.3.2p4:
1422 // Names declared in the for-init-statement, and in the condition of if,
1423 // while, for, and switch statements are local to the if, while, for, or
1424 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001425 // C++ 6.5.3p1:
1426 // Names declared in the for-init-statement are in the same declarative-region
1427 // as those declared in the condition.
1428 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001429 unsigned ScopeFlags = 0;
Chris Lattner934074c2009-04-22 00:54:41 +00001430 if (C99orCXXorObjC)
Serge Pavlov09f99242014-01-23 15:05:00 +00001431 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001432
1433 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001434
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001435 BalancedDelimiterTracker T(*this, tok::l_paren);
1436 T.consumeOpen();
1437
John McCalldadc5752010-08-24 06:29:42 +00001438 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001439
Richard Smith02e85f32011-04-14 22:09:26 +00001440 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001441 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001442 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001443 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001444 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001445 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001446 FullExprArg ThirdPart(Actions);
John McCall48871652010-08-21 09:40:31 +00001447 Decl *SecondVar = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001448
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001449 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001450 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001451 C99orCXXorObjC? Sema::PCC_ForInit
1452 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001453 cutOffParsing();
1454 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001455 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001456
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001457 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001458 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001459
Chris Lattner9075bd72006-08-10 04:59:57 +00001460 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001461 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001462 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001463 // no first part, eat the ';'.
1464 ConsumeToken();
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001465 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001466 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001467 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001468 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001469
Richard Smith02e85f32011-04-14 22:09:26 +00001470 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001471 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001472 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1473
Chris Lattner49836b42009-04-02 04:16:50 +00001474 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +00001475 StmtVector Stmts;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001476 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smith02e85f32011-04-14 22:09:26 +00001477 DeclEnd, attrs, false,
1478 MightBeForRangeStmt ?
1479 &ForRangeInit : 0);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001480 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001481
Richard Smith02e85f32011-04-14 22:09:26 +00001482 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001483 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001484 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001485
Richard Smith02e85f32011-04-14 22:09:26 +00001486 ForRange = true;
1487 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001488 ConsumeToken();
1489 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001490 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001491 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001492 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001493
Douglas Gregor68762e72010-08-23 21:17:50 +00001494 if (Tok.is(tok::code_completion)) {
1495 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001496 cutOffParsing();
1497 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001498 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001499 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001500 } else {
1501 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001502 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001503 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001504 ProhibitAttributes(attrs);
Chris Lattner89c50c62006-08-11 06:41:18 +00001505 Value = ParseExpression();
Chris Lattner71e23ce2006-11-04 20:18:38 +00001506
John McCall34376a62010-12-04 03:47:34 +00001507 ForEach = isTokIdentifier_in();
1508
Chris Lattnercd68f642007-06-27 01:06:29 +00001509 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001510 if (!Value.isInvalid()) {
1511 if (ForEach)
1512 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1513 else
Richard Smith945f8d32013-01-14 22:39:08 +00001514 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001515 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001516
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001517 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001518 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001519 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001520 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001521
Douglas Gregor68762e72010-08-23 21:17:50 +00001522 if (Tok.is(tok::code_completion)) {
1523 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001524 cutOffParsing();
1525 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001526 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001527 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001528 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001529 // User tried to write the reasonable, but ill-formed, for-range-statement
1530 // for (expr : expr) { ... }
1531 Diag(Tok, diag::err_for_range_expected_decl)
1532 << FirstPart.get()->getSourceRange();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001533 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smith4f848f12011-12-20 22:56:20 +00001534 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001535 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001536 if (!Value.isInvalid()) {
1537 Diag(Tok, diag::err_expected_semi_for);
1538 } else {
1539 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001540 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001541 if (Tok.is(tok::semi))
1542 ConsumeToken();
1543 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001544 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001545 }
Serge Pavlov09f99242014-01-23 15:05:00 +00001546
1547 // Parse the second part of the for specifier.
1548 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smith02e85f32011-04-14 22:09:26 +00001549 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001550 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001551 // Parse the second part of the for specifier.
1552 if (Tok.is(tok::semi)) { // for (...;;
1553 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001554 } else if (Tok.is(tok::r_paren)) {
1555 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001556 } else {
John McCalldadc5752010-08-24 06:29:42 +00001557 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001558 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001559 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1560 else {
1561 Second = ParseExpression();
1562 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001563 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001564 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001565 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001566 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001567 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001568 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001569
Douglas Gregor230a7e62011-02-17 03:38:46 +00001570 if (Tok.isNot(tok::semi)) {
1571 if (!SecondPartIsInvalid || SecondVar)
1572 Diag(Tok, diag::err_expected_semi_for);
1573 else
1574 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001575 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001576 }
1577
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001578 if (Tok.is(tok::semi)) {
1579 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001580 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001581
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001582 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001583 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001584 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001585 // FIXME: The C++11 standard doesn't actually say that this is a
1586 // discarded-value expression, but it clearly should be.
1587 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001588 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001589 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001590 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001591 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001592
Richard Smith02e85f32011-04-14 22:09:26 +00001593 // We need to perform most of the semantic analysis for a C++0x for-range
1594 // statememt before parsing the body, in order to be able to deduce the type
1595 // of an auto-typed loop variable.
1596 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001597 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001598
John McCall53848232011-07-27 01:07:15 +00001599 if (ForRange) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001600 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smith02e85f32011-04-14 22:09:26 +00001601 ForRangeInit.ColonLoc,
1602 ForRangeInit.RangeExpr.get(),
Richard Smitha05b3b52012-09-20 21:52:32 +00001603 T.getCloseLocation(),
1604 Sema::BFRK_Build);
Richard Smith02e85f32011-04-14 22:09:26 +00001605
John McCall53848232011-07-27 01:07:15 +00001606
1607 // Similarly, we need to do the semantic analysis for a for-range
1608 // statement immediately in order to close over temporaries correctly.
1609 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001610 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001611 FirstPart.take(),
Chad Rosier67055f52012-07-10 21:35:27 +00001612 Collection.take(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001613 T.getCloseLocation());
John McCall53848232011-07-27 01:07:15 +00001614 }
1615
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001616 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001617 // there is no compound stmt. C90 does not have this clause. We only do this
1618 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001619 //
1620 // C++ 6.5p2:
1621 // The substatement in an iteration-statement implicitly defines a local scope
1622 // which is entered and exited each time through the loop.
1623 //
1624 // See comments in ParseIfStatement for why we create a scope for
1625 // for-init-statement/condition and a new scope for substatement in C++.
1626 //
Mike Stump11289f42009-09-09 15:08:12 +00001627 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner934074c2009-04-22 00:54:41 +00001628 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001629
Chris Lattner9075bd72006-08-10 04:59:57 +00001630 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001631 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001632
Chris Lattner8fb26252007-08-22 05:28:50 +00001633 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001634 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001635
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001636 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001637 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001638
1639 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001640 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001641
Richard Smith02e85f32011-04-14 22:09:26 +00001642 if (ForEach)
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001643 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1644 Body.take());
Mike Stump11289f42009-09-09 15:08:12 +00001645
Richard Smith02e85f32011-04-14 22:09:26 +00001646 if (ForRange)
1647 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1648
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001649 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1650 SecondPart, SecondVar, ThirdPart,
1651 T.getCloseLocation(), Body.take());
Chris Lattner9075bd72006-08-10 04:59:57 +00001652}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001653
Chris Lattner503fadc2006-08-10 05:45:44 +00001654/// ParseGotoStatement
1655/// jump-statement:
1656/// 'goto' identifier ';'
1657/// [GNU] 'goto' '*' expression ';'
1658///
1659/// Note: this lets the caller parse the end ';'.
1660///
Richard Smithc202b282012-04-14 00:33:13 +00001661StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001662 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001663 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001664
John McCalldadc5752010-08-24 06:29:42 +00001665 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001666 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001667 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1668 Tok.getLocation());
1669 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001670 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001671 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001672 // GNU indirect goto extension.
1673 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001674 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001675 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001676 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001677 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001678 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001679 }
John McCallb268a282010-08-23 23:25:46 +00001680 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001681 } else {
Alp Tokerec543272013-12-24 09:48:30 +00001682 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001683 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001684 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001685
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001686 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001687}
1688
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001689/// ParseContinueStatement
1690/// jump-statement:
1691/// 'continue' ';'
1692///
1693/// Note: this lets the caller parse the end ';'.
1694///
Richard Smithc202b282012-04-14 00:33:13 +00001695StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001696 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001697 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001698}
1699
1700/// ParseBreakStatement
1701/// jump-statement:
1702/// 'break' ';'
1703///
1704/// Note: this lets the caller parse the end ';'.
1705///
Richard Smithc202b282012-04-14 00:33:13 +00001706StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001707 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001708 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001709}
1710
Chris Lattner503fadc2006-08-10 05:45:44 +00001711/// ParseReturnStatement
1712/// jump-statement:
1713/// 'return' expression[opt] ';'
Richard Smithc202b282012-04-14 00:33:13 +00001714StmtResult Parser::ParseReturnStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001715 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001716 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001717
John McCalldadc5752010-08-24 06:29:42 +00001718 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001719 if (Tok.isNot(tok::semi)) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001720 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001721 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001722 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001723 return StmtError();
1724 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001725
David Blaikiebbafb8a2012-03-11 07:00:24 +00001726 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001727 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001728 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001729 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001730 diag::warn_cxx98_compat_generalized_initializer_lists :
1731 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001732 << R.get()->getSourceRange();
1733 } else
1734 R = ParseExpression();
Serge Pavlovf79bd5c2013-12-04 03:51:59 +00001735 if (R.isInvalid()) {
1736 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001737 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001738 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001739 }
John McCallb268a282010-08-23 23:25:46 +00001740 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Chris Lattner503fadc2006-08-10 05:45:44 +00001741}
Chris Lattner0116c472006-08-15 06:03:28 +00001742
John McCallf413f5e2013-05-03 00:10:13 +00001743namespace {
1744 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1745 Parser &TheParser;
1746 SourceLocation AsmLoc;
1747 StringRef AsmString;
1748
1749 /// The tokens we streamed into AsmString and handed off to MC.
1750 ArrayRef<Token> AsmToks;
1751
1752 /// The offset of each token in AsmToks within AsmString.
1753 ArrayRef<unsigned> AsmTokOffsets;
1754
1755 public:
1756 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1757 StringRef AsmString,
1758 ArrayRef<Token> Toks,
1759 ArrayRef<unsigned> Offsets)
1760 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1761 AsmToks(Toks), AsmTokOffsets(Offsets) {
1762 assert(AsmToks.size() == AsmTokOffsets.size());
1763 }
1764
1765 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1766 InlineAsmIdentifierInfo &Info,
1767 bool IsUnevaluatedContext) {
1768 // Collect the desired tokens.
1769 SmallVector<Token, 16> LineToks;
1770 const Token *FirstOrigToken = 0;
1771 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1772
1773 unsigned NumConsumedToks;
1774 ExprResult Result =
1775 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1776 IsUnevaluatedContext);
1777
1778 // If we consumed the entire line, tell MC that.
1779 // Also do this if we consumed nothing as a way of reporting failure.
1780 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1781 // By not modifying LineBuf, we're implicitly consuming it all.
1782
1783 // Otherwise, consume up to the original tokens.
1784 } else {
1785 assert(FirstOrigToken && "not using original tokens?");
1786
1787 // Since we're using original tokens, apply that offset.
1788 assert(FirstOrigToken[NumConsumedToks].getLocation()
1789 == LineToks[NumConsumedToks].getLocation());
1790 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1791 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1792
1793 // The total length we've consumed is the relative offset
1794 // of the last token we consumed plus its length.
1795 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1796 + AsmToks[LastIndex].getLength()
1797 - AsmTokOffsets[FirstIndex]);
1798 LineBuf = LineBuf.substr(0, TotalOffset);
1799 }
1800
1801 // Initialize the "decl" with the lookup result.
1802 Info.OpDecl = static_cast<void*>(Result.take());
1803 return Info.OpDecl;
1804 }
1805
1806 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1807 unsigned &Offset) {
1808 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1809 Offset, AsmLoc);
1810 }
1811
1812 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1813 void *Context) {
1814 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1815 }
1816
1817 private:
1818 /// Collect the appropriate tokens for the given string.
1819 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1820 const Token *&FirstOrigToken) const {
1821 // For now, assert that the string we're working with is a substring
1822 // of what we gave to MC. This lets us use the original tokens.
1823 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1824 !std::less<const char*>()(AsmString.end(), Str.end()));
1825
1826 // Try to find a token whose offset matches the first token.
1827 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1828 const unsigned *FirstTokOffset
1829 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1830 FirstCharOffset);
1831
1832 // For now, assert that the start of the string exactly
1833 // corresponds to the start of a token.
1834 assert(*FirstTokOffset == FirstCharOffset);
1835
1836 // Use all the original tokens for this line. (We assume the
1837 // end of the line corresponds cleanly to a token break.)
1838 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1839 FirstOrigToken = &AsmToks[FirstTokIndex];
1840 unsigned LastCharOffset = Str.end() - AsmString.begin();
1841 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1842 if (AsmTokOffsets[i] >= LastCharOffset) break;
1843 TempToks.push_back(AsmToks[i]);
1844 }
1845 }
1846
1847 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1848 // Compute an offset into the inline asm buffer.
1849 // FIXME: This isn't right if .macro is involved (but hopefully, no
1850 // real-world code does that).
1851 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1852 const llvm::MemoryBuffer *LBuf =
1853 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1854 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1855
1856 // Figure out which token that offset points into.
1857 const unsigned *TokOffsetPtr =
1858 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1859 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1860 unsigned TokOffset = *TokOffsetPtr;
1861
1862 // If we come up with an answer which seems sane, use it; otherwise,
1863 // just point at the __asm keyword.
1864 // FIXME: Assert the answer is sane once we handle .macro correctly.
1865 SourceLocation Loc = AsmLoc;
1866 if (TokIndex < AsmToks.size()) {
1867 const Token &Tok = AsmToks[TokIndex];
1868 Loc = Tok.getLocation();
1869 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1870 }
1871 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1872 << D.getMessage();
1873 }
1874 };
1875}
1876
1877/// Parse an identifier in an MS-style inline assembly block.
1878///
1879/// \param CastInfo - a void* so that we don't have to teach Parser.h
1880/// about the actual type.
1881ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1882 unsigned &NumLineToksConsumed,
1883 void *CastInfo,
1884 bool IsUnevaluatedContext) {
1885 llvm::InlineAsmIdentifierInfo &Info =
1886 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1887
1888 // Push a fake token on the end so that we don't overrun the token
1889 // stream. We use ';' because it expression-parsing should never
1890 // overrun it.
1891 const tok::TokenKind EndOfStream = tok::semi;
1892 Token EndOfStreamTok;
1893 EndOfStreamTok.startToken();
1894 EndOfStreamTok.setKind(EndOfStream);
1895 LineToks.push_back(EndOfStreamTok);
1896
1897 // Also copy the current token over.
1898 LineToks.push_back(Tok);
1899
1900 PP.EnterTokenStream(LineToks.begin(),
1901 LineToks.size(),
1902 /*disable macros*/ true,
1903 /*owns tokens*/ false);
1904
1905 // Clear the current token and advance to the first token in LineToks.
1906 ConsumeAnyToken();
1907
1908 // Parse an optional scope-specifier if we're in C++.
1909 CXXScopeSpec SS;
1910 if (getLangOpts().CPlusPlus) {
1911 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1912 }
1913
1914 // Require an identifier here.
1915 SourceLocation TemplateKWLoc;
1916 UnqualifiedId Id;
1917 bool Invalid = ParseUnqualifiedId(SS,
1918 /*EnteringContext=*/false,
1919 /*AllowDestructorName=*/false,
1920 /*AllowConstructorName=*/false,
1921 /*ObjectType=*/ ParsedType(),
1922 TemplateKWLoc,
1923 Id);
1924
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001925 // Figure out how many tokens we are into LineToks.
1926 unsigned LineIndex = 0;
1927 if (Tok.is(EndOfStream)) {
1928 LineIndex = LineToks.size() - 2;
John McCallf413f5e2013-05-03 00:10:13 +00001929 } else {
John McCallf413f5e2013-05-03 00:10:13 +00001930 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1931 LineIndex++;
1932 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1933 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001934 }
John McCallf413f5e2013-05-03 00:10:13 +00001935
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001936 // If we've run into the poison token we inserted before, or there
1937 // was a parsing error, then claim the entire line.
1938 if (Invalid || Tok.is(EndOfStream)) {
1939 NumLineToksConsumed = LineToks.size() - 2;
1940 } else {
1941 // Otherwise, claim up to the start of the next token.
John McCallf413f5e2013-05-03 00:10:13 +00001942 NumLineToksConsumed = LineIndex;
1943 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001944
1945 // Finally, restore the old parsing state by consuming all the tokens we
1946 // staged before, implicitly killing off the token-lexer we pushed.
1947 for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
John McCallf413f5e2013-05-03 00:10:13 +00001948 ConsumeAnyToken();
1949 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001950 assert(Tok.is(EndOfStream));
1951 ConsumeToken();
John McCallf413f5e2013-05-03 00:10:13 +00001952
1953 // Leave LineToks in its original state.
1954 LineToks.pop_back();
1955 LineToks.pop_back();
1956
1957 // Perform the lookup.
1958 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1959 IsUnevaluatedContext);
1960}
1961
1962/// Turn a sequence of our tokens back into a string that we can hand
1963/// to the MC asm parser.
1964static bool buildMSAsmString(Preprocessor &PP,
1965 SourceLocation AsmLoc,
1966 ArrayRef<Token> AsmToks,
1967 SmallVectorImpl<unsigned> &TokOffsets,
1968 SmallString<512> &Asm) {
1969 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1970
1971 // Is this the start of a new assembly statement?
1972 bool isNewStatement = true;
1973
1974 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1975 const Token &Tok = AsmToks[i];
1976
1977 // Start each new statement with a newline and a tab.
1978 if (!isNewStatement &&
1979 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1980 Asm += "\n\t";
1981 isNewStatement = true;
1982 }
1983
1984 // Preserve the existence of leading whitespace except at the
1985 // start of a statement.
1986 if (!isNewStatement && Tok.hasLeadingSpace())
1987 Asm += ' ';
1988
1989 // Remember the offset of this token.
1990 TokOffsets.push_back(Asm.size());
1991
1992 // Don't actually write '__asm' into the assembly stream.
1993 if (Tok.is(tok::kw_asm)) {
1994 // Complain about __asm at the end of the stream.
1995 if (i + 1 == e) {
1996 PP.Diag(AsmLoc, diag::err_asm_empty);
1997 return true;
1998 }
1999
2000 continue;
2001 }
2002
2003 // Append the spelling of the token.
2004 SmallString<32> SpellingBuffer;
2005 bool SpellingInvalid = false;
2006 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
2007 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
2008
2009 // We are no longer at the start of a statement.
2010 isNewStatement = false;
2011 }
2012
2013 // Ensure that the buffer is null-terminated.
2014 Asm.push_back('\0');
2015 Asm.pop_back();
2016
2017 assert(TokOffsets.size() == AsmToks.size());
2018 return false;
2019}
2020
Eli Friedmana4b02c32011-09-30 01:13:51 +00002021/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
2022/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier32503022012-06-11 20:47:18 +00002023///
2024/// [MS] ms-asm-statement:
2025/// ms-asm-block
2026/// ms-asm-block ms-asm-statement
2027///
2028/// [MS] ms-asm-block:
2029/// '__asm' ms-asm-line '\n'
2030/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
2031///
2032/// [MS] ms-asm-instruction-block
2033/// ms-asm-line
2034/// ms-asm-line '\n' ms-asm-instruction-block
2035///
Eli Friedmana4b02c32011-09-30 01:13:51 +00002036StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
2037 SourceManager &SrcMgr = PP.getSourceManager();
2038 SourceLocation EndLoc = AsmLoc;
Chad Rosier32503022012-06-11 20:47:18 +00002039 SmallVector<Token, 4> AsmToks;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002040
2041 bool InBraces = false;
2042 unsigned short savedBraceCount = 0;
2043 bool InAsmComment = false;
2044 FileID FID;
2045 unsigned LineNo = 0;
2046 unsigned NumTokensRead = 0;
2047 SourceLocation LBraceLoc;
2048
2049 if (Tok.is(tok::l_brace)) {
2050 // Braced inline asm: consume the opening brace.
2051 InBraces = true;
2052 savedBraceCount = BraceCount;
2053 EndLoc = LBraceLoc = ConsumeBrace();
2054 ++NumTokensRead;
2055 } else {
2056 // Single-line inline asm; compute which line it is on.
2057 std::pair<FileID, unsigned> ExpAsmLoc =
2058 SrcMgr.getDecomposedExpansionLoc(EndLoc);
2059 FID = ExpAsmLoc.first;
2060 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2061 }
2062
2063 SourceLocation TokLoc = Tok.getLocation();
Eli Friedmana4b02c32011-09-30 01:13:51 +00002064 do {
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002065 // If we hit EOF, we're done, period.
Richard Smith34f30512013-11-23 04:06:09 +00002066 if (isEofOrEom())
Eli Friedmana4b02c32011-09-30 01:13:51 +00002067 break;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002068
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002069 if (!InAsmComment && Tok.is(tok::semi)) {
2070 // A semicolon in an asm is the start of a comment.
2071 InAsmComment = true;
2072 if (InBraces) {
2073 // Compute which line the comment is on.
2074 std::pair<FileID, unsigned> ExpSemiLoc =
2075 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2076 FID = ExpSemiLoc.first;
2077 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2078 }
2079 } else if (!InBraces || InAsmComment) {
2080 // If end-of-line is significant, check whether this token is on a
2081 // new line.
2082 std::pair<FileID, unsigned> ExpLoc =
2083 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2084 if (ExpLoc.first != FID ||
2085 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2086 // If this is a single-line __asm, we're done.
2087 if (!InBraces)
2088 break;
2089 // We're no longer in a comment.
2090 InAsmComment = false;
2091 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2092 // Single-line asm always ends when a closing brace is seen.
2093 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2094 // does MSVC do here?
2095 break;
2096 }
2097 }
2098 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2099 BraceCount == (savedBraceCount + 1)) {
2100 // Consume the closing brace, and finish
2101 EndLoc = ConsumeBrace();
2102 break;
2103 }
2104
2105 // Consume the next token; make sure we don't modify the brace count etc.
2106 // if we are in a comment.
2107 EndLoc = TokLoc;
2108 if (InAsmComment)
2109 PP.Lex(Tok);
2110 else {
2111 AsmToks.push_back(Tok);
2112 ConsumeAnyToken();
2113 }
2114 TokLoc = Tok.getLocation();
2115 ++NumTokensRead;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002116 } while (1);
Chad Rosier32503022012-06-11 20:47:18 +00002117
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002118 if (InBraces && BraceCount != savedBraceCount) {
2119 // __asm without closing brace (this can happen at EOF).
Alp Tokerec543272013-12-24 09:48:30 +00002120 Diag(Tok, diag::err_expected) << tok::r_brace;
2121 Diag(LBraceLoc, diag::note_matching) << tok::l_brace;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002122 return StmtError();
2123 } else if (NumTokensRead == 0) {
2124 // Empty __asm.
Alp Tokerec543272013-12-24 09:48:30 +00002125 Diag(Tok, diag::err_expected) << tok::l_brace;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002126 return StmtError();
2127 }
2128
John McCallf413f5e2013-05-03 00:10:13 +00002129 // Okay, prepare to use MC to parse the assembly.
2130 SmallVector<StringRef, 4> ConstraintRefs;
2131 SmallVector<Expr*, 4> Exprs;
2132 SmallVector<StringRef, 4> ClobberRefs;
2133
2134 // We need an actual supported target.
Benjamin Kramer9299637dc2014-03-04 19:31:42 +00002135 const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
John McCallf413f5e2013-05-03 00:10:13 +00002136 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
Alp Tokerb3644282013-10-30 15:07:10 +00002137 const std::string &TT = TheTriple.getTriple();
2138 const llvm::Target *TheTarget = 0;
John McCallf413f5e2013-05-03 00:10:13 +00002139 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2140 ArchTy != llvm::Triple::x86_64);
Alp Tokerb3644282013-10-30 15:07:10 +00002141 if (UnsupportedArch) {
John McCallf413f5e2013-05-03 00:10:13 +00002142 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
Alp Tokerb3644282013-10-30 15:07:10 +00002143 } else {
2144 std::string Error;
2145 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2146 if (!TheTarget)
2147 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
2148 }
Alp Toker45cf31f2013-10-30 14:29:28 +00002149
John McCallf413f5e2013-05-03 00:10:13 +00002150 // If we don't support assembly, or the assembly is empty, we don't
2151 // need to instantiate the AsmParser, etc.
Alp Tokerb3644282013-10-30 15:07:10 +00002152 if (!TheTarget || AsmToks.empty()) {
John McCallf413f5e2013-05-03 00:10:13 +00002153 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2154 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2155 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2156 }
2157
2158 // Expand the tokens into a string buffer.
2159 SmallString<512> AsmString;
2160 SmallVector<unsigned, 8> TokOffsets;
2161 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2162 return StmtError();
2163
John McCallf413f5e2013-05-03 00:10:13 +00002164 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
Rafael Espindola77056232013-05-13 01:24:18 +00002165 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002166 // Get the instruction descriptor.
2167 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
John McCallf413f5e2013-05-03 00:10:13 +00002168 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2169 OwningPtr<llvm::MCSubtargetInfo>
2170 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2171
2172 llvm::SourceMgr TempSrcMgr;
Bill Wendlingda1e3e72013-06-18 07:22:05 +00002173 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallf413f5e2013-05-03 00:10:13 +00002174 llvm::MemoryBuffer *Buffer =
2175 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2176
2177 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2178 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2179
2180 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2181 OwningPtr<llvm::MCAsmParser>
2182 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2183 OwningPtr<llvm::MCTargetAsmParser>
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002184 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser, *MII));
John McCallf413f5e2013-05-03 00:10:13 +00002185
John McCallf413f5e2013-05-03 00:10:13 +00002186 llvm::MCInstPrinter *IP =
2187 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2188
2189 // Change to the Intel dialect.
2190 Parser->setAssemblerDialect(1);
2191 Parser->setTargetParser(*TargetParser.get());
2192 Parser->setParsingInlineAsm(true);
2193 TargetParser->setParsingInlineAsm(true);
2194
2195 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2196 AsmToks, TokOffsets);
2197 TargetParser->setSemaCallback(&Callback);
2198 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2199 &Callback);
2200
2201 unsigned NumOutputs;
2202 unsigned NumInputs;
2203 std::string AsmStringIR;
2204 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2205 SmallVector<std::string, 4> Constraints;
2206 SmallVector<std::string, 4> Clobbers;
2207 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2208 NumOutputs, NumInputs, OpExprs, Constraints,
2209 Clobbers, MII, IP, Callback))
2210 return StmtError();
2211
2212 // Build the vector of clobber StringRefs.
2213 unsigned NumClobbers = Clobbers.size();
2214 ClobberRefs.resize(NumClobbers);
2215 for (unsigned i = 0; i != NumClobbers; ++i)
2216 ClobberRefs[i] = StringRef(Clobbers[i]);
2217
2218 // Recast the void pointers and build the vector of constraint StringRefs.
2219 unsigned NumExprs = NumOutputs + NumInputs;
2220 ConstraintRefs.resize(NumExprs);
2221 Exprs.resize(NumExprs);
2222 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2223 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2224 if (!OpExpr)
2225 return StmtError();
2226
2227 // Need address of variable.
2228 if (OpExprs[i].second)
2229 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2230 .take();
2231
2232 ConstraintRefs[i] = StringRef(Constraints[i]);
2233 Exprs[i] = OpExpr;
2234 }
2235
Chad Rosierc6c71332012-08-06 20:03:45 +00002236 // FIXME: We should be passing source locations for better diagnostics.
John McCallf413f5e2013-05-03 00:10:13 +00002237 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2238 NumOutputs, NumInputs,
2239 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002240}
2241
Chris Lattner0116c472006-08-15 06:03:28 +00002242/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff69e8f9e2008-02-11 23:15:56 +00002243/// asm-statement:
2244/// gnu-asm-statement
2245/// ms-asm-statement
2246///
2247/// [GNU] gnu-asm-statement:
Chris Lattner0116c472006-08-15 06:03:28 +00002248/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2249///
2250/// [GNU] asm-argument:
2251/// asm-string-literal
2252/// asm-string-literal ':' asm-operands[opt]
2253/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2254/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2255/// ':' asm-clobbers
2256///
2257/// [GNU] asm-clobbers:
2258/// asm-string-literal
2259/// asm-clobbers ',' asm-string-literal
2260///
John McCalldadc5752010-08-24 06:29:42 +00002261StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002262 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattner73c56c02007-10-29 04:04:16 +00002263 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002264
Chad Rosierc8e56e82012-12-05 21:08:21 +00002265 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosier67055f52012-07-10 21:35:27 +00002266 !isTypeQualifier()) {
Steve Naroffb2c80c72008-02-07 03:50:06 +00002267 msAsm = true;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002268 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002269 }
John McCall084e83d2011-03-24 11:26:52 +00002270 DeclSpec DS(AttrFactory);
Chris Lattner0116c472006-08-15 06:03:28 +00002271 SourceLocation Loc = Tok.getLocation();
Alexis Hunt96d5c762009-11-21 08:43:09 +00002272 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002273
Chris Lattner0116c472006-08-15 06:03:28 +00002274 // GNU asms accept, but warn, about type-qualifiers other than volatile.
Chris Lattnera925dc62006-11-28 04:33:46 +00002275 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner6d29c102008-11-18 07:48:38 +00002276 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Chris Lattnera925dc62006-11-28 04:33:46 +00002277 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner6d29c102008-11-18 07:48:38 +00002278 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith8e1ac332013-03-28 01:55:44 +00002279 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2280 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2281 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redlb62406f2008-12-11 19:48:14 +00002282
Chris Lattner0116c472006-08-15 06:03:28 +00002283 // Remember if this was a volatile asm.
Anders Carlsson660bdd12007-11-23 23:12:25 +00002284 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002285 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002286 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Alexey Bataevee6507d2013-11-18 08:17:37 +00002287 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002288 return StmtError();
Chris Lattner0116c472006-08-15 06:03:28 +00002289 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002290 BalancedDelimiterTracker T(*this, tok::l_paren);
2291 T.consumeOpen();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002292
John McCalldadc5752010-08-24 06:29:42 +00002293 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002294 if (AsmString.isInvalid()) {
Richard Smithd67aea22012-03-06 03:21:47 +00002295 // Consume up to and including the closing paren.
2296 T.skipToEnd();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002297 return StmtError();
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002298 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002299
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002300 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002301 ExprVector Constraints;
2302 ExprVector Exprs;
2303 ExprVector Clobbers;
Chris Lattner0116c472006-08-15 06:03:28 +00002304
Anders Carlsson19fe1162008-02-05 23:03:50 +00002305 if (Tok.is(tok::r_paren)) {
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002306 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002307 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002308 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2309 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2310 Constraints, Exprs, AsmString.take(),
2311 Clobbers, T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002312 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002313
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002314 // Parse Outputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002315 bool AteExtraColon = false;
2316 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2317 // In C++ mode, parse "::" like ": :".
2318 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002319 ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002320
Chris Lattner15768502009-12-20 23:08:04 +00002321 if (!AteExtraColon &&
2322 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002323 return StmtError();
2324 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002325
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002326 unsigned NumOutputs = Names.size();
2327
2328 // Parse Inputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002329 if (AteExtraColon ||
2330 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2331 // In C++ mode, parse "::" like ": :".
2332 if (AteExtraColon)
2333 AteExtraColon = false;
2334 else {
2335 AteExtraColon = Tok.is(tok::coloncolon);
2336 ConsumeToken();
2337 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002338
Chris Lattner15768502009-12-20 23:08:04 +00002339 if (!AteExtraColon &&
2340 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002341 return StmtError();
2342 }
2343
2344 assert(Names.size() == Constraints.size() &&
2345 Constraints.size() == Exprs.size() &&
2346 "Input operand size mismatch!");
2347
2348 unsigned NumInputs = Names.size() - NumOutputs;
2349
2350 // Parse the clobbers, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002351 if (AteExtraColon || Tok.is(tok::colon)) {
2352 if (!AteExtraColon)
2353 ConsumeToken();
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002354
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002355 // Parse the asm-string list for clobbers if present.
2356 if (Tok.isNot(tok::r_paren)) {
2357 while (1) {
John McCalldadc5752010-08-24 06:29:42 +00002358 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002359
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002360 if (Clobber.isInvalid())
2361 break;
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002362
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002363 Clobbers.push_back(Clobber.release());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002364
Alp Toker97650562014-01-10 11:19:30 +00002365 if (!TryConsumeToken(tok::comma))
2366 break;
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002367 }
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002368 }
2369 }
2370
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002371 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002372 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2373 NumInputs, Names.data(), Constraints, Exprs,
2374 AsmString.take(), Clobbers,
2375 T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002376}
2377
2378/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002379/// asm-statement, assuming the leading ':' token was eaten.
Chris Lattner0116c472006-08-15 06:03:28 +00002380///
2381/// [GNU] asm-operands:
2382/// asm-operand
2383/// asm-operands ',' asm-operand
2384///
2385/// [GNU] asm-operand:
2386/// asm-string-literal '(' expression ')'
2387/// '[' identifier ']' asm-string-literal '(' expression ')'
2388///
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00002389//
2390// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002391bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieu2bd04012011-09-09 02:00:50 +00002392 SmallVectorImpl<Expr *> &Constraints,
2393 SmallVectorImpl<Expr *> &Exprs) {
Chris Lattner0116c472006-08-15 06:03:28 +00002394 // 'asm-operands' isn't present?
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002395 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002396 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002397
2398 while (1) {
Chris Lattner0116c472006-08-15 06:03:28 +00002399 // Read the [id] if present.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002400 if (Tok.is(tok::l_square)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002401 BalancedDelimiterTracker T(*this, tok::l_square);
2402 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00002403
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002404 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00002405 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00002406 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002407 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002408 }
Mike Stump11289f42009-09-09 15:08:12 +00002409
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002410 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner645ff3f2007-10-29 04:06:22 +00002411 ConsumeToken();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002412
Anders Carlsson9a020f92010-01-30 22:25:16 +00002413 Names.push_back(II);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002414 T.consumeClose();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002415 } else
Anders Carlsson9a020f92010-01-30 22:25:16 +00002416 Names.push_back(0);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002417
John McCalldadc5752010-08-24 06:29:42 +00002418 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002419 if (Constraint.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002420 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002421 return true;
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002422 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002423 Constraints.push_back(Constraint.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002424
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002425 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002426 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Alexey Bataevee6507d2013-11-18 08:17:37 +00002427 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002428 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002429 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002430
Chris Lattner0116c472006-08-15 06:03:28 +00002431 // Read the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002432 BalancedDelimiterTracker T(*this, tok::l_paren);
2433 T.consumeOpen();
John McCalldadc5752010-08-24 06:29:42 +00002434 ExprResult Res(ParseExpression());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002435 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002436 if (Res.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002437 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002438 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002439 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002440 Exprs.push_back(Res.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002441 // Eat the comma and continue parsing if it exists.
Alp Toker97650562014-01-10 11:19:30 +00002442 if (!TryConsumeToken(tok::comma))
2443 return false;
Chris Lattner0116c472006-08-15 06:03:28 +00002444 }
2445}
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002446
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002447Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002448 assert(Tok.is(tok::l_brace));
2449 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002450
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00002451 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00002452 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002453 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002454 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002455 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002456
John McCallfaf5fb42010-08-26 23:41:50 +00002457 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2458 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002459
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002460 // Do not enter a scope for the brace, as the arguments are in the same scope
2461 // (the function body) as the body itself. Instead, just read the statement
2462 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002463 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002464
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002465 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002466 if (FnBody.isInvalid()) {
2467 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002468 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002469 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002470
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002471 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002472 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002473}
Sebastian Redlb219c902008-12-21 16:41:36 +00002474
Sebastian Redla7b98a72009-04-26 20:35:05 +00002475/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2476///
2477/// function-try-block:
2478/// 'try' ctor-initializer[opt] compound-statement handler-seq
2479///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002480Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002481 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2482 SourceLocation TryLoc = ConsumeToken();
2483
John McCallfaf5fb42010-08-26 23:41:50 +00002484 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2485 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002486
2487 // Constructor initializer list?
2488 if (Tok.is(tok::colon))
2489 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002490 else
2491 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002492
Richard Smith1ab34b32012-11-19 21:13:18 +00002493 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2494 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002495 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002496 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002497 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002498
Sebastian Redld98ecd62009-04-26 21:08:36 +00002499 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002500 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00002501 // If we failed to parse the try-catch, we just give the function an empty
2502 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002503 if (FnBody.isInvalid()) {
2504 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002505 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002506 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002507
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002508 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002509 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002510}
2511
Erik Verbruggen6e922512012-04-12 10:11:59 +00002512bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002513 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00002514 assert(SkipFunctionBodies &&
2515 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002516
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002517 if (!PP.isCodeCompletionEnabled()) {
2518 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002519 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002520 return true;
2521 }
2522
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002523 // We're in code-completion mode. Skip parsing for all function bodies unless
2524 // the body contains the code-completion point.
2525 TentativeParsingAction PA(*this);
2526 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002527 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002528 PA.Commit();
2529 return true;
2530 }
2531
2532 PA.Revert();
2533 return false;
2534}
2535
Sebastian Redlb219c902008-12-21 16:41:36 +00002536/// ParseCXXTryBlock - Parse a C++ try-block.
2537///
2538/// try-block:
2539/// 'try' compound-statement handler-seq
2540///
Richard Smithc202b282012-04-14 00:33:13 +00002541StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002542 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2543
2544 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002545 return ParseCXXTryBlockCommon(TryLoc);
2546}
2547
2548/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2549/// function-try-block.
2550///
2551/// try-block:
2552/// 'try' compound-statement handler-seq
2553///
2554/// function-try-block:
2555/// 'try' ctor-initializer[opt] compound-statement handler-seq
2556///
2557/// handler-seq:
2558/// handler handler-seq[opt]
2559///
John Wiegley1c0675e2011-04-28 01:08:34 +00002560/// [Borland] try-block:
2561/// 'try' compound-statement seh-except-block
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002562/// 'try' compound-statement seh-finally-block
John Wiegley1c0675e2011-04-28 01:08:34 +00002563///
David Blaikie1c9c9042012-11-10 01:04:23 +00002564StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002565 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002566 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002567 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002568
2569 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikie3403feb2012-11-13 18:51:45 +00002570 Scope::DeclScope | Scope::TryScope |
2571 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002572 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002573 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002574
John Wiegley1c0675e2011-04-28 01:08:34 +00002575 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002576
Richard Smithc202b282012-04-14 00:33:13 +00002577 if ((Tok.is(tok::identifier) &&
2578 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2579 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002580 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2581 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002582 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002583 SourceLocation Loc = ConsumeToken();
2584 Handler = ParseSEHExceptBlock(Loc);
2585 }
2586 else {
2587 SourceLocation Loc = ConsumeToken();
2588 Handler = ParseSEHFinallyBlock(Loc);
2589 }
2590 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002591 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002592
John Wiegley1c0675e2011-04-28 01:08:34 +00002593 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2594 TryLoc,
2595 TryBlock.take(),
2596 Handler.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002597 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002598 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002599 StmtVector Handlers;
Richard Smithc2c8bb82013-10-15 01:34:54 +00002600
2601 // C++11 attributes can't appear here, despite this context seeming
2602 // statement-like.
2603 DiagnoseAndSkipCXX11Attributes();
Sebastian Redlb219c902008-12-21 16:41:36 +00002604
John Wiegley1c0675e2011-04-28 01:08:34 +00002605 if (Tok.isNot(tok::kw_catch))
2606 return StmtError(Diag(Tok, diag::err_expected_catch));
2607 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002608 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002609 if (!Handler.isInvalid())
2610 Handlers.push_back(Handler.release());
2611 }
2612 // Don't bother creating the full statement if we don't have any usable
2613 // handlers.
2614 if (Handlers.empty())
2615 return StmtError();
2616
Robert Wilhelmcafda822013-08-22 09:20:03 +00002617 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002618 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002619}
2620
2621/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2622///
Richard Smith1dba27c2013-01-29 09:02:09 +00002623/// handler:
2624/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002625///
Richard Smith1dba27c2013-01-29 09:02:09 +00002626/// exception-declaration:
2627/// attribute-specifier-seq[opt] type-specifier-seq declarator
2628/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2629/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002630///
David Blaikie1c9c9042012-11-10 01:04:23 +00002631StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002632 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2633
2634 SourceLocation CatchLoc = ConsumeToken();
2635
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002636 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002637 if (T.expectAndConsume())
Sebastian Redlb219c902008-12-21 16:41:36 +00002638 return StmtError();
2639
2640 // C++ 3.3.2p3:
2641 // The name in a catch exception-declaration is local to the handler and
2642 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002643 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002644 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002645
2646 // exception-declaration is equivalent to '...' or a parameter-declaration
2647 // without default arguments.
John McCall48871652010-08-21 09:40:31 +00002648 Decl *ExceptionDecl = 0;
Sebastian Redlb219c902008-12-21 16:41:36 +00002649 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002650 ParsedAttributesWithRange Attributes(AttrFactory);
2651 MaybeParseCXX11Attributes(Attributes);
2652
John McCall084e83d2011-03-24 11:26:52 +00002653 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002654 DS.takeAttributesFrom(Attributes);
2655
Sebastian Redl54c04d42008-12-22 19:15:10 +00002656 if (ParseCXXTypeSpecifierSeq(DS))
2657 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002658
Sebastian Redlb219c902008-12-21 16:41:36 +00002659 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2660 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002661 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002662 } else
2663 ConsumeToken();
2664
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002665 T.consumeClose();
2666 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002667 return StmtError();
2668
2669 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002670 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redlb219c902008-12-21 16:41:36 +00002671
Alexis Hunt96d5c762009-11-21 08:43:09 +00002672 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002673 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002674 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002675 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002676
John McCallb268a282010-08-23 23:25:46 +00002677 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002678}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002679
2680void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002681 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002682 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002683 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002684
Douglas Gregor43edb322011-10-24 22:31:10 +00002685 // Handle dependent statements by parsing the braces as a compound statement.
2686 // This is not the same behavior as Visual C++, which don't treat this as a
2687 // compound statement, but for Clang's type checking we can't have anything
2688 // inside these braces escaping to the surrounding code.
2689 if (Result.Behavior == IEB_Dependent) {
2690 if (!Tok.is(tok::l_brace)) {
Alp Tokerec543272013-12-24 09:48:30 +00002691 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smithc202b282012-04-14 00:33:13 +00002692 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002693 }
Richard Smithc202b282012-04-14 00:33:13 +00002694
2695 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002696 if (Compound.isInvalid())
2697 return;
Richard Smithc202b282012-04-14 00:33:13 +00002698
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002699 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2700 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002701 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002702 Result.Name,
2703 Compound.get());
2704 if (DepResult.isUsable())
2705 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002706 return;
2707 }
Richard Smithc202b282012-04-14 00:33:13 +00002708
Douglas Gregor43edb322011-10-24 22:31:10 +00002709 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2710 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00002711 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002712 return;
2713 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002714
Douglas Gregor43edb322011-10-24 22:31:10 +00002715 switch (Result.Behavior) {
2716 case IEB_Parse:
2717 // Parse the statements below.
2718 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002719
Douglas Gregor43edb322011-10-24 22:31:10 +00002720 case IEB_Dependent:
2721 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002722
Douglas Gregor43edb322011-10-24 22:31:10 +00002723 case IEB_Skip:
2724 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002725 return;
2726 }
2727
2728 // Condition is true, parse the statements.
2729 while (Tok.isNot(tok::r_brace)) {
2730 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2731 if (R.isUsable())
2732 Stmts.push_back(R.release());
2733 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002734 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002735}