blob: 166f403efba65893dfd6087065330e8e0bcd0d31 [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"
Nico Weber01708cd2014-04-23 19:19:20 +000029#include "llvm/MC/MCInstPrinter.h"
John McCallf413f5e2013-05-03 00:10:13 +000030#include "llvm/MC/MCObjectFileInfo.h"
31#include "llvm/MC/MCParser/MCAsmParser.h"
32#include "llvm/MC/MCRegisterInfo.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSubtargetInfo.h"
35#include "llvm/MC/MCTargetAsmParser.h"
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +000036#include "llvm/MC/MCTargetOptions.h"
John McCallf413f5e2013-05-03 00:10:13 +000037#include "llvm/Support/SourceMgr.h"
38#include "llvm/Support/TargetRegistry.h"
39#include "llvm/Support/TargetSelect.h"
Chris Lattner0ccd51e2006-08-09 05:47:47 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43// C99 6.8: Statements and Blocks.
44//===----------------------------------------------------------------------===//
45
Richard Smith426a47b2013-10-28 22:04:30 +000046/// \brief Parse a standalone statement (for instance, as the body of an 'if',
47/// 'while', or 'for').
48StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) {
49 StmtResult Res;
50
51 // We may get back a null statement if we found a #pragma. Keep going until
52 // we get an actual statement.
53 do {
54 StmtVector Stmts;
55 Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
56 } while (!Res.isInvalid() && !Res.get());
57
58 return Res;
59}
60
Chris Lattner0ccd51e2006-08-09 05:47:47 +000061/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
62/// StatementOrDeclaration:
63/// statement
64/// declaration
65///
66/// statement:
67/// labeled-statement
68/// compound-statement
69/// expression-statement
70/// selection-statement
71/// iteration-statement
72/// jump-statement
Argyrios Kyrtzidisdee82912008-09-07 18:58:01 +000073/// [C++] declaration-statement
Sebastian Redlb219c902008-12-21 16:41:36 +000074/// [C++] try-block
John Wiegley1c0675e2011-04-28 01:08:34 +000075/// [MS] seh-try-block
Fariborz Jahanian90814572007-10-04 20:19:06 +000076/// [OBC] objc-throw-statement
77/// [OBC] objc-try-catch-statement
Fariborz Jahanianf89ca382008-01-29 18:21:32 +000078/// [OBC] objc-synchronized-statement
Chris Lattner0116c472006-08-15 06:03:28 +000079/// [GNU] asm-statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +000080/// [OMP] openmp-construct [TODO]
81///
82/// labeled-statement:
83/// identifier ':' statement
84/// 'case' constant-expression ':' statement
85/// 'default' ':' statement
86///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000087/// selection-statement:
88/// if-statement
89/// switch-statement
90///
91/// iteration-statement:
92/// while-statement
93/// do-statement
94/// for-statement
95///
Chris Lattner9075bd72006-08-10 04:59:57 +000096/// expression-statement:
97/// expression[opt] ';'
98///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000099/// jump-statement:
100/// 'goto' identifier ';'
101/// 'continue' ';'
102/// 'break' ';'
103/// 'return' expression[opt] ';'
Chris Lattner503fadc2006-08-10 05:45:44 +0000104/// [GNU] 'goto' '*' expression ';'
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000105///
Fariborz Jahanian90814572007-10-04 20:19:06 +0000106/// [OBC] objc-throw-statement:
107/// [OBC] '@' 'throw' expression ';'
Mike Stump11289f42009-09-09 15:08:12 +0000108/// [OBC] '@' 'throw' ';'
109///
John McCalldadc5752010-08-24 06:29:42 +0000110StmtResult
Nico Weber3cef1082011-12-22 23:26:17 +0000111Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
112 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000113
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +0000114 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000115
Richard Smithc202b282012-04-14 00:33:13 +0000116 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000117 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
Richard Smithc202b282012-04-14 00:33:13 +0000118
119 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
120 OnlyStatement, TrailingElseLoc, Attrs);
121
122 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
123 "attributes on empty statement");
124
125 if (Attrs.empty() || Res.isInvalid())
126 return Res;
127
128 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
129}
130
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000131namespace {
132class StatementFilterCCC : public CorrectionCandidateCallback {
133public:
134 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
135 WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) ||
136 nextTok.is(tok::identifier) || nextTok.is(tok::star) ||
137 nextTok.is(tok::amp) || nextTok.is(tok::l_square);
138 WantExpressionKeywords = nextTok.is(tok::l_paren) ||
139 nextTok.is(tok::identifier) ||
140 nextTok.is(tok::arrow) || nextTok.is(tok::period);
141 WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) ||
142 nextTok.is(tok::identifier) ||
143 nextTok.is(tok::l_brace);
144 WantCXXNamedCasts = false;
145 }
146
Craig Topper2b07f022014-03-12 05:09:18 +0000147 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000148 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
Kaelyn Uhrain07e62722013-10-01 22:00:28 +0000149 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain46b6cdc2013-09-27 19:40:16 +0000150 if (NextToken.is(tok::equal))
151 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain30943ce2013-09-27 23:54:23 +0000152 if (NextToken.is(tok::period) &&
153 candidate.getCorrectionDeclAs<NamespaceDecl>())
154 return false;
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000155 return CorrectionCandidateCallback::ValidateCandidate(candidate);
156 }
157
158private:
159 Token NextToken;
160};
161}
162
Richard Smithc202b282012-04-14 00:33:13 +0000163StmtResult
164Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
165 bool OnlyStatement, SourceLocation *TrailingElseLoc,
166 ParsedAttributesWithRange &Attrs) {
167 const char *SemiError = 0;
168 StmtResult Res;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000169
Chris Lattner503fadc2006-08-10 05:45:44 +0000170 // Cases in this switch statement should fall through if the parser expects
171 // the token to end in a semicolon (in which case SemiError should be set),
172 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000173Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000174 tok::TokenKind Kind = Tok.getKind();
175 SourceLocation AtLoc;
176 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000177 case tok::at: // May be a @try or @throw statement
178 {
Richard Smithc202b282012-04-14 00:33:13 +0000179 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000180 AtLoc = ConsumeToken(); // consume @
Sebastian Redlbab9a4b2008-12-11 20:12:42 +0000181 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000182 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000183
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000184 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000185 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000186 cutOffParsing();
187 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000188
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000189 case tok::identifier: {
190 Token Next = NextToken();
191 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000192 // identifier ':' statement
Richard Smithc202b282012-04-14 00:33:13 +0000193 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000194 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000195
Richard Smith4f605af2012-08-18 00:55:03 +0000196 // Look up the identifier, and typo-correct it to a keyword if it's not
197 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000198 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000199 // Try to limit which sets of keywords should be included in typo
200 // correction based on what the next token is.
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000201 StatementFilterCCC Validator(Next);
202 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
Richard Smith4f605af2012-08-18 00:55:03 +0000203 == ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000204 // Handle errors here by skipping up to the next semicolon or '}', and
205 // eat the semicolon if that's what stopped us.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000206 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000207 if (Tok.is(tok::semi))
208 ConsumeToken();
209 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000210 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000211
Richard Smith4f605af2012-08-18 00:55:03 +0000212 // If the identifier was typo-corrected, try again.
213 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000214 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000215 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000216
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000217 // Fall through
218 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000219
Chris Lattner803802d2009-03-24 17:04:48 +0000220 default: {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000221 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000222 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek5eec2b02010-11-10 05:59:39 +0000223 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000224 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000225 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000226 }
227
228 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000229 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000230 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000231 }
Mike Stump11289f42009-09-09 15:08:12 +0000232
Richard Smithc202b282012-04-14 00:33:13 +0000233 return ParseExprStatement();
Chris Lattner803802d2009-03-24 17:04:48 +0000234 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000235
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000236 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000237 return ParseCaseStatement();
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000238 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000239 return ParseDefaultStatement();
Sebastian Redl042ad952008-12-11 19:30:53 +0000240
Chris Lattner9075bd72006-08-10 04:59:57 +0000241 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000242 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000243 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000244 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
245 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000246 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000247
Chris Lattner9075bd72006-08-10 04:59:57 +0000248 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000249 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000250 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000251 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000252
Chris Lattner9075bd72006-08-10 04:59:57 +0000253 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000254 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000255 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000256 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000257 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000258 break;
259 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000260 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000261
262 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000263 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000264 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000265 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000266 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000267 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000268 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000269 break;
270 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000271 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000272 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000273 break;
274 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000275 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000276 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000277 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000278
Sebastian Redlb219c902008-12-21 16:41:36 +0000279 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000280 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000281 bool msAsm = false;
282 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000283 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000284 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000285 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000286 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000287 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000288
Sebastian Redlb219c902008-12-21 16:41:36 +0000289 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000290 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000291
292 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000293 ProhibitAttributes(Attrs); // TODO: is it correct?
294 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000295
296 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000297 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000298 HandlePragmaVisibility();
299 return StmtEmpty();
300
301 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000302 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000303 HandlePragmaPack();
304 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000305
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000306 case tok::annot_pragma_msstruct:
307 ProhibitAttributes(Attrs);
308 HandlePragmaMSStruct();
309 return StmtEmpty();
310
Eli Friedmanae8ee252012-10-08 23:52:38 +0000311 case tok::annot_pragma_align:
312 ProhibitAttributes(Attrs);
313 HandlePragmaAlign();
314 return StmtEmpty();
315
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000316 case tok::annot_pragma_weak:
317 ProhibitAttributes(Attrs);
318 HandlePragmaWeak();
319 return StmtEmpty();
320
321 case tok::annot_pragma_weakalias:
322 ProhibitAttributes(Attrs);
323 HandlePragmaWeakAlias();
324 return StmtEmpty();
325
326 case tok::annot_pragma_redefine_extname:
327 ProhibitAttributes(Attrs);
328 HandlePragmaRedefineExtname();
329 return StmtEmpty();
330
Eli Friedman68be1642012-10-04 02:36:51 +0000331 case tok::annot_pragma_fp_contract:
Richard Smithca9b0b62013-11-15 21:10:54 +0000332 ProhibitAttributes(Attrs);
Lang Hamesa930e712012-10-21 01:10:01 +0000333 Diag(Tok, diag::err_pragma_fp_contract_scope);
334 ConsumeToken();
335 return StmtError();
336
Eli Friedman68be1642012-10-04 02:36:51 +0000337 case tok::annot_pragma_opencl_extension:
338 ProhibitAttributes(Attrs);
339 HandlePragmaOpenCLExtension();
340 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000341
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000342 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000343 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000344 return HandlePragmaCaptured();
345
Alexey Bataeva769e072013-03-22 06:34:35 +0000346 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000347 ProhibitAttributes(Attrs);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000348 return ParseOpenMPDeclarativeOrExecutableDirective();
349
David Majnemer4bb09802014-02-10 19:50:15 +0000350 case tok::annot_pragma_ms_pointers_to_members:
351 ProhibitAttributes(Attrs);
352 HandlePragmaMSPointersToMembers();
353 return StmtEmpty();
354
Warren Huntc3b18962014-04-08 22:30:47 +0000355 case tok::annot_pragma_ms_pragma:
356 ProhibitAttributes(Attrs);
357 HandlePragmaMSPragma();
358 return StmtEmpty();
Sebastian Redlb219c902008-12-21 16:41:36 +0000359 }
360
Chris Lattner503fadc2006-08-10 05:45:44 +0000361 // If we reached this code, the statement must end in a semicolon.
Alp Toker97650562014-01-10 11:19:30 +0000362 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000363 // If the result was valid, then we do want to diagnose this. Use
364 // ExpectAndConsume to emit the diagnostic, even though we know it won't
365 // succeed.
366 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000367 // Skip until we see a } or ;, but don't eat it.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000368 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner503fadc2006-08-10 05:45:44 +0000369 }
Mike Stump11289f42009-09-09 15:08:12 +0000370
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000371 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000372}
373
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000374/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000375StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000376 // If a case keyword is missing, this is where it should be inserted.
377 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000378
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000379 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000380 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000381 if (Expr.isInvalid()) {
382 // If the expression is invalid, skip ahead to the next semicolon or '}'.
383 // Not doing this opens us up to the possibility of infinite loops if
384 // ParseExpression does not consume any tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000385 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000386 if (Tok.is(tok::semi))
387 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000388 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000389 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000390
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000391 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
392 Actions.CheckCaseExpression(Expr.get())) {
393 // If a constant expression is followed by a colon inside a switch block,
394 // suggest a missing case keyword.
395 Diag(OldToken, diag::err_expected_case_before_expression)
396 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000397
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000398 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000399 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000400 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000401
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000402 // Otherwise, eat the semicolon.
403 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000404 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000405}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000406
Richard Smithc202b282012-04-14 00:33:13 +0000407StmtResult Parser::ParseSEHTryBlock() {
John Wiegley1c0675e2011-04-28 01:08:34 +0000408 assert(Tok.is(tok::kw___try) && "Expected '__try'");
409 SourceLocation Loc = ConsumeToken();
410 return ParseSEHTryBlockCommon(Loc);
411}
412
413/// ParseSEHTryBlockCommon
414///
415/// seh-try-block:
416/// '__try' compound-statement seh-handler
417///
418/// seh-handler:
419/// seh-except-block
420/// seh-finally-block
421///
422StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
423 if(Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000424 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley1c0675e2011-04-28 01:08:34 +0000425
Joao Matos566359c2012-09-04 17:49:35 +0000426 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000427 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000428 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000429
430 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000431 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000432 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000433 SourceLocation Loc = ConsumeToken();
434 Handler = ParseSEHExceptBlock(Loc);
435 } else if (Tok.is(tok::kw___finally)) {
436 SourceLocation Loc = ConsumeToken();
437 Handler = ParseSEHFinallyBlock(Loc);
438 } else {
439 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
440 }
441
442 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000443 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000444
445 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
446 TryLoc,
447 TryBlock.take(),
448 Handler.take());
449}
450
451/// ParseSEHExceptBlock - Handle __except
452///
453/// seh-except-block:
454/// '__except' '(' seh-filter-expression ')' compound-statement
455///
456StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
457 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
458 raii2(Ident___exception_code, false),
459 raii3(Ident_GetExceptionCode, false);
460
Alp Toker383d2c42014-01-01 03:08:43 +0000461 if (ExpectAndConsume(tok::l_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000462 return StmtError();
463
464 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
465
David Blaikiebbafb8a2012-03-11 07:00:24 +0000466 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000467 Ident__exception_info->setIsPoisoned(false);
468 Ident___exception_info->setIsPoisoned(false);
469 Ident_GetExceptionInfo->setIsPoisoned(false);
470 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000471 ExprResult FilterExpr(ParseExpression());
Francois Pichetbfaf4772011-04-28 03:14:31 +0000472
David Blaikiebbafb8a2012-03-11 07:00:24 +0000473 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000474 Ident__exception_info->setIsPoisoned(true);
475 Ident___exception_info->setIsPoisoned(true);
476 Ident_GetExceptionInfo->setIsPoisoned(true);
477 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000478
479 if(FilterExpr.isInvalid())
480 return StmtError();
481
Alp Toker383d2c42014-01-01 03:08:43 +0000482 if (ExpectAndConsume(tok::r_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000483 return StmtError();
484
Richard Smithc202b282012-04-14 00:33:13 +0000485 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000486
487 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000488 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000489
490 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
491}
492
493/// ParseSEHFinallyBlock - Handle __finally
494///
495/// seh-finally-block:
496/// '__finally' compound-statement
497///
498StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
499 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
500 raii2(Ident___abnormal_termination, false),
501 raii3(Ident_AbnormalTermination, false);
502
Richard Smithc202b282012-04-14 00:33:13 +0000503 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000504 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000505 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000506
507 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000508}
509
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000510/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000511///
512/// labeled-statement:
513/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000514/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000515///
Richard Smithc202b282012-04-14 00:33:13 +0000516StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000517 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
518 "Not an identifier!");
519
520 Token IdentTok = Tok; // Save the whole token.
521 ConsumeToken(); // eat the identifier.
522
523 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000524
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000525 // identifier ':' statement
526 SourceLocation ColonLoc = ConsumeToken();
527
Richard Smitha3e01cf2013-11-15 22:45:29 +0000528 // Read label attributes, if present.
529 StmtResult SubStmt;
530 if (Tok.is(tok::kw___attribute)) {
531 ParsedAttributesWithRange TempAttrs(AttrFactory);
532 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000533
Richard Smitha3e01cf2013-11-15 22:45:29 +0000534 // In C++, GNU attributes only apply to the label if they are followed by a
535 // semicolon, to disambiguate label attributes from attributes on a labeled
536 // declaration.
537 //
538 // This doesn't quite match what GCC does; if the attribute list is empty
539 // and followed by a semicolon, GCC will reject (it appears to parse the
540 // attributes as part of a statement in that case). That looks like a bug.
541 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
542 attrs.takeAllFrom(TempAttrs);
543 else if (isDeclarationStatement()) {
544 StmtVector Stmts;
545 // FIXME: We should do this whether or not we have a declaration
546 // statement, but that doesn't work correctly (because ProhibitAttributes
547 // can't handle GNU attributes), so only call it in the one case where
548 // GNU attributes are allowed.
549 SubStmt = ParseStatementOrDeclarationAfterAttributes(
550 Stmts, /*OnlyStmts*/ true, 0, TempAttrs);
551 if (!TempAttrs.empty() && !SubStmt.isInvalid())
552 SubStmt = Actions.ProcessStmtAttributes(
553 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
554 } else {
Alp Toker383d2c42014-01-01 03:08:43 +0000555 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smitha3e01cf2013-11-15 22:45:29 +0000556 }
557 }
558
559 // If we've not parsed a statement yet, parse one now.
560 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
561 SubStmt = ParseStatement();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000562
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000563 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000564 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000565 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000566
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000567 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
568 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000569 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000570 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000571 attrs.clear();
572 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000573
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000574 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
575 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000576}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000577
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000578/// ParseCaseStatement
579/// labeled-statement:
580/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000581/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000582///
Richard Smithc202b282012-04-14 00:33:13 +0000583StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000584 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000585
Chris Lattner34a22092009-03-04 04:23:07 +0000586 // It is very very common for code to contain many case statements recursively
587 // nested, as in (but usually without indentation):
588 // case 1:
589 // case 2:
590 // case 3:
591 // case 4:
592 // case 5: etc.
593 //
594 // Parsing this naively works, but is both inefficient and can cause us to run
595 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000596 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000597 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smitha3e01cf2013-11-15 22:45:29 +0000598 // weirdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000599
Chris Lattner34a22092009-03-04 04:23:07 +0000600 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
601 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000602 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000603
Chris Lattner34a22092009-03-04 04:23:07 +0000604 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
605 // gets updated each time a new case is parsed, and whose body is unset so
606 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieu3481fcd2011-09-09 02:16:15 +0000607 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000608
Chris Lattner34a22092009-03-04 04:23:07 +0000609 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000610 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000611 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000612 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
613 ConsumeToken(); // eat the 'case'.
Mike Stump11289f42009-09-09 15:08:12 +0000614
Douglas Gregord328d572009-09-21 18:10:23 +0000615 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000616 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000617 cutOffParsing();
618 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000619 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000620
Chris Lattner125c0ee2009-12-10 00:38:54 +0000621 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
622 /// Disable this form of error recovery while we're parsing the case
623 /// expression.
624 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000625
Richard Trieu2c850c02011-04-21 21:44:26 +0000626 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
627 MissingCase = false;
Chris Lattner34a22092009-03-04 04:23:07 +0000628 if (LHS.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000629 SkipUntil(tok::colon, StopAtSemi);
Sebastian Redl042ad952008-12-11 19:30:53 +0000630 return StmtError();
Chris Lattner476c3ad2006-08-13 22:09:58 +0000631 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000632
Chris Lattner34a22092009-03-04 04:23:07 +0000633 // GNU case range extension.
634 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000635 ExprResult RHS;
Alp Tokerec543272013-12-24 09:48:30 +0000636 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
637 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Chris Lattner34a22092009-03-04 04:23:07 +0000638 RHS = ParseConstantExpression();
639 if (RHS.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000640 SkipUntil(tok::colon, StopAtSemi);
Chris Lattner34a22092009-03-04 04:23:07 +0000641 return StmtError();
642 }
643 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000644
Chris Lattner125c0ee2009-12-10 00:38:54 +0000645 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000646
Alp Tokerec543272013-12-24 09:48:30 +0000647 if (TryConsumeToken(tok::colon, ColonLoc)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000648 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
649 TryConsumeToken(tok::coloncolon, ColonLoc)) {
650 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Alp Tokerec543272013-12-24 09:48:30 +0000651 Diag(ColonLoc, diag::err_expected_after)
652 << "'case'" << tok::colon
653 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000654 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000655 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000656 Diag(ExpectedLoc, diag::err_expected_after)
657 << "'case'" << tok::colon
658 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000659 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000660 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000661
John McCalldadc5752010-08-24 06:29:42 +0000662 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000663 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
664 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000665
Chris Lattner34a22092009-03-04 04:23:07 +0000666 // If we had a sema error parsing this case, then just ignore it and
667 // continue parsing the sub-stmt.
668 if (Case.isInvalid()) {
669 if (TopLevelCase.isInvalid()) // No parsed case stmts.
670 return ParseStatement();
671 // Otherwise, just don't add it as a nested case.
672 } else {
673 // If this is the first case statement we parsed, it becomes TopLevelCase.
674 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000675 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000676 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000677 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000678 else
John McCallb268a282010-08-23 23:25:46 +0000679 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000680 DeepestParsedCaseStmt = NextDeepest;
681 }
Mike Stump11289f42009-09-09 15:08:12 +0000682
Chris Lattner34a22092009-03-04 04:23:07 +0000683 // Handle all case statements.
684 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000685
Chris Lattner34a22092009-03-04 04:23:07 +0000686 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump11289f42009-09-09 15:08:12 +0000687
Chris Lattner34a22092009-03-04 04:23:07 +0000688 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000689 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000690
Chris Lattner34a22092009-03-04 04:23:07 +0000691 if (Tok.isNot(tok::r_brace)) {
692 SubStmt = ParseStatement();
693 } else {
694 // Nicely diagnose the common error "switch (X) { case 4: }", which is
695 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000696 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000697 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
698 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner34a22092009-03-04 04:23:07 +0000699 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000700 }
Mike Stump11289f42009-09-09 15:08:12 +0000701
Chris Lattner34a22092009-03-04 04:23:07 +0000702 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000703 if (SubStmt.isInvalid())
Chris Lattner34a22092009-03-04 04:23:07 +0000704 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000705
Chris Lattner34a22092009-03-04 04:23:07 +0000706 // Install the body into the most deeply-nested case.
John McCallb268a282010-08-23 23:25:46 +0000707 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl042ad952008-12-11 19:30:53 +0000708
Chris Lattner34a22092009-03-04 04:23:07 +0000709 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000710 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000711}
712
713/// ParseDefaultStatement
714/// labeled-statement:
715/// 'default' ':' statement
716/// Note that this does not parse the 'statement' at the end.
717///
Richard Smithc202b282012-04-14 00:33:13 +0000718StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000719 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000720 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000721
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000722 SourceLocation ColonLoc;
Alp Tokerec543272013-12-24 09:48:30 +0000723 if (TryConsumeToken(tok::colon, ColonLoc)) {
Alp Tokerec543272013-12-24 09:48:30 +0000724 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
Alp Toker97650562014-01-10 11:19:30 +0000725 // Treat "default;" as a typo for "default:".
Alp Tokerec543272013-12-24 09:48:30 +0000726 Diag(ColonLoc, diag::err_expected_after)
727 << "'default'" << tok::colon
728 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000729 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000730 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000731 Diag(ExpectedLoc, diag::err_expected_after)
732 << "'default'" << tok::colon
733 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000734 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000735 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000736
Richard Smith1002d102012-02-17 01:35:32 +0000737 StmtResult SubStmt;
738
739 if (Tok.isNot(tok::r_brace)) {
740 SubStmt = ParseStatement();
741 } else {
742 // Diagnose the common error "switch (X) {... default: }", which is
743 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000744 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000745 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
746 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
747 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000748 }
749
Richard Smith1002d102012-02-17 01:35:32 +0000750 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000751 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000752 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000753
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000754 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000755 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000756}
757
Richard Smithc202b282012-04-14 00:33:13 +0000758StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
759 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000760}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000761
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000762/// ParseCompoundStatement - Parse a "{}" block.
763///
764/// compound-statement: [C99 6.8.2]
765/// { block-item-list[opt] }
766/// [GNU] { label-declarations block-item-list } [TODO]
767///
768/// block-item-list:
769/// block-item
770/// block-item-list block-item
771///
772/// block-item:
773/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000774/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000775/// statement
776/// [OMP] openmp-directive [TODO]
777///
778/// [GNU] label-declarations:
779/// [GNU] label-declaration
780/// [GNU] label-declarations label-declaration
781///
782/// [GNU] label-declaration:
783/// [GNU] '__label__' identifier-list ';'
784///
785/// [OMP] openmp-directive: [TODO]
786/// [OMP] barrier-directive
787/// [OMP] flush-directive
Chris Lattner30f910e2006-10-16 05:52:41 +0000788///
Richard Smithc202b282012-04-14 00:33:13 +0000789StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000790 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000791 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000792
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000793 // Enter a scope to hold everything within the compound stmt. Compound
794 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000795 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000796
797 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000798 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000799}
800
Lang Hames2954cea2012-11-03 22:29:05 +0000801/// Parse any pragmas at the start of the compound expression. We handle these
802/// separately since some pragmas (FP_CONTRACT) must appear before any C
803/// statement in the compound, but may be intermingled with other pragmas.
804void Parser::ParseCompoundStatementLeadingPragmas() {
805 bool checkForPragmas = true;
806 while (checkForPragmas) {
807 switch (Tok.getKind()) {
808 case tok::annot_pragma_vis:
809 HandlePragmaVisibility();
810 break;
811 case tok::annot_pragma_pack:
812 HandlePragmaPack();
813 break;
814 case tok::annot_pragma_msstruct:
815 HandlePragmaMSStruct();
816 break;
817 case tok::annot_pragma_align:
818 HandlePragmaAlign();
819 break;
820 case tok::annot_pragma_weak:
821 HandlePragmaWeak();
822 break;
823 case tok::annot_pragma_weakalias:
824 HandlePragmaWeakAlias();
825 break;
826 case tok::annot_pragma_redefine_extname:
827 HandlePragmaRedefineExtname();
828 break;
829 case tok::annot_pragma_opencl_extension:
830 HandlePragmaOpenCLExtension();
831 break;
832 case tok::annot_pragma_fp_contract:
833 HandlePragmaFPContract();
834 break;
David Majnemer4bb09802014-02-10 19:50:15 +0000835 case tok::annot_pragma_ms_pointers_to_members:
836 HandlePragmaMSPointersToMembers();
837 break;
Warren Huntc3b18962014-04-08 22:30:47 +0000838 case tok::annot_pragma_ms_pragma:
839 HandlePragmaMSPragma();
840 break;
Lang Hames2954cea2012-11-03 22:29:05 +0000841 default:
842 checkForPragmas = false;
843 break;
844 }
845 }
846
847}
848
Chris Lattnerf2978802007-01-21 06:52:16 +0000849/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000850/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000851/// consume the '}' at the end of the block. It does not manipulate the scope
852/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000853StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000854 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000855 Tok.getLocation(),
856 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000857
858 // Record the state of the FP_CONTRACT pragma, restore on leaving the
859 // compound statement.
860 Sema::FPContractStateRAII SaveFPContractState(Actions);
861
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000862 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000863 BalancedDelimiterTracker T(*this, tok::l_brace);
864 if (T.consumeOpen())
865 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000866
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000867 Sema::CompoundScopeRAII CompoundScope(Actions);
868
Lang Hames2954cea2012-11-03 22:29:05 +0000869 // Parse any pragmas at the beginning of the compound statement.
870 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000871
Lang Hames2954cea2012-11-03 22:29:05 +0000872 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000873
Chris Lattner43e7f312011-02-18 02:08:43 +0000874 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
875 // only allowed at the start of a compound stmt regardless of the language.
876 while (Tok.is(tok::kw___label__)) {
877 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000878
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000879 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000880 while (1) {
881 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +0000882 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner43e7f312011-02-18 02:08:43 +0000883 break;
884 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000885
Chris Lattner43e7f312011-02-18 02:08:43 +0000886 IdentifierInfo *II = Tok.getIdentifierInfo();
887 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000888 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000889
Alp Tokerec543272013-12-24 09:48:30 +0000890 if (!TryConsumeToken(tok::comma))
Chris Lattner43e7f312011-02-18 02:08:43 +0000891 break;
Chris Lattner43e7f312011-02-18 02:08:43 +0000892 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000893
John McCall084e83d2011-03-24 11:26:52 +0000894 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000895 DeclGroupPtrTy Res =
896 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000897 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000898
Chris Lattner02f1b612012-04-28 16:12:17 +0000899 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000900 if (R.isUsable())
901 Stmts.push_back(R.release());
902 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000903
Richard Smith34f30512013-11-23 04:06:09 +0000904 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000905 if (Tok.is(tok::annot_pragma_unused)) {
906 HandlePragmaUnused();
907 continue;
908 }
909
David Blaikiebbafb8a2012-03-11 07:00:24 +0000910 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet4a7de3e2011-05-06 20:48:22 +0000911 Tok.is(tok::kw___if_not_exists))) {
912 ParseMicrosoftIfExistsStatement(Stmts);
913 continue;
914 }
915
John McCalldadc5752010-08-24 06:29:42 +0000916 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000917 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000918 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000919 } else {
920 // __extension__ can start declarations and it can also be a unary
921 // operator for expressions. Consume multiple __extension__ markers here
922 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000923 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000924 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000925 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000926 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000927
John McCall084e83d2011-03-24 11:26:52 +0000928 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000929 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000930
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000931 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +0000932 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +0000933 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +0000934 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +0000935 ExtensionRAIIObject O(Diags);
936
Chris Lattner49836b42009-04-02 04:16:50 +0000937 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000938 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
939 Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000940 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000941 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000942 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000943 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +0000944 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +0000945
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000946 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000947 SkipUntil(tok::semi);
948 continue;
949 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +0000950
Alexis Hunt96d5c762009-11-21 08:43:09 +0000951 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +0000952 // Eat the semicolon at the end of stmt and convert the expr into a
953 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000954 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000955 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000956 }
957 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000958
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000959 if (R.isUsable())
Sebastian Redld9f7b1c2008-12-10 00:02:53 +0000960 Stmts.push_back(R.release());
Chris Lattner30f910e2006-10-16 05:52:41 +0000961 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000962
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000963 SourceLocation CloseLoc = Tok.getLocation();
964
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000965 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +0000966 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000967 // Recover by creating a compound statement with what we parsed so far,
968 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +0000969 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +0000970
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000971 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000972 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000973}
Chris Lattnerc951dae2006-08-10 04:23:57 +0000974
Chris Lattnerc0081db2008-12-12 06:31:07 +0000975/// ParseParenExprOrCondition:
976/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +0000977/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +0000978///
979/// This function parses and performs error recovery on the specified condition
980/// or expression (depending on whether we're in C++ or C mode). This function
981/// goes out of its way to recover well. It returns true if there was a parser
982/// error (the right paren couldn't be found), which indicates that the caller
983/// should try to recover harder. It returns false if the condition is
984/// successfully parsed. Note that a successful parse can still have semantic
985/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +0000986bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +0000987 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +0000988 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000989 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000990 BalancedDelimiterTracker T(*this, tok::l_paren);
991 T.consumeOpen();
992
David Blaikiebbafb8a2012-03-11 07:00:24 +0000993 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +0000994 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000995 else {
996 ExprResult = ParseExpression();
John McCall48871652010-08-21 09:40:31 +0000997 DeclResult = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000998
Douglas Gregore60e41a2010-05-06 17:25:47 +0000999 // If required, convert to a boolean value.
1000 if (!ExprResult.isInvalid() && ConvertToBoolean)
1001 ExprResult
John McCallb268a282010-08-23 23:25:46 +00001002 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004
Chris Lattnerc0081db2008-12-12 06:31:07 +00001005 // If the parser was confused by the condition and we don't have a ')', try to
1006 // recover by skipping ahead to a semi and bailing out. If condexp is
1007 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +00001008 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +00001009 SkipUntil(tok::semi);
1010 // Skipping may have stopped if it found the containing ')'. If so, we can
1011 // continue parsing the if statement.
1012 if (Tok.isNot(tok::r_paren))
1013 return true;
1014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Chris Lattnerc0081db2008-12-12 06:31:07 +00001016 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001017 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +00001018
Chris Lattner70d44982012-04-28 16:24:20 +00001019 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1020 // that all callers are looking for a statement after the condition, so ")"
1021 // isn't valid.
1022 while (Tok.is(tok::r_paren)) {
1023 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1024 << FixItHint::CreateRemoval(Tok.getLocation());
1025 ConsumeParen();
1026 }
Chad Rosier67055f52012-07-10 21:35:27 +00001027
Chris Lattnerc0081db2008-12-12 06:31:07 +00001028 return false;
1029}
1030
1031
Chris Lattnerc951dae2006-08-10 04:23:57 +00001032/// ParseIfStatement
1033/// if-statement: [C99 6.8.4.1]
1034/// 'if' '(' expression ')' statement
1035/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001036/// [C++] 'if' '(' condition ')' statement
1037/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +00001038///
Richard Smithc202b282012-04-14 00:33:13 +00001039StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001040 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001041 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +00001042
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001043 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001044 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +00001045 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +00001046 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +00001047 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001048
David Blaikiebbafb8a2012-03-11 07:00:24 +00001049 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001050
Chris Lattner2dd1b722007-08-26 23:08:06 +00001051 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1052 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001053 //
1054 // C++ 6.4p3:
1055 // A name introduced by a declaration in a condition is in scope from its
1056 // point of declaration until the end of the substatements controlled by the
1057 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001058 // C++ 3.3.2p4:
1059 // Names declared in the for-init-statement, and in the condition of if,
1060 // while, for, and switch statements are local to the if, while, for, or
1061 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001062 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001063 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001064
Chris Lattnerc951dae2006-08-10 04:23:57 +00001065 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001066 ExprResult CondExp;
John McCall48871652010-08-21 09:40:31 +00001067 Decl *CondVar = 0;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001068 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001069 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001070
David Blaikiea5696df2012-05-16 04:20:04 +00001071 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattner8fb26252007-08-22 05:28:50 +00001073 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001074 // there is no compound stmt. C90 does not have this clause. We only do this
1075 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001076 //
1077 // C++ 6.4p1:
1078 // The substatement in a selection-statement (each substatement, in the else
1079 // form of the if statement) implicitly defines a local scope.
1080 //
1081 // For C++ we create a scope for the condition and a new scope for
1082 // substatements because:
1083 // -When the 'then' scope exits, we want the condition declaration to still be
1084 // active for the 'else' scope too.
1085 // -Sema will detect name clashes by considering declarations of a
1086 // 'ControlScope' as part of its direct subscope.
1087 // -If we wanted the condition and substatement to be in the same scope, we
1088 // would have to notify ParseStatement not to create a new scope. It's
1089 // simpler to let it create a new scope.
1090 //
David Majnemer2206bf52014-03-05 08:57:59 +00001091 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001092
Chris Lattner5c5808a2007-10-29 05:08:52 +00001093 // Read the 'then' stmt.
1094 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001095
1096 SourceLocation InnerStatementTrailingElseLoc;
1097 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001098
Chris Lattner37e54f42007-08-22 05:16:28 +00001099 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001100 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001101
Chris Lattnerc951dae2006-08-10 04:23:57 +00001102 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001103 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001104 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001105 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001106
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001107 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001108 if (TrailingElseLoc)
1109 *TrailingElseLoc = Tok.getLocation();
1110
Chris Lattneraf635312006-10-16 06:06:51 +00001111 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001112 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001113
Chris Lattner8fb26252007-08-22 05:28:50 +00001114 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001115 // there is no compound stmt. C90 does not have this clause. We only do
1116 // this if the body isn't a compound statement to avoid push/pop in common
1117 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001118 //
1119 // C++ 6.4p1:
1120 // The substatement in a selection-statement (each substatement, in the else
1121 // form of the if statement) implicitly defines a local scope.
1122 //
David Majnemer2206bf52014-03-05 08:57:59 +00001123 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001124
Chris Lattner30f910e2006-10-16 05:52:41 +00001125 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001126
Chris Lattner37e54f42007-08-22 05:16:28 +00001127 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001128 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001129 } else if (Tok.is(tok::code_completion)) {
1130 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001131 cutOffParsing();
1132 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001133 } else if (InnerStatementTrailingElseLoc.isValid()) {
1134 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001135 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001136
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001137 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001138
Chris Lattner5c5808a2007-10-29 05:08:52 +00001139 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001140 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001141 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001142 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1143 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1144 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001145 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001146 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001147 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001148
Chris Lattner5c5808a2007-10-29 05:08:52 +00001149 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001150 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001151 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001152 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001153 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001154
John McCallb268a282010-08-23 23:25:46 +00001155 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001156 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001157}
1158
Chris Lattner9075bd72006-08-10 04:59:57 +00001159/// ParseSwitchStatement
1160/// switch-statement:
1161/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001162/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001163StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001164 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001165 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001166
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001167 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001168 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001169 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001170 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001171 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001172
David Blaikiebbafb8a2012-03-11 07:00:24 +00001173 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001174
Chris Lattner2dd1b722007-08-26 23:08:06 +00001175 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1176 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001177 //
1178 // C++ 6.4p3:
1179 // A name introduced by a declaration in a condition is in scope from its
1180 // point of declaration until the end of the substatements controlled by the
1181 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001182 // C++ 3.3.2p4:
1183 // Names declared in the for-init-statement, and in the condition of if,
1184 // while, for, and switch statements are local to the if, while, for, or
1185 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001186 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001187 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001188 if (C99orCXX)
1189 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001190 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001191
Chris Lattner9075bd72006-08-10 04:59:57 +00001192 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001193 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001194 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001195 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001196 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001197
John McCalldadc5752010-08-24 06:29:42 +00001198 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001199 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001200
Douglas Gregore60e41a2010-05-06 17:25:47 +00001201 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001202 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001203 // FIXME: This is not optimal recovery, but parsing the body is more
1204 // dangerous due to the presence of case and default statements, which
1205 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001206 if (Tok.is(tok::l_brace)) {
1207 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001208 SkipUntil(tok::r_brace);
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001209 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001210 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001211 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001212 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001213
Chris Lattner8fb26252007-08-22 05:28:50 +00001214 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001215 // there is no compound stmt. C90 does not have this clause. We only do this
1216 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001217 //
1218 // C++ 6.4p1:
1219 // The substatement in a selection-statement (each substatement, in the else
1220 // form of the if statement) implicitly defines a local scope.
1221 //
1222 // See comments in ParseIfStatement for why we create a scope for the
1223 // condition and a new scope for substatement in C++.
1224 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001225 getCurScope()->AddFlags(Scope::BreakScope);
David Majnemer2206bf52014-03-05 08:57:59 +00001226 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001227
Chris Lattner9075bd72006-08-10 04:59:57 +00001228 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001229 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001230
Chris Lattner8fd2d012010-01-24 01:50:29 +00001231 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001232 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001233 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001234
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001235 if (Body.isInvalid()) {
Chris Lattner8fd2d012010-01-24 01:50:29 +00001236 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001237
1238 // Put the synthesized null statement on the same line as the end of switch
1239 // condition.
1240 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1241 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1242 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001243
John McCallb268a282010-08-23 23:25:46 +00001244 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001245}
1246
1247/// ParseWhileStatement
1248/// while-statement: [C99 6.8.5.1]
1249/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001250/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001251StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001252 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001253 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001254 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001255
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001256 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001257 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001258 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001259 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001260 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001261
David Blaikiebbafb8a2012-03-11 07:00:24 +00001262 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001263
Chris Lattner2dd1b722007-08-26 23:08:06 +00001264 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1265 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001266 //
1267 // C++ 6.4p3:
1268 // A name introduced by a declaration in a condition is in scope from its
1269 // point of declaration until the end of the substatements controlled by the
1270 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001271 // C++ 3.3.2p4:
1272 // Names declared in the for-init-statement, and in the condition of if,
1273 // while, for, and switch statements are local to the if, while, for, or
1274 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001275 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001276 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001277 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001278 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1279 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001280 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001281 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1282 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001283
Chris Lattner9075bd72006-08-10 04:59:57 +00001284 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001285 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001286 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001287 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001288 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001289
David Blaikiea5696df2012-05-16 04:20:04 +00001290 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001291
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001292 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001293 // there is no compound stmt. C90 does not have this clause. We only do this
1294 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001295 //
1296 // C++ 6.5p2:
1297 // The substatement in an iteration-statement implicitly defines a local scope
1298 // which is entered and exited each time through the loop.
1299 //
1300 // See comments in ParseIfStatement for why we create a scope for the
1301 // condition and a new scope for substatement in C++.
1302 //
David Majnemer2206bf52014-03-05 08:57:59 +00001303 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001304
Chris Lattner9075bd72006-08-10 04:59:57 +00001305 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001306 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001307
Chris Lattner8fb26252007-08-22 05:28:50 +00001308 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001309 InnerScope.Exit();
1310 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001311
John McCall48871652010-08-21 09:40:31 +00001312 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001313 return StmtError();
1314
John McCallb268a282010-08-23 23:25:46 +00001315 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001316}
1317
1318/// ParseDoStatement
1319/// do-statement: [C99 6.8.5.2]
1320/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001321/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001322StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001323 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001324 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001325
Chris Lattner2dd1b722007-08-26 23:08:06 +00001326 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1327 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001328 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001329 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001330 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001331 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001332 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001333
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001334 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001335
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001336 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001337 // there is no compound stmt. C90 does not have this clause. We only do this
1338 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001339 //
1340 // C++ 6.5p2:
1341 // The substatement in an iteration-statement implicitly defines a local scope
1342 // which is entered and exited each time through the loop.
1343 //
David Majnemer2206bf52014-03-05 08:57:59 +00001344 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1345 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001346
Chris Lattner9075bd72006-08-10 04:59:57 +00001347 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001348 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001349
Chris Lattner8fb26252007-08-22 05:28:50 +00001350 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001351 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001352
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001353 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001354 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001355 Diag(Tok, diag::err_expected_while);
Alp Tokerec543272013-12-24 09:48:30 +00001356 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001357 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner0046de12008-11-13 18:52:53 +00001358 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001359 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001360 }
Chris Lattneraf635312006-10-16 06:06:51 +00001361 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001362
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001363 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001364 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001365 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001366 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001367 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001368
Richard Smithc2c8bb82013-10-15 01:34:54 +00001369 // Parse the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001370 BalancedDelimiterTracker T(*this, tok::l_paren);
1371 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001372
Richard Smithc2c8bb82013-10-15 01:34:54 +00001373 // A do-while expression is not a condition, so can't have attributes.
1374 DiagnoseAndSkipCXX11Attributes();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001375
John McCalldadc5752010-08-24 06:29:42 +00001376 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001377 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001378 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001379
Sebastian Redlb62406f2008-12-11 19:48:14 +00001380 if (Cond.isInvalid() || Body.isInvalid())
1381 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001382
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001383 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1384 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001385}
1386
1387/// ParseForStatement
1388/// for-statement: [C99 6.8.5.3]
1389/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1390/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001391/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1392/// [C++] statement
Richard Smith02e85f32011-04-14 22:09:26 +00001393/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001394/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1395/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001396///
1397/// [C++] for-init-statement:
1398/// [C++] expression-statement
1399/// [C++] simple-declaration
1400///
Richard Smith02e85f32011-04-14 22:09:26 +00001401/// [C++0x] for-range-declaration:
1402/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1403/// [C++0x] for-range-initializer:
1404/// [C++0x] expression
1405/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001406StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001407 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001408 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001409
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001410 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001411 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001412 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001413 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001414 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001415
Chad Rosier67055f52012-07-10 21:35:27 +00001416 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1417 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001418
Chris Lattner2dd1b722007-08-26 23:08:06 +00001419 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1420 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001421 //
1422 // C++ 6.4p3:
1423 // A name introduced by a declaration in a condition is in scope from its
1424 // point of declaration until the end of the substatements controlled by the
1425 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001426 // C++ 3.3.2p4:
1427 // Names declared in the for-init-statement, and in the condition of if,
1428 // while, for, and switch statements are local to the if, while, for, or
1429 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001430 // C++ 6.5.3p1:
1431 // Names declared in the for-init-statement are in the same declarative-region
1432 // as those declared in the condition.
1433 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001434 unsigned ScopeFlags = 0;
Chris Lattner934074c2009-04-22 00:54:41 +00001435 if (C99orCXXorObjC)
Serge Pavlov09f99242014-01-23 15:05:00 +00001436 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001437
1438 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001439
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001440 BalancedDelimiterTracker T(*this, tok::l_paren);
1441 T.consumeOpen();
1442
John McCalldadc5752010-08-24 06:29:42 +00001443 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001444
Richard Smith02e85f32011-04-14 22:09:26 +00001445 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001446 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001447 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001448 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001449 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001450 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001451 FullExprArg ThirdPart(Actions);
John McCall48871652010-08-21 09:40:31 +00001452 Decl *SecondVar = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001453
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001454 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001455 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001456 C99orCXXorObjC? Sema::PCC_ForInit
1457 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001458 cutOffParsing();
1459 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001460 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001461
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001462 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001463 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001464
Chris Lattner9075bd72006-08-10 04:59:57 +00001465 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001466 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001467 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001468 // no first part, eat the ';'.
1469 ConsumeToken();
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001470 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001471 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001472 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001473 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001474
Richard Smith02e85f32011-04-14 22:09:26 +00001475 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001476 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001477 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1478
Chris Lattner49836b42009-04-02 04:16:50 +00001479 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +00001480 StmtVector Stmts;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001481 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smith02e85f32011-04-14 22:09:26 +00001482 DeclEnd, attrs, false,
1483 MightBeForRangeStmt ?
1484 &ForRangeInit : 0);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001485 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001486
Richard Smith02e85f32011-04-14 22:09:26 +00001487 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001488 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001489 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001490
Richard Smith02e85f32011-04-14 22:09:26 +00001491 ForRange = true;
1492 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001493 ConsumeToken();
1494 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001495 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001496 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001497 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001498
Douglas Gregor68762e72010-08-23 21:17:50 +00001499 if (Tok.is(tok::code_completion)) {
1500 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001501 cutOffParsing();
1502 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001503 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001504 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001505 } else {
1506 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001507 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001508 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001509 ProhibitAttributes(attrs);
Chris Lattner89c50c62006-08-11 06:41:18 +00001510 Value = ParseExpression();
Chris Lattner71e23ce2006-11-04 20:18:38 +00001511
John McCall34376a62010-12-04 03:47:34 +00001512 ForEach = isTokIdentifier_in();
1513
Chris Lattnercd68f642007-06-27 01:06:29 +00001514 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001515 if (!Value.isInvalid()) {
1516 if (ForEach)
1517 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1518 else
Richard Smith945f8d32013-01-14 22:39:08 +00001519 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001520 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001521
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001522 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001523 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001524 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001525 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001526
Douglas Gregor68762e72010-08-23 21:17:50 +00001527 if (Tok.is(tok::code_completion)) {
1528 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001529 cutOffParsing();
1530 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001531 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001532 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001533 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001534 // User tried to write the reasonable, but ill-formed, for-range-statement
1535 // for (expr : expr) { ... }
1536 Diag(Tok, diag::err_for_range_expected_decl)
1537 << FirstPart.get()->getSourceRange();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001538 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smith4f848f12011-12-20 22:56:20 +00001539 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001540 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001541 if (!Value.isInvalid()) {
1542 Diag(Tok, diag::err_expected_semi_for);
1543 } else {
1544 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001545 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001546 if (Tok.is(tok::semi))
1547 ConsumeToken();
1548 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001549 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001550 }
Serge Pavlov09f99242014-01-23 15:05:00 +00001551
1552 // Parse the second part of the for specifier.
1553 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smith02e85f32011-04-14 22:09:26 +00001554 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001555 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001556 // Parse the second part of the for specifier.
1557 if (Tok.is(tok::semi)) { // for (...;;
1558 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001559 } else if (Tok.is(tok::r_paren)) {
1560 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001561 } else {
John McCalldadc5752010-08-24 06:29:42 +00001562 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001563 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001564 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1565 else {
1566 Second = ParseExpression();
1567 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001568 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001569 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001570 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001571 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001572 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001573 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001574
Douglas Gregor230a7e62011-02-17 03:38:46 +00001575 if (Tok.isNot(tok::semi)) {
1576 if (!SecondPartIsInvalid || SecondVar)
1577 Diag(Tok, diag::err_expected_semi_for);
1578 else
1579 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001580 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001581 }
1582
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001583 if (Tok.is(tok::semi)) {
1584 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001585 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001586
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001587 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001588 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001589 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001590 // FIXME: The C++11 standard doesn't actually say that this is a
1591 // discarded-value expression, but it clearly should be.
1592 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001593 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001594 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001595 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001596 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001597
Richard Smith02e85f32011-04-14 22:09:26 +00001598 // We need to perform most of the semantic analysis for a C++0x for-range
1599 // statememt before parsing the body, in order to be able to deduce the type
1600 // of an auto-typed loop variable.
1601 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001602 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001603
John McCall53848232011-07-27 01:07:15 +00001604 if (ForRange) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001605 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smith02e85f32011-04-14 22:09:26 +00001606 ForRangeInit.ColonLoc,
1607 ForRangeInit.RangeExpr.get(),
Richard Smitha05b3b52012-09-20 21:52:32 +00001608 T.getCloseLocation(),
1609 Sema::BFRK_Build);
Richard Smith02e85f32011-04-14 22:09:26 +00001610
John McCall53848232011-07-27 01:07:15 +00001611
1612 // Similarly, we need to do the semantic analysis for a for-range
1613 // statement immediately in order to close over temporaries correctly.
1614 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001615 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001616 FirstPart.take(),
Chad Rosier67055f52012-07-10 21:35:27 +00001617 Collection.take(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001618 T.getCloseLocation());
John McCall53848232011-07-27 01:07:15 +00001619 }
1620
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001621 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001622 // there is no compound stmt. C90 does not have this clause. We only do this
1623 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001624 //
1625 // C++ 6.5p2:
1626 // The substatement in an iteration-statement implicitly defines a local scope
1627 // which is entered and exited each time through the loop.
1628 //
1629 // See comments in ParseIfStatement for why we create a scope for
1630 // for-init-statement/condition and a new scope for substatement in C++.
1631 //
David Majnemer2206bf52014-03-05 08:57:59 +00001632 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1633 Tok.is(tok::l_brace));
1634
1635 // The body of the for loop has the same local mangling number as the
1636 // for-init-statement.
1637 // It will only be incremented if the body contains other things that would
1638 // normally increment the mangling number (like a compound statement).
1639 if (C99orCXXorObjC)
1640 getCurScope()->decrementMSLocalManglingNumber();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001641
Chris Lattner9075bd72006-08-10 04:59:57 +00001642 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001643 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001644
Chris Lattner8fb26252007-08-22 05:28:50 +00001645 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001646 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001647
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001648 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001649 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001650
1651 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001652 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001653
Richard Smith02e85f32011-04-14 22:09:26 +00001654 if (ForEach)
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001655 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1656 Body.take());
Mike Stump11289f42009-09-09 15:08:12 +00001657
Richard Smith02e85f32011-04-14 22:09:26 +00001658 if (ForRange)
1659 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1660
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001661 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1662 SecondPart, SecondVar, ThirdPart,
1663 T.getCloseLocation(), Body.take());
Chris Lattner9075bd72006-08-10 04:59:57 +00001664}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001665
Chris Lattner503fadc2006-08-10 05:45:44 +00001666/// ParseGotoStatement
1667/// jump-statement:
1668/// 'goto' identifier ';'
1669/// [GNU] 'goto' '*' expression ';'
1670///
1671/// Note: this lets the caller parse the end ';'.
1672///
Richard Smithc202b282012-04-14 00:33:13 +00001673StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001674 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001675 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001676
John McCalldadc5752010-08-24 06:29:42 +00001677 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001678 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001679 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1680 Tok.getLocation());
1681 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001682 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001683 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001684 // GNU indirect goto extension.
1685 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001686 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001687 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001688 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001689 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001690 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001691 }
John McCallb268a282010-08-23 23:25:46 +00001692 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001693 } else {
Alp Tokerec543272013-12-24 09:48:30 +00001694 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001695 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001696 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001697
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001698 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001699}
1700
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001701/// ParseContinueStatement
1702/// jump-statement:
1703/// 'continue' ';'
1704///
1705/// Note: this lets the caller parse the end ';'.
1706///
Richard Smithc202b282012-04-14 00:33:13 +00001707StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001708 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001709 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001710}
1711
1712/// ParseBreakStatement
1713/// jump-statement:
1714/// 'break' ';'
1715///
1716/// Note: this lets the caller parse the end ';'.
1717///
Richard Smithc202b282012-04-14 00:33:13 +00001718StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001719 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001720 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001721}
1722
Chris Lattner503fadc2006-08-10 05:45:44 +00001723/// ParseReturnStatement
1724/// jump-statement:
1725/// 'return' expression[opt] ';'
Richard Smithc202b282012-04-14 00:33:13 +00001726StmtResult Parser::ParseReturnStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001727 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001728 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001729
John McCalldadc5752010-08-24 06:29:42 +00001730 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001731 if (Tok.isNot(tok::semi)) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001732 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001733 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001734 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001735 return StmtError();
1736 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001737
David Blaikiebbafb8a2012-03-11 07:00:24 +00001738 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001739 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001740 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001741 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001742 diag::warn_cxx98_compat_generalized_initializer_lists :
1743 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001744 << R.get()->getSourceRange();
1745 } else
1746 R = ParseExpression();
Serge Pavlovf79bd5c2013-12-04 03:51:59 +00001747 if (R.isInvalid()) {
1748 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001749 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001750 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001751 }
John McCallb268a282010-08-23 23:25:46 +00001752 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Chris Lattner503fadc2006-08-10 05:45:44 +00001753}
Chris Lattner0116c472006-08-15 06:03:28 +00001754
John McCallf413f5e2013-05-03 00:10:13 +00001755namespace {
1756 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1757 Parser &TheParser;
1758 SourceLocation AsmLoc;
1759 StringRef AsmString;
1760
1761 /// The tokens we streamed into AsmString and handed off to MC.
1762 ArrayRef<Token> AsmToks;
1763
1764 /// The offset of each token in AsmToks within AsmString.
1765 ArrayRef<unsigned> AsmTokOffsets;
1766
1767 public:
1768 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1769 StringRef AsmString,
1770 ArrayRef<Token> Toks,
1771 ArrayRef<unsigned> Offsets)
1772 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1773 AsmToks(Toks), AsmTokOffsets(Offsets) {
1774 assert(AsmToks.size() == AsmTokOffsets.size());
1775 }
1776
1777 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1778 InlineAsmIdentifierInfo &Info,
Craig Topper2b07f022014-03-12 05:09:18 +00001779 bool IsUnevaluatedContext) override {
John McCallf413f5e2013-05-03 00:10:13 +00001780 // Collect the desired tokens.
1781 SmallVector<Token, 16> LineToks;
1782 const Token *FirstOrigToken = 0;
1783 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1784
1785 unsigned NumConsumedToks;
1786 ExprResult Result =
1787 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1788 IsUnevaluatedContext);
1789
1790 // If we consumed the entire line, tell MC that.
1791 // Also do this if we consumed nothing as a way of reporting failure.
1792 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1793 // By not modifying LineBuf, we're implicitly consuming it all.
1794
1795 // Otherwise, consume up to the original tokens.
1796 } else {
1797 assert(FirstOrigToken && "not using original tokens?");
1798
1799 // Since we're using original tokens, apply that offset.
1800 assert(FirstOrigToken[NumConsumedToks].getLocation()
1801 == LineToks[NumConsumedToks].getLocation());
1802 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1803 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1804
1805 // The total length we've consumed is the relative offset
1806 // of the last token we consumed plus its length.
1807 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1808 + AsmToks[LastIndex].getLength()
1809 - AsmTokOffsets[FirstIndex]);
1810 LineBuf = LineBuf.substr(0, TotalOffset);
1811 }
1812
1813 // Initialize the "decl" with the lookup result.
1814 Info.OpDecl = static_cast<void*>(Result.take());
1815 return Info.OpDecl;
1816 }
1817
1818 bool LookupInlineAsmField(StringRef Base, StringRef Member,
Craig Topper2b07f022014-03-12 05:09:18 +00001819 unsigned &Offset) override {
John McCallf413f5e2013-05-03 00:10:13 +00001820 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1821 Offset, AsmLoc);
1822 }
1823
1824 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1825 void *Context) {
1826 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1827 }
1828
1829 private:
1830 /// Collect the appropriate tokens for the given string.
1831 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1832 const Token *&FirstOrigToken) const {
1833 // For now, assert that the string we're working with is a substring
1834 // of what we gave to MC. This lets us use the original tokens.
1835 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1836 !std::less<const char*>()(AsmString.end(), Str.end()));
1837
1838 // Try to find a token whose offset matches the first token.
1839 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1840 const unsigned *FirstTokOffset
1841 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1842 FirstCharOffset);
1843
1844 // For now, assert that the start of the string exactly
1845 // corresponds to the start of a token.
1846 assert(*FirstTokOffset == FirstCharOffset);
1847
1848 // Use all the original tokens for this line. (We assume the
1849 // end of the line corresponds cleanly to a token break.)
1850 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1851 FirstOrigToken = &AsmToks[FirstTokIndex];
1852 unsigned LastCharOffset = Str.end() - AsmString.begin();
1853 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1854 if (AsmTokOffsets[i] >= LastCharOffset) break;
1855 TempToks.push_back(AsmToks[i]);
1856 }
1857 }
1858
1859 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1860 // Compute an offset into the inline asm buffer.
1861 // FIXME: This isn't right if .macro is involved (but hopefully, no
1862 // real-world code does that).
1863 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1864 const llvm::MemoryBuffer *LBuf =
1865 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1866 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1867
1868 // Figure out which token that offset points into.
1869 const unsigned *TokOffsetPtr =
1870 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1871 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1872 unsigned TokOffset = *TokOffsetPtr;
1873
1874 // If we come up with an answer which seems sane, use it; otherwise,
1875 // just point at the __asm keyword.
1876 // FIXME: Assert the answer is sane once we handle .macro correctly.
1877 SourceLocation Loc = AsmLoc;
1878 if (TokIndex < AsmToks.size()) {
1879 const Token &Tok = AsmToks[TokIndex];
1880 Loc = Tok.getLocation();
1881 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1882 }
1883 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1884 << D.getMessage();
1885 }
1886 };
1887}
1888
1889/// Parse an identifier in an MS-style inline assembly block.
1890///
1891/// \param CastInfo - a void* so that we don't have to teach Parser.h
1892/// about the actual type.
1893ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1894 unsigned &NumLineToksConsumed,
1895 void *CastInfo,
1896 bool IsUnevaluatedContext) {
1897 llvm::InlineAsmIdentifierInfo &Info =
1898 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1899
1900 // Push a fake token on the end so that we don't overrun the token
1901 // stream. We use ';' because it expression-parsing should never
1902 // overrun it.
1903 const tok::TokenKind EndOfStream = tok::semi;
1904 Token EndOfStreamTok;
1905 EndOfStreamTok.startToken();
1906 EndOfStreamTok.setKind(EndOfStream);
1907 LineToks.push_back(EndOfStreamTok);
1908
1909 // Also copy the current token over.
1910 LineToks.push_back(Tok);
1911
1912 PP.EnterTokenStream(LineToks.begin(),
1913 LineToks.size(),
1914 /*disable macros*/ true,
1915 /*owns tokens*/ false);
1916
1917 // Clear the current token and advance to the first token in LineToks.
1918 ConsumeAnyToken();
1919
1920 // Parse an optional scope-specifier if we're in C++.
1921 CXXScopeSpec SS;
1922 if (getLangOpts().CPlusPlus) {
1923 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1924 }
1925
1926 // Require an identifier here.
1927 SourceLocation TemplateKWLoc;
1928 UnqualifiedId Id;
1929 bool Invalid = ParseUnqualifiedId(SS,
1930 /*EnteringContext=*/false,
1931 /*AllowDestructorName=*/false,
1932 /*AllowConstructorName=*/false,
1933 /*ObjectType=*/ ParsedType(),
1934 TemplateKWLoc,
1935 Id);
1936
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001937 // Figure out how many tokens we are into LineToks.
1938 unsigned LineIndex = 0;
1939 if (Tok.is(EndOfStream)) {
1940 LineIndex = LineToks.size() - 2;
John McCallf413f5e2013-05-03 00:10:13 +00001941 } else {
John McCallf413f5e2013-05-03 00:10:13 +00001942 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1943 LineIndex++;
1944 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1945 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001946 }
John McCallf413f5e2013-05-03 00:10:13 +00001947
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001948 // If we've run into the poison token we inserted before, or there
1949 // was a parsing error, then claim the entire line.
1950 if (Invalid || Tok.is(EndOfStream)) {
1951 NumLineToksConsumed = LineToks.size() - 2;
1952 } else {
1953 // Otherwise, claim up to the start of the next token.
John McCallf413f5e2013-05-03 00:10:13 +00001954 NumLineToksConsumed = LineIndex;
1955 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001956
1957 // Finally, restore the old parsing state by consuming all the tokens we
1958 // staged before, implicitly killing off the token-lexer we pushed.
1959 for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
John McCallf413f5e2013-05-03 00:10:13 +00001960 ConsumeAnyToken();
1961 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001962 assert(Tok.is(EndOfStream));
1963 ConsumeToken();
John McCallf413f5e2013-05-03 00:10:13 +00001964
1965 // Leave LineToks in its original state.
1966 LineToks.pop_back();
1967 LineToks.pop_back();
1968
1969 // Perform the lookup.
1970 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1971 IsUnevaluatedContext);
1972}
1973
1974/// Turn a sequence of our tokens back into a string that we can hand
1975/// to the MC asm parser.
1976static bool buildMSAsmString(Preprocessor &PP,
1977 SourceLocation AsmLoc,
1978 ArrayRef<Token> AsmToks,
1979 SmallVectorImpl<unsigned> &TokOffsets,
1980 SmallString<512> &Asm) {
1981 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1982
1983 // Is this the start of a new assembly statement?
1984 bool isNewStatement = true;
1985
1986 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1987 const Token &Tok = AsmToks[i];
1988
1989 // Start each new statement with a newline and a tab.
1990 if (!isNewStatement &&
1991 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1992 Asm += "\n\t";
1993 isNewStatement = true;
1994 }
1995
1996 // Preserve the existence of leading whitespace except at the
1997 // start of a statement.
1998 if (!isNewStatement && Tok.hasLeadingSpace())
1999 Asm += ' ';
2000
2001 // Remember the offset of this token.
2002 TokOffsets.push_back(Asm.size());
2003
2004 // Don't actually write '__asm' into the assembly stream.
2005 if (Tok.is(tok::kw_asm)) {
2006 // Complain about __asm at the end of the stream.
2007 if (i + 1 == e) {
2008 PP.Diag(AsmLoc, diag::err_asm_empty);
2009 return true;
2010 }
2011
2012 continue;
2013 }
2014
2015 // Append the spelling of the token.
2016 SmallString<32> SpellingBuffer;
2017 bool SpellingInvalid = false;
2018 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
2019 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
2020
2021 // We are no longer at the start of a statement.
2022 isNewStatement = false;
2023 }
2024
2025 // Ensure that the buffer is null-terminated.
2026 Asm.push_back('\0');
2027 Asm.pop_back();
2028
2029 assert(TokOffsets.size() == AsmToks.size());
2030 return false;
2031}
2032
Eli Friedmana4b02c32011-09-30 01:13:51 +00002033/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
2034/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier32503022012-06-11 20:47:18 +00002035///
2036/// [MS] ms-asm-statement:
2037/// ms-asm-block
2038/// ms-asm-block ms-asm-statement
2039///
2040/// [MS] ms-asm-block:
2041/// '__asm' ms-asm-line '\n'
2042/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
2043///
2044/// [MS] ms-asm-instruction-block
2045/// ms-asm-line
2046/// ms-asm-line '\n' ms-asm-instruction-block
2047///
Eli Friedmana4b02c32011-09-30 01:13:51 +00002048StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
2049 SourceManager &SrcMgr = PP.getSourceManager();
2050 SourceLocation EndLoc = AsmLoc;
Chad Rosier32503022012-06-11 20:47:18 +00002051 SmallVector<Token, 4> AsmToks;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002052
2053 bool InBraces = false;
2054 unsigned short savedBraceCount = 0;
2055 bool InAsmComment = false;
2056 FileID FID;
2057 unsigned LineNo = 0;
2058 unsigned NumTokensRead = 0;
2059 SourceLocation LBraceLoc;
2060
2061 if (Tok.is(tok::l_brace)) {
2062 // Braced inline asm: consume the opening brace.
2063 InBraces = true;
2064 savedBraceCount = BraceCount;
2065 EndLoc = LBraceLoc = ConsumeBrace();
2066 ++NumTokensRead;
2067 } else {
2068 // Single-line inline asm; compute which line it is on.
2069 std::pair<FileID, unsigned> ExpAsmLoc =
2070 SrcMgr.getDecomposedExpansionLoc(EndLoc);
2071 FID = ExpAsmLoc.first;
2072 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2073 }
2074
2075 SourceLocation TokLoc = Tok.getLocation();
Eli Friedmana4b02c32011-09-30 01:13:51 +00002076 do {
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002077 // If we hit EOF, we're done, period.
Richard Smith34f30512013-11-23 04:06:09 +00002078 if (isEofOrEom())
Eli Friedmana4b02c32011-09-30 01:13:51 +00002079 break;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002080
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002081 if (!InAsmComment && Tok.is(tok::semi)) {
2082 // A semicolon in an asm is the start of a comment.
2083 InAsmComment = true;
2084 if (InBraces) {
2085 // Compute which line the comment is on.
2086 std::pair<FileID, unsigned> ExpSemiLoc =
2087 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2088 FID = ExpSemiLoc.first;
2089 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2090 }
2091 } else if (!InBraces || InAsmComment) {
2092 // If end-of-line is significant, check whether this token is on a
2093 // new line.
2094 std::pair<FileID, unsigned> ExpLoc =
2095 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2096 if (ExpLoc.first != FID ||
2097 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2098 // If this is a single-line __asm, we're done.
2099 if (!InBraces)
2100 break;
2101 // We're no longer in a comment.
2102 InAsmComment = false;
2103 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2104 // Single-line asm always ends when a closing brace is seen.
2105 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2106 // does MSVC do here?
2107 break;
2108 }
2109 }
2110 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2111 BraceCount == (savedBraceCount + 1)) {
2112 // Consume the closing brace, and finish
2113 EndLoc = ConsumeBrace();
2114 break;
2115 }
2116
2117 // Consume the next token; make sure we don't modify the brace count etc.
2118 // if we are in a comment.
2119 EndLoc = TokLoc;
2120 if (InAsmComment)
2121 PP.Lex(Tok);
2122 else {
2123 AsmToks.push_back(Tok);
2124 ConsumeAnyToken();
2125 }
2126 TokLoc = Tok.getLocation();
2127 ++NumTokensRead;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002128 } while (1);
Chad Rosier32503022012-06-11 20:47:18 +00002129
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002130 if (InBraces && BraceCount != savedBraceCount) {
2131 // __asm without closing brace (this can happen at EOF).
Alp Tokerec543272013-12-24 09:48:30 +00002132 Diag(Tok, diag::err_expected) << tok::r_brace;
2133 Diag(LBraceLoc, diag::note_matching) << tok::l_brace;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002134 return StmtError();
2135 } else if (NumTokensRead == 0) {
2136 // Empty __asm.
Alp Tokerec543272013-12-24 09:48:30 +00002137 Diag(Tok, diag::err_expected) << tok::l_brace;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002138 return StmtError();
2139 }
2140
John McCallf413f5e2013-05-03 00:10:13 +00002141 // Okay, prepare to use MC to parse the assembly.
2142 SmallVector<StringRef, 4> ConstraintRefs;
2143 SmallVector<Expr*, 4> Exprs;
2144 SmallVector<StringRef, 4> ClobberRefs;
2145
2146 // We need an actual supported target.
Benjamin Kramer9299637dc2014-03-04 19:31:42 +00002147 const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
John McCallf413f5e2013-05-03 00:10:13 +00002148 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
Alp Tokerb3644282013-10-30 15:07:10 +00002149 const std::string &TT = TheTriple.getTriple();
2150 const llvm::Target *TheTarget = 0;
John McCallf413f5e2013-05-03 00:10:13 +00002151 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2152 ArchTy != llvm::Triple::x86_64);
Alp Tokerb3644282013-10-30 15:07:10 +00002153 if (UnsupportedArch) {
John McCallf413f5e2013-05-03 00:10:13 +00002154 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
Alp Tokerb3644282013-10-30 15:07:10 +00002155 } else {
2156 std::string Error;
2157 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2158 if (!TheTarget)
2159 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
2160 }
Alp Toker45cf31f2013-10-30 14:29:28 +00002161
John McCallf413f5e2013-05-03 00:10:13 +00002162 // If we don't support assembly, or the assembly is empty, we don't
2163 // need to instantiate the AsmParser, etc.
Alp Tokerb3644282013-10-30 15:07:10 +00002164 if (!TheTarget || AsmToks.empty()) {
John McCallf413f5e2013-05-03 00:10:13 +00002165 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2166 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2167 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2168 }
2169
2170 // Expand the tokens into a string buffer.
2171 SmallString<512> AsmString;
2172 SmallVector<unsigned, 8> TokOffsets;
2173 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2174 return StmtError();
2175
Ahmed Charlesb8984322014-03-07 20:03:18 +00002176 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2177 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002178 // Get the instruction descriptor.
Ahmed Charlesb8984322014-03-07 20:03:18 +00002179 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
2180 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2181 std::unique_ptr<llvm::MCSubtargetInfo> STI(
2182 TheTarget->createMCSubtargetInfo(TT, "", ""));
John McCallf413f5e2013-05-03 00:10:13 +00002183
2184 llvm::SourceMgr TempSrcMgr;
Bill Wendlingda1e3e72013-06-18 07:22:05 +00002185 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallf413f5e2013-05-03 00:10:13 +00002186 llvm::MemoryBuffer *Buffer =
2187 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2188
2189 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2190 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2191
Ahmed Charlesb8984322014-03-07 20:03:18 +00002192 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2193 std::unique_ptr<llvm::MCAsmParser> Parser(
2194 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +00002195
2196 // FIXME: init MCOptions from sanitizer flags here.
2197 llvm::MCTargetOptions MCOptions;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002198 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +00002199 TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
John McCallf413f5e2013-05-03 00:10:13 +00002200
Nico Weber01708cd2014-04-23 19:19:20 +00002201 std::unique_ptr<llvm::MCInstPrinter> IP(
2202 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI));
John McCallf413f5e2013-05-03 00:10:13 +00002203
2204 // Change to the Intel dialect.
2205 Parser->setAssemblerDialect(1);
2206 Parser->setTargetParser(*TargetParser.get());
2207 Parser->setParsingInlineAsm(true);
2208 TargetParser->setParsingInlineAsm(true);
2209
2210 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2211 AsmToks, TokOffsets);
2212 TargetParser->setSemaCallback(&Callback);
2213 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2214 &Callback);
2215
2216 unsigned NumOutputs;
2217 unsigned NumInputs;
2218 std::string AsmStringIR;
2219 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2220 SmallVector<std::string, 4> Constraints;
2221 SmallVector<std::string, 4> Clobbers;
2222 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2223 NumOutputs, NumInputs, OpExprs, Constraints,
Nico Weber01708cd2014-04-23 19:19:20 +00002224 Clobbers, MII, IP.get(), Callback))
John McCallf413f5e2013-05-03 00:10:13 +00002225 return StmtError();
2226
Reid Kleckner185940a2014-03-27 00:00:03 +00002227 // Filter out "fpsw". Clang doesn't accept it, and it always lists flags and
2228 // fpsr as clobbers.
2229 auto End = std::remove(Clobbers.begin(), Clobbers.end(), "fpsw");
2230 Clobbers.erase(End, Clobbers.end());
2231
John McCallf413f5e2013-05-03 00:10:13 +00002232 // Build the vector of clobber StringRefs.
2233 unsigned NumClobbers = Clobbers.size();
2234 ClobberRefs.resize(NumClobbers);
2235 for (unsigned i = 0; i != NumClobbers; ++i)
2236 ClobberRefs[i] = StringRef(Clobbers[i]);
2237
2238 // Recast the void pointers and build the vector of constraint StringRefs.
2239 unsigned NumExprs = NumOutputs + NumInputs;
2240 ConstraintRefs.resize(NumExprs);
2241 Exprs.resize(NumExprs);
2242 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2243 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2244 if (!OpExpr)
2245 return StmtError();
2246
2247 // Need address of variable.
2248 if (OpExprs[i].second)
2249 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2250 .take();
2251
2252 ConstraintRefs[i] = StringRef(Constraints[i]);
2253 Exprs[i] = OpExpr;
2254 }
2255
Chad Rosierc6c71332012-08-06 20:03:45 +00002256 // FIXME: We should be passing source locations for better diagnostics.
John McCallf413f5e2013-05-03 00:10:13 +00002257 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2258 NumOutputs, NumInputs,
2259 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002260}
2261
Chris Lattner0116c472006-08-15 06:03:28 +00002262/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff69e8f9e2008-02-11 23:15:56 +00002263/// asm-statement:
2264/// gnu-asm-statement
2265/// ms-asm-statement
2266///
2267/// [GNU] gnu-asm-statement:
Chris Lattner0116c472006-08-15 06:03:28 +00002268/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2269///
2270/// [GNU] asm-argument:
2271/// asm-string-literal
2272/// asm-string-literal ':' asm-operands[opt]
2273/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2274/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2275/// ':' asm-clobbers
2276///
2277/// [GNU] asm-clobbers:
2278/// asm-string-literal
2279/// asm-clobbers ',' asm-string-literal
2280///
John McCalldadc5752010-08-24 06:29:42 +00002281StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002282 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattner73c56c02007-10-29 04:04:16 +00002283 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002284
Chad Rosierc8e56e82012-12-05 21:08:21 +00002285 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosier67055f52012-07-10 21:35:27 +00002286 !isTypeQualifier()) {
Steve Naroffb2c80c72008-02-07 03:50:06 +00002287 msAsm = true;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002288 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002289 }
John McCall084e83d2011-03-24 11:26:52 +00002290 DeclSpec DS(AttrFactory);
Chris Lattner0116c472006-08-15 06:03:28 +00002291 SourceLocation Loc = Tok.getLocation();
Alexis Hunt96d5c762009-11-21 08:43:09 +00002292 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002293
Chris Lattner0116c472006-08-15 06:03:28 +00002294 // GNU asms accept, but warn, about type-qualifiers other than volatile.
Chris Lattnera925dc62006-11-28 04:33:46 +00002295 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner6d29c102008-11-18 07:48:38 +00002296 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Chris Lattnera925dc62006-11-28 04:33:46 +00002297 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner6d29c102008-11-18 07:48:38 +00002298 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith8e1ac332013-03-28 01:55:44 +00002299 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2300 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2301 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redlb62406f2008-12-11 19:48:14 +00002302
Chris Lattner0116c472006-08-15 06:03:28 +00002303 // Remember if this was a volatile asm.
Anders Carlsson660bdd12007-11-23 23:12:25 +00002304 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002305 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002306 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Alexey Bataevee6507d2013-11-18 08:17:37 +00002307 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002308 return StmtError();
Chris Lattner0116c472006-08-15 06:03:28 +00002309 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002310 BalancedDelimiterTracker T(*this, tok::l_paren);
2311 T.consumeOpen();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002312
John McCalldadc5752010-08-24 06:29:42 +00002313 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002314 if (AsmString.isInvalid()) {
Richard Smithd67aea22012-03-06 03:21:47 +00002315 // Consume up to and including the closing paren.
2316 T.skipToEnd();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002317 return StmtError();
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002318 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002319
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002320 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002321 ExprVector Constraints;
2322 ExprVector Exprs;
2323 ExprVector Clobbers;
Chris Lattner0116c472006-08-15 06:03:28 +00002324
Anders Carlsson19fe1162008-02-05 23:03:50 +00002325 if (Tok.is(tok::r_paren)) {
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002326 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002327 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002328 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2329 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2330 Constraints, Exprs, AsmString.take(),
2331 Clobbers, T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002332 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002333
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002334 // Parse Outputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002335 bool AteExtraColon = false;
2336 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2337 // In C++ mode, parse "::" like ": :".
2338 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002339 ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002340
Chris Lattner15768502009-12-20 23:08:04 +00002341 if (!AteExtraColon &&
2342 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002343 return StmtError();
2344 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002345
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002346 unsigned NumOutputs = Names.size();
2347
2348 // Parse Inputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002349 if (AteExtraColon ||
2350 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2351 // In C++ mode, parse "::" like ": :".
2352 if (AteExtraColon)
2353 AteExtraColon = false;
2354 else {
2355 AteExtraColon = Tok.is(tok::coloncolon);
2356 ConsumeToken();
2357 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002358
Chris Lattner15768502009-12-20 23:08:04 +00002359 if (!AteExtraColon &&
2360 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002361 return StmtError();
2362 }
2363
2364 assert(Names.size() == Constraints.size() &&
2365 Constraints.size() == Exprs.size() &&
2366 "Input operand size mismatch!");
2367
2368 unsigned NumInputs = Names.size() - NumOutputs;
2369
2370 // Parse the clobbers, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002371 if (AteExtraColon || Tok.is(tok::colon)) {
2372 if (!AteExtraColon)
2373 ConsumeToken();
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002374
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002375 // Parse the asm-string list for clobbers if present.
2376 if (Tok.isNot(tok::r_paren)) {
2377 while (1) {
John McCalldadc5752010-08-24 06:29:42 +00002378 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002379
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002380 if (Clobber.isInvalid())
2381 break;
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002382
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002383 Clobbers.push_back(Clobber.release());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002384
Alp Toker97650562014-01-10 11:19:30 +00002385 if (!TryConsumeToken(tok::comma))
2386 break;
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002387 }
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002388 }
2389 }
2390
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002391 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002392 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2393 NumInputs, Names.data(), Constraints, Exprs,
2394 AsmString.take(), Clobbers,
2395 T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002396}
2397
2398/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002399/// asm-statement, assuming the leading ':' token was eaten.
Chris Lattner0116c472006-08-15 06:03:28 +00002400///
2401/// [GNU] asm-operands:
2402/// asm-operand
2403/// asm-operands ',' asm-operand
2404///
2405/// [GNU] asm-operand:
2406/// asm-string-literal '(' expression ')'
2407/// '[' identifier ']' asm-string-literal '(' expression ')'
2408///
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00002409//
2410// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002411bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieu2bd04012011-09-09 02:00:50 +00002412 SmallVectorImpl<Expr *> &Constraints,
2413 SmallVectorImpl<Expr *> &Exprs) {
Chris Lattner0116c472006-08-15 06:03:28 +00002414 // 'asm-operands' isn't present?
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002415 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002416 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002417
2418 while (1) {
Chris Lattner0116c472006-08-15 06:03:28 +00002419 // Read the [id] if present.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002420 if (Tok.is(tok::l_square)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002421 BalancedDelimiterTracker T(*this, tok::l_square);
2422 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00002423
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002424 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00002425 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00002426 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002427 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002428 }
Mike Stump11289f42009-09-09 15:08:12 +00002429
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002430 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner645ff3f2007-10-29 04:06:22 +00002431 ConsumeToken();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002432
Anders Carlsson9a020f92010-01-30 22:25:16 +00002433 Names.push_back(II);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002434 T.consumeClose();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002435 } else
Anders Carlsson9a020f92010-01-30 22:25:16 +00002436 Names.push_back(0);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002437
John McCalldadc5752010-08-24 06:29:42 +00002438 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002439 if (Constraint.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002440 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002441 return true;
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002442 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002443 Constraints.push_back(Constraint.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002444
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002445 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002446 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Alexey Bataevee6507d2013-11-18 08:17:37 +00002447 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002448 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002449 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002450
Chris Lattner0116c472006-08-15 06:03:28 +00002451 // Read the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002452 BalancedDelimiterTracker T(*this, tok::l_paren);
2453 T.consumeOpen();
John McCalldadc5752010-08-24 06:29:42 +00002454 ExprResult Res(ParseExpression());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002455 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002456 if (Res.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002457 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002458 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002459 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002460 Exprs.push_back(Res.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002461 // Eat the comma and continue parsing if it exists.
Alp Toker97650562014-01-10 11:19:30 +00002462 if (!TryConsumeToken(tok::comma))
2463 return false;
Chris Lattner0116c472006-08-15 06:03:28 +00002464 }
2465}
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002466
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002467Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002468 assert(Tok.is(tok::l_brace));
2469 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002470
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00002471 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00002472 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002473 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002474 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002475 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002476
John McCallfaf5fb42010-08-26 23:41:50 +00002477 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2478 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002479
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002480 // Do not enter a scope for the brace, as the arguments are in the same scope
2481 // (the function body) as the body itself. Instead, just read the statement
2482 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002483 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002484
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002485 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002486 if (FnBody.isInvalid()) {
2487 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002488 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002489 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002490
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002491 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002492 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002493}
Sebastian Redlb219c902008-12-21 16:41:36 +00002494
Sebastian Redla7b98a72009-04-26 20:35:05 +00002495/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2496///
2497/// function-try-block:
2498/// 'try' ctor-initializer[opt] compound-statement handler-seq
2499///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002500Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002501 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2502 SourceLocation TryLoc = ConsumeToken();
2503
John McCallfaf5fb42010-08-26 23:41:50 +00002504 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2505 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002506
2507 // Constructor initializer list?
2508 if (Tok.is(tok::colon))
2509 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002510 else
2511 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002512
Richard Smith1ab34b32012-11-19 21:13:18 +00002513 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2514 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002515 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002516 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002517 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002518
Sebastian Redld98ecd62009-04-26 21:08:36 +00002519 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002520 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00002521 // If we failed to parse the try-catch, we just give the function an empty
2522 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002523 if (FnBody.isInvalid()) {
2524 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002525 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002526 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002527
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002528 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002529 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002530}
2531
Erik Verbruggen6e922512012-04-12 10:11:59 +00002532bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002533 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00002534 assert(SkipFunctionBodies &&
2535 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002536
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002537 if (!PP.isCodeCompletionEnabled()) {
2538 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002539 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002540 return true;
2541 }
2542
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002543 // We're in code-completion mode. Skip parsing for all function bodies unless
2544 // the body contains the code-completion point.
2545 TentativeParsingAction PA(*this);
2546 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002547 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002548 PA.Commit();
2549 return true;
2550 }
2551
2552 PA.Revert();
2553 return false;
2554}
2555
Sebastian Redlb219c902008-12-21 16:41:36 +00002556/// ParseCXXTryBlock - Parse a C++ try-block.
2557///
2558/// try-block:
2559/// 'try' compound-statement handler-seq
2560///
Richard Smithc202b282012-04-14 00:33:13 +00002561StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002562 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2563
2564 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002565 return ParseCXXTryBlockCommon(TryLoc);
2566}
2567
2568/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2569/// function-try-block.
2570///
2571/// try-block:
2572/// 'try' compound-statement handler-seq
2573///
2574/// function-try-block:
2575/// 'try' ctor-initializer[opt] compound-statement handler-seq
2576///
2577/// handler-seq:
2578/// handler handler-seq[opt]
2579///
John Wiegley1c0675e2011-04-28 01:08:34 +00002580/// [Borland] try-block:
2581/// 'try' compound-statement seh-except-block
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002582/// 'try' compound-statement seh-finally-block
John Wiegley1c0675e2011-04-28 01:08:34 +00002583///
David Blaikie1c9c9042012-11-10 01:04:23 +00002584StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002585 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002586 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002587 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002588
2589 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikie3403feb2012-11-13 18:51:45 +00002590 Scope::DeclScope | Scope::TryScope |
2591 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002592 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002593 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002594
John Wiegley1c0675e2011-04-28 01:08:34 +00002595 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002596
Richard Smithc202b282012-04-14 00:33:13 +00002597 if ((Tok.is(tok::identifier) &&
2598 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2599 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002600 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2601 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002602 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002603 SourceLocation Loc = ConsumeToken();
2604 Handler = ParseSEHExceptBlock(Loc);
2605 }
2606 else {
2607 SourceLocation Loc = ConsumeToken();
2608 Handler = ParseSEHFinallyBlock(Loc);
2609 }
2610 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002611 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002612
John Wiegley1c0675e2011-04-28 01:08:34 +00002613 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2614 TryLoc,
2615 TryBlock.take(),
2616 Handler.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002617 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002618 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002619 StmtVector Handlers;
Richard Smithc2c8bb82013-10-15 01:34:54 +00002620
2621 // C++11 attributes can't appear here, despite this context seeming
2622 // statement-like.
2623 DiagnoseAndSkipCXX11Attributes();
Sebastian Redlb219c902008-12-21 16:41:36 +00002624
John Wiegley1c0675e2011-04-28 01:08:34 +00002625 if (Tok.isNot(tok::kw_catch))
2626 return StmtError(Diag(Tok, diag::err_expected_catch));
2627 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002628 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002629 if (!Handler.isInvalid())
2630 Handlers.push_back(Handler.release());
2631 }
2632 // Don't bother creating the full statement if we don't have any usable
2633 // handlers.
2634 if (Handlers.empty())
2635 return StmtError();
2636
Robert Wilhelmcafda822013-08-22 09:20:03 +00002637 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002638 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002639}
2640
2641/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2642///
Richard Smith1dba27c2013-01-29 09:02:09 +00002643/// handler:
2644/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002645///
Richard Smith1dba27c2013-01-29 09:02:09 +00002646/// exception-declaration:
2647/// attribute-specifier-seq[opt] type-specifier-seq declarator
2648/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2649/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002650///
David Blaikie1c9c9042012-11-10 01:04:23 +00002651StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002652 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2653
2654 SourceLocation CatchLoc = ConsumeToken();
2655
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002656 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002657 if (T.expectAndConsume())
Sebastian Redlb219c902008-12-21 16:41:36 +00002658 return StmtError();
2659
2660 // C++ 3.3.2p3:
2661 // The name in a catch exception-declaration is local to the handler and
2662 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002663 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002664 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002665
2666 // exception-declaration is equivalent to '...' or a parameter-declaration
2667 // without default arguments.
John McCall48871652010-08-21 09:40:31 +00002668 Decl *ExceptionDecl = 0;
Sebastian Redlb219c902008-12-21 16:41:36 +00002669 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002670 ParsedAttributesWithRange Attributes(AttrFactory);
2671 MaybeParseCXX11Attributes(Attributes);
2672
John McCall084e83d2011-03-24 11:26:52 +00002673 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002674 DS.takeAttributesFrom(Attributes);
2675
Sebastian Redl54c04d42008-12-22 19:15:10 +00002676 if (ParseCXXTypeSpecifierSeq(DS))
2677 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002678
Sebastian Redlb219c902008-12-21 16:41:36 +00002679 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2680 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002681 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002682 } else
2683 ConsumeToken();
2684
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002685 T.consumeClose();
2686 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002687 return StmtError();
2688
2689 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002690 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redlb219c902008-12-21 16:41:36 +00002691
Alexis Hunt96d5c762009-11-21 08:43:09 +00002692 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002693 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002694 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002695 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002696
John McCallb268a282010-08-23 23:25:46 +00002697 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002698}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002699
2700void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002701 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002702 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002703 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002704
Douglas Gregor43edb322011-10-24 22:31:10 +00002705 // Handle dependent statements by parsing the braces as a compound statement.
2706 // This is not the same behavior as Visual C++, which don't treat this as a
2707 // compound statement, but for Clang's type checking we can't have anything
2708 // inside these braces escaping to the surrounding code.
2709 if (Result.Behavior == IEB_Dependent) {
2710 if (!Tok.is(tok::l_brace)) {
Alp Tokerec543272013-12-24 09:48:30 +00002711 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smithc202b282012-04-14 00:33:13 +00002712 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002713 }
Richard Smithc202b282012-04-14 00:33:13 +00002714
2715 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002716 if (Compound.isInvalid())
2717 return;
Richard Smithc202b282012-04-14 00:33:13 +00002718
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002719 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2720 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002721 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002722 Result.Name,
2723 Compound.get());
2724 if (DepResult.isUsable())
2725 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002726 return;
2727 }
Richard Smithc202b282012-04-14 00:33:13 +00002728
Douglas Gregor43edb322011-10-24 22:31:10 +00002729 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2730 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00002731 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002732 return;
2733 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002734
Douglas Gregor43edb322011-10-24 22:31:10 +00002735 switch (Result.Behavior) {
2736 case IEB_Parse:
2737 // Parse the statements below.
2738 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002739
Douglas Gregor43edb322011-10-24 22:31:10 +00002740 case IEB_Dependent:
2741 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002742
Douglas Gregor43edb322011-10-24 22:31:10 +00002743 case IEB_Skip:
2744 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002745 return;
2746 }
2747
2748 // Condition is true, parse the statements.
2749 while (Tok.isNot(tok::r_brace)) {
2750 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2751 if (R.isUsable())
2752 Stmts.push_back(R.release());
2753 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002754 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002755}