blob: eafe334891965862a7b4cf646d2db345fb5894fd [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"
Nico Weber303ff602014-04-23 22:07:21 +000030#include "llvm/MC/MCInstrInfo.h"
John McCallf413f5e2013-05-03 00:10:13 +000031#include "llvm/MC/MCObjectFileInfo.h"
32#include "llvm/MC/MCParser/MCAsmParser.h"
33#include "llvm/MC/MCRegisterInfo.h"
34#include "llvm/MC/MCStreamer.h"
35#include "llvm/MC/MCSubtargetInfo.h"
36#include "llvm/MC/MCTargetAsmParser.h"
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +000037#include "llvm/MC/MCTargetOptions.h"
John McCallf413f5e2013-05-03 00:10:13 +000038#include "llvm/Support/SourceMgr.h"
39#include "llvm/Support/TargetRegistry.h"
40#include "llvm/Support/TargetSelect.h"
Chris Lattner0ccd51e2006-08-09 05:47:47 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
44// C99 6.8: Statements and Blocks.
45//===----------------------------------------------------------------------===//
46
Richard Smith426a47b2013-10-28 22:04:30 +000047/// \brief Parse a standalone statement (for instance, as the body of an 'if',
48/// 'while', or 'for').
49StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) {
50 StmtResult Res;
51
52 // We may get back a null statement if we found a #pragma. Keep going until
53 // we get an actual statement.
54 do {
55 StmtVector Stmts;
56 Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
57 } while (!Res.isInvalid() && !Res.get());
58
59 return Res;
60}
61
Chris Lattner0ccd51e2006-08-09 05:47:47 +000062/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
63/// StatementOrDeclaration:
64/// statement
65/// declaration
66///
67/// statement:
68/// labeled-statement
69/// compound-statement
70/// expression-statement
71/// selection-statement
72/// iteration-statement
73/// jump-statement
Argyrios Kyrtzidisdee82912008-09-07 18:58:01 +000074/// [C++] declaration-statement
Sebastian Redlb219c902008-12-21 16:41:36 +000075/// [C++] try-block
John Wiegley1c0675e2011-04-28 01:08:34 +000076/// [MS] seh-try-block
Fariborz Jahanian90814572007-10-04 20:19:06 +000077/// [OBC] objc-throw-statement
78/// [OBC] objc-try-catch-statement
Fariborz Jahanianf89ca382008-01-29 18:21:32 +000079/// [OBC] objc-synchronized-statement
Chris Lattner0116c472006-08-15 06:03:28 +000080/// [GNU] asm-statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +000081/// [OMP] openmp-construct [TODO]
82///
83/// labeled-statement:
84/// identifier ':' statement
85/// 'case' constant-expression ':' statement
86/// 'default' ':' statement
87///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000088/// selection-statement:
89/// if-statement
90/// switch-statement
91///
92/// iteration-statement:
93/// while-statement
94/// do-statement
95/// for-statement
96///
Chris Lattner9075bd72006-08-10 04:59:57 +000097/// expression-statement:
98/// expression[opt] ';'
99///
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000100/// jump-statement:
101/// 'goto' identifier ';'
102/// 'continue' ';'
103/// 'break' ';'
104/// 'return' expression[opt] ';'
Chris Lattner503fadc2006-08-10 05:45:44 +0000105/// [GNU] 'goto' '*' expression ';'
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000106///
Fariborz Jahanian90814572007-10-04 20:19:06 +0000107/// [OBC] objc-throw-statement:
108/// [OBC] '@' 'throw' expression ';'
Mike Stump11289f42009-09-09 15:08:12 +0000109/// [OBC] '@' 'throw' ';'
110///
John McCalldadc5752010-08-24 06:29:42 +0000111StmtResult
Nico Weber3cef1082011-12-22 23:26:17 +0000112Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
113 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000114
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +0000115 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000116
Richard Smithc202b282012-04-14 00:33:13 +0000117 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000118 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
Richard Smithc202b282012-04-14 00:33:13 +0000119
120 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
121 OnlyStatement, TrailingElseLoc, Attrs);
122
123 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
124 "attributes on empty statement");
125
126 if (Attrs.empty() || Res.isInvalid())
127 return Res;
128
129 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
130}
131
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000132namespace {
133class StatementFilterCCC : public CorrectionCandidateCallback {
134public:
135 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
136 WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) ||
137 nextTok.is(tok::identifier) || nextTok.is(tok::star) ||
138 nextTok.is(tok::amp) || nextTok.is(tok::l_square);
139 WantExpressionKeywords = nextTok.is(tok::l_paren) ||
140 nextTok.is(tok::identifier) ||
141 nextTok.is(tok::arrow) || nextTok.is(tok::period);
142 WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) ||
143 nextTok.is(tok::identifier) ||
144 nextTok.is(tok::l_brace);
145 WantCXXNamedCasts = false;
146 }
147
Craig Topper2b07f022014-03-12 05:09:18 +0000148 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000149 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
Kaelyn Uhrain07e62722013-10-01 22:00:28 +0000150 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain46b6cdc2013-09-27 19:40:16 +0000151 if (NextToken.is(tok::equal))
152 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain30943ce2013-09-27 23:54:23 +0000153 if (NextToken.is(tok::period) &&
154 candidate.getCorrectionDeclAs<NamespaceDecl>())
155 return false;
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000156 return CorrectionCandidateCallback::ValidateCandidate(candidate);
157 }
158
159private:
160 Token NextToken;
161};
162}
163
Richard Smithc202b282012-04-14 00:33:13 +0000164StmtResult
165Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
166 bool OnlyStatement, SourceLocation *TrailingElseLoc,
167 ParsedAttributesWithRange &Attrs) {
168 const char *SemiError = 0;
169 StmtResult Res;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000170
Chris Lattner503fadc2006-08-10 05:45:44 +0000171 // Cases in this switch statement should fall through if the parser expects
172 // the token to end in a semicolon (in which case SemiError should be set),
173 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000174Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000175 tok::TokenKind Kind = Tok.getKind();
176 SourceLocation AtLoc;
177 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000178 case tok::at: // May be a @try or @throw statement
179 {
Richard Smithc202b282012-04-14 00:33:13 +0000180 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000181 AtLoc = ConsumeToken(); // consume @
Sebastian Redlbab9a4b2008-12-11 20:12:42 +0000182 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000183 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000184
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000185 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000186 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000187 cutOffParsing();
188 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000189
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000190 case tok::identifier: {
191 Token Next = NextToken();
192 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000193 // identifier ':' statement
Richard Smithc202b282012-04-14 00:33:13 +0000194 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000195 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000196
Richard Smith4f605af2012-08-18 00:55:03 +0000197 // Look up the identifier, and typo-correct it to a keyword if it's not
198 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000199 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000200 // Try to limit which sets of keywords should be included in typo
201 // correction based on what the next token is.
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000202 StatementFilterCCC Validator(Next);
203 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
Richard Smith4f605af2012-08-18 00:55:03 +0000204 == ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000205 // Handle errors here by skipping up to the next semicolon or '}', and
206 // eat the semicolon if that's what stopped us.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000207 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000208 if (Tok.is(tok::semi))
209 ConsumeToken();
210 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000211 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000212
Richard Smith4f605af2012-08-18 00:55:03 +0000213 // If the identifier was typo-corrected, try again.
214 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000215 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000216 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000217
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000218 // Fall through
219 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000220
Chris Lattner803802d2009-03-24 17:04:48 +0000221 default: {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000222 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000223 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek5eec2b02010-11-10 05:59:39 +0000224 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000225 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000226 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000227 }
228
229 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000230 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000231 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000232 }
Mike Stump11289f42009-09-09 15:08:12 +0000233
Richard Smithc202b282012-04-14 00:33:13 +0000234 return ParseExprStatement();
Chris Lattner803802d2009-03-24 17:04:48 +0000235 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000236
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000237 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000238 return ParseCaseStatement();
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000239 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000240 return ParseDefaultStatement();
Sebastian Redl042ad952008-12-11 19:30:53 +0000241
Chris Lattner9075bd72006-08-10 04:59:57 +0000242 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000243 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000244 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000245 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
246 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000247 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000248
Chris Lattner9075bd72006-08-10 04:59:57 +0000249 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000250 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000251 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000252 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000253
Chris Lattner9075bd72006-08-10 04:59:57 +0000254 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000255 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000256 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000257 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000258 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000259 break;
260 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000261 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000262
263 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000264 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000265 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000266 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000267 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000268 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000269 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000270 break;
271 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000272 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000273 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000274 break;
275 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000276 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000277 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000278 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000279
Sebastian Redlb219c902008-12-21 16:41:36 +0000280 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000281 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000282 bool msAsm = false;
283 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000284 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000285 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000286 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000287 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000288 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000289
Sebastian Redlb219c902008-12-21 16:41:36 +0000290 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000291 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000292
293 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000294 ProhibitAttributes(Attrs); // TODO: is it correct?
295 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000296
297 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000298 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000299 HandlePragmaVisibility();
300 return StmtEmpty();
301
302 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000303 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000304 HandlePragmaPack();
305 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000306
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000307 case tok::annot_pragma_msstruct:
308 ProhibitAttributes(Attrs);
309 HandlePragmaMSStruct();
310 return StmtEmpty();
311
Eli Friedmanae8ee252012-10-08 23:52:38 +0000312 case tok::annot_pragma_align:
313 ProhibitAttributes(Attrs);
314 HandlePragmaAlign();
315 return StmtEmpty();
316
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000317 case tok::annot_pragma_weak:
318 ProhibitAttributes(Attrs);
319 HandlePragmaWeak();
320 return StmtEmpty();
321
322 case tok::annot_pragma_weakalias:
323 ProhibitAttributes(Attrs);
324 HandlePragmaWeakAlias();
325 return StmtEmpty();
326
327 case tok::annot_pragma_redefine_extname:
328 ProhibitAttributes(Attrs);
329 HandlePragmaRedefineExtname();
330 return StmtEmpty();
331
Eli Friedman68be1642012-10-04 02:36:51 +0000332 case tok::annot_pragma_fp_contract:
Richard Smithca9b0b62013-11-15 21:10:54 +0000333 ProhibitAttributes(Attrs);
Lang Hamesa930e712012-10-21 01:10:01 +0000334 Diag(Tok, diag::err_pragma_fp_contract_scope);
335 ConsumeToken();
336 return StmtError();
337
Eli Friedman68be1642012-10-04 02:36:51 +0000338 case tok::annot_pragma_opencl_extension:
339 ProhibitAttributes(Attrs);
340 HandlePragmaOpenCLExtension();
341 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000342
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000343 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000344 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000345 return HandlePragmaCaptured();
346
Alexey Bataeva769e072013-03-22 06:34:35 +0000347 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000348 ProhibitAttributes(Attrs);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000349 return ParseOpenMPDeclarativeOrExecutableDirective();
350
David Majnemer4bb09802014-02-10 19:50:15 +0000351 case tok::annot_pragma_ms_pointers_to_members:
352 ProhibitAttributes(Attrs);
353 HandlePragmaMSPointersToMembers();
354 return StmtEmpty();
355
Warren Huntc3b18962014-04-08 22:30:47 +0000356 case tok::annot_pragma_ms_pragma:
357 ProhibitAttributes(Attrs);
358 HandlePragmaMSPragma();
359 return StmtEmpty();
Sebastian Redlb219c902008-12-21 16:41:36 +0000360 }
361
Chris Lattner503fadc2006-08-10 05:45:44 +0000362 // If we reached this code, the statement must end in a semicolon.
Alp Toker97650562014-01-10 11:19:30 +0000363 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000364 // If the result was valid, then we do want to diagnose this. Use
365 // ExpectAndConsume to emit the diagnostic, even though we know it won't
366 // succeed.
367 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000368 // Skip until we see a } or ;, but don't eat it.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000369 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner503fadc2006-08-10 05:45:44 +0000370 }
Mike Stump11289f42009-09-09 15:08:12 +0000371
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000372 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000373}
374
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000375/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000376StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000377 // If a case keyword is missing, this is where it should be inserted.
378 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000379
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000380 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000381 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000382 if (Expr.isInvalid()) {
383 // If the expression is invalid, skip ahead to the next semicolon or '}'.
384 // Not doing this opens us up to the possibility of infinite loops if
385 // ParseExpression does not consume any tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000386 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000387 if (Tok.is(tok::semi))
388 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000389 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000390 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000391
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000392 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
393 Actions.CheckCaseExpression(Expr.get())) {
394 // If a constant expression is followed by a colon inside a switch block,
395 // suggest a missing case keyword.
396 Diag(OldToken, diag::err_expected_case_before_expression)
397 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000398
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000399 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000400 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000401 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000402
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000403 // Otherwise, eat the semicolon.
404 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000405 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000406}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000407
Richard Smithc202b282012-04-14 00:33:13 +0000408StmtResult Parser::ParseSEHTryBlock() {
John Wiegley1c0675e2011-04-28 01:08:34 +0000409 assert(Tok.is(tok::kw___try) && "Expected '__try'");
410 SourceLocation Loc = ConsumeToken();
411 return ParseSEHTryBlockCommon(Loc);
412}
413
414/// ParseSEHTryBlockCommon
415///
416/// seh-try-block:
417/// '__try' compound-statement seh-handler
418///
419/// seh-handler:
420/// seh-except-block
421/// seh-finally-block
422///
423StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
424 if(Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000425 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley1c0675e2011-04-28 01:08:34 +0000426
Joao Matos566359c2012-09-04 17:49:35 +0000427 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000428 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000429 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000430
431 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000432 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000433 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000434 SourceLocation Loc = ConsumeToken();
435 Handler = ParseSEHExceptBlock(Loc);
436 } else if (Tok.is(tok::kw___finally)) {
437 SourceLocation Loc = ConsumeToken();
438 Handler = ParseSEHFinallyBlock(Loc);
439 } else {
440 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
441 }
442
443 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000444 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000445
446 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
447 TryLoc,
448 TryBlock.take(),
449 Handler.take());
450}
451
452/// ParseSEHExceptBlock - Handle __except
453///
454/// seh-except-block:
455/// '__except' '(' seh-filter-expression ')' compound-statement
456///
457StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
458 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
459 raii2(Ident___exception_code, false),
460 raii3(Ident_GetExceptionCode, false);
461
Alp Toker383d2c42014-01-01 03:08:43 +0000462 if (ExpectAndConsume(tok::l_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000463 return StmtError();
464
465 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
466
David Blaikiebbafb8a2012-03-11 07:00:24 +0000467 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000468 Ident__exception_info->setIsPoisoned(false);
469 Ident___exception_info->setIsPoisoned(false);
470 Ident_GetExceptionInfo->setIsPoisoned(false);
471 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000472 ExprResult FilterExpr(ParseExpression());
Francois Pichetbfaf4772011-04-28 03:14:31 +0000473
David Blaikiebbafb8a2012-03-11 07:00:24 +0000474 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000475 Ident__exception_info->setIsPoisoned(true);
476 Ident___exception_info->setIsPoisoned(true);
477 Ident_GetExceptionInfo->setIsPoisoned(true);
478 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000479
480 if(FilterExpr.isInvalid())
481 return StmtError();
482
Alp Toker383d2c42014-01-01 03:08:43 +0000483 if (ExpectAndConsume(tok::r_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000484 return StmtError();
485
Richard Smithc202b282012-04-14 00:33:13 +0000486 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000487
488 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000489 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000490
491 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
492}
493
494/// ParseSEHFinallyBlock - Handle __finally
495///
496/// seh-finally-block:
497/// '__finally' compound-statement
498///
499StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
500 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
501 raii2(Ident___abnormal_termination, false),
502 raii3(Ident_AbnormalTermination, false);
503
Richard Smithc202b282012-04-14 00:33:13 +0000504 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000505 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000506 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000507
508 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000509}
510
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000511/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000512///
513/// labeled-statement:
514/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000515/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000516///
Richard Smithc202b282012-04-14 00:33:13 +0000517StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000518 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
519 "Not an identifier!");
520
521 Token IdentTok = Tok; // Save the whole token.
522 ConsumeToken(); // eat the identifier.
523
524 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000525
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000526 // identifier ':' statement
527 SourceLocation ColonLoc = ConsumeToken();
528
Richard Smitha3e01cf2013-11-15 22:45:29 +0000529 // Read label attributes, if present.
530 StmtResult SubStmt;
531 if (Tok.is(tok::kw___attribute)) {
532 ParsedAttributesWithRange TempAttrs(AttrFactory);
533 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000534
Richard Smitha3e01cf2013-11-15 22:45:29 +0000535 // In C++, GNU attributes only apply to the label if they are followed by a
536 // semicolon, to disambiguate label attributes from attributes on a labeled
537 // declaration.
538 //
539 // This doesn't quite match what GCC does; if the attribute list is empty
540 // and followed by a semicolon, GCC will reject (it appears to parse the
541 // attributes as part of a statement in that case). That looks like a bug.
542 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
543 attrs.takeAllFrom(TempAttrs);
544 else if (isDeclarationStatement()) {
545 StmtVector Stmts;
546 // FIXME: We should do this whether or not we have a declaration
547 // statement, but that doesn't work correctly (because ProhibitAttributes
548 // can't handle GNU attributes), so only call it in the one case where
549 // GNU attributes are allowed.
550 SubStmt = ParseStatementOrDeclarationAfterAttributes(
551 Stmts, /*OnlyStmts*/ true, 0, TempAttrs);
552 if (!TempAttrs.empty() && !SubStmt.isInvalid())
553 SubStmt = Actions.ProcessStmtAttributes(
554 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
555 } else {
Alp Toker383d2c42014-01-01 03:08:43 +0000556 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smitha3e01cf2013-11-15 22:45:29 +0000557 }
558 }
559
560 // If we've not parsed a statement yet, parse one now.
561 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
562 SubStmt = ParseStatement();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000563
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000564 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000565 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000566 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000567
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000568 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
569 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000570 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000571 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000572 attrs.clear();
573 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000574
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000575 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
576 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000577}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000578
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000579/// ParseCaseStatement
580/// labeled-statement:
581/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000582/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000583///
Richard Smithc202b282012-04-14 00:33:13 +0000584StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000585 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattner34a22092009-03-04 04:23:07 +0000587 // It is very very common for code to contain many case statements recursively
588 // nested, as in (but usually without indentation):
589 // case 1:
590 // case 2:
591 // case 3:
592 // case 4:
593 // case 5: etc.
594 //
595 // Parsing this naively works, but is both inefficient and can cause us to run
596 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000597 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000598 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smitha3e01cf2013-11-15 22:45:29 +0000599 // weirdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000600
Chris Lattner34a22092009-03-04 04:23:07 +0000601 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
602 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000603 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000604
Chris Lattner34a22092009-03-04 04:23:07 +0000605 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
606 // gets updated each time a new case is parsed, and whose body is unset so
607 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieu3481fcd2011-09-09 02:16:15 +0000608 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattner34a22092009-03-04 04:23:07 +0000610 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000611 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000612 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000613 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
614 ConsumeToken(); // eat the 'case'.
Mike Stump11289f42009-09-09 15:08:12 +0000615
Douglas Gregord328d572009-09-21 18:10:23 +0000616 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000617 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000618 cutOffParsing();
619 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000620 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000621
Chris Lattner125c0ee2009-12-10 00:38:54 +0000622 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
623 /// Disable this form of error recovery while we're parsing the case
624 /// expression.
625 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000626
Richard Trieu2c850c02011-04-21 21:44:26 +0000627 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
628 MissingCase = false;
Chris Lattner34a22092009-03-04 04:23:07 +0000629 if (LHS.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000630 SkipUntil(tok::colon, StopAtSemi);
Sebastian Redl042ad952008-12-11 19:30:53 +0000631 return StmtError();
Chris Lattner476c3ad2006-08-13 22:09:58 +0000632 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000633
Chris Lattner34a22092009-03-04 04:23:07 +0000634 // GNU case range extension.
635 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000636 ExprResult RHS;
Alp Tokerec543272013-12-24 09:48:30 +0000637 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
638 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Chris Lattner34a22092009-03-04 04:23:07 +0000639 RHS = ParseConstantExpression();
640 if (RHS.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000641 SkipUntil(tok::colon, StopAtSemi);
Chris Lattner34a22092009-03-04 04:23:07 +0000642 return StmtError();
643 }
644 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000645
Chris Lattner125c0ee2009-12-10 00:38:54 +0000646 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000647
Alp Tokerec543272013-12-24 09:48:30 +0000648 if (TryConsumeToken(tok::colon, ColonLoc)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000649 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
650 TryConsumeToken(tok::coloncolon, ColonLoc)) {
651 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Alp Tokerec543272013-12-24 09:48:30 +0000652 Diag(ColonLoc, diag::err_expected_after)
653 << "'case'" << tok::colon
654 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000655 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000656 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000657 Diag(ExpectedLoc, diag::err_expected_after)
658 << "'case'" << tok::colon
659 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000660 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000661 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000662
John McCalldadc5752010-08-24 06:29:42 +0000663 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000664 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
665 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner34a22092009-03-04 04:23:07 +0000667 // If we had a sema error parsing this case, then just ignore it and
668 // continue parsing the sub-stmt.
669 if (Case.isInvalid()) {
670 if (TopLevelCase.isInvalid()) // No parsed case stmts.
671 return ParseStatement();
672 // Otherwise, just don't add it as a nested case.
673 } else {
674 // If this is the first case statement we parsed, it becomes TopLevelCase.
675 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000676 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000677 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000678 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000679 else
John McCallb268a282010-08-23 23:25:46 +0000680 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000681 DeepestParsedCaseStmt = NextDeepest;
682 }
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattner34a22092009-03-04 04:23:07 +0000684 // Handle all case statements.
685 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000686
Chris Lattner34a22092009-03-04 04:23:07 +0000687 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump11289f42009-09-09 15:08:12 +0000688
Chris Lattner34a22092009-03-04 04:23:07 +0000689 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000690 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner34a22092009-03-04 04:23:07 +0000692 if (Tok.isNot(tok::r_brace)) {
693 SubStmt = ParseStatement();
694 } else {
695 // Nicely diagnose the common error "switch (X) { case 4: }", which is
696 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000697 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000698 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
699 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner34a22092009-03-04 04:23:07 +0000700 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000701 }
Mike Stump11289f42009-09-09 15:08:12 +0000702
Chris Lattner34a22092009-03-04 04:23:07 +0000703 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000704 if (SubStmt.isInvalid())
Chris Lattner34a22092009-03-04 04:23:07 +0000705 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner34a22092009-03-04 04:23:07 +0000707 // Install the body into the most deeply-nested case.
John McCallb268a282010-08-23 23:25:46 +0000708 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl042ad952008-12-11 19:30:53 +0000709
Chris Lattner34a22092009-03-04 04:23:07 +0000710 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000711 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000712}
713
714/// ParseDefaultStatement
715/// labeled-statement:
716/// 'default' ':' statement
717/// Note that this does not parse the 'statement' at the end.
718///
Richard Smithc202b282012-04-14 00:33:13 +0000719StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000720 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000721 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000722
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000723 SourceLocation ColonLoc;
Alp Tokerec543272013-12-24 09:48:30 +0000724 if (TryConsumeToken(tok::colon, ColonLoc)) {
Alp Tokerec543272013-12-24 09:48:30 +0000725 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
Alp Toker97650562014-01-10 11:19:30 +0000726 // Treat "default;" as a typo for "default:".
Alp Tokerec543272013-12-24 09:48:30 +0000727 Diag(ColonLoc, diag::err_expected_after)
728 << "'default'" << tok::colon
729 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000730 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000731 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000732 Diag(ExpectedLoc, diag::err_expected_after)
733 << "'default'" << tok::colon
734 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000735 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000736 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000737
Richard Smith1002d102012-02-17 01:35:32 +0000738 StmtResult SubStmt;
739
740 if (Tok.isNot(tok::r_brace)) {
741 SubStmt = ParseStatement();
742 } else {
743 // Diagnose the common error "switch (X) {... default: }", which is
744 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000745 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000746 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
747 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
748 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000749 }
750
Richard Smith1002d102012-02-17 01:35:32 +0000751 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000752 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000753 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000754
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000755 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000756 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000757}
758
Richard Smithc202b282012-04-14 00:33:13 +0000759StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
760 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000761}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000762
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000763/// ParseCompoundStatement - Parse a "{}" block.
764///
765/// compound-statement: [C99 6.8.2]
766/// { block-item-list[opt] }
767/// [GNU] { label-declarations block-item-list } [TODO]
768///
769/// block-item-list:
770/// block-item
771/// block-item-list block-item
772///
773/// block-item:
774/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000775/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000776/// statement
777/// [OMP] openmp-directive [TODO]
778///
779/// [GNU] label-declarations:
780/// [GNU] label-declaration
781/// [GNU] label-declarations label-declaration
782///
783/// [GNU] label-declaration:
784/// [GNU] '__label__' identifier-list ';'
785///
786/// [OMP] openmp-directive: [TODO]
787/// [OMP] barrier-directive
788/// [OMP] flush-directive
Chris Lattner30f910e2006-10-16 05:52:41 +0000789///
Richard Smithc202b282012-04-14 00:33:13 +0000790StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000791 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000792 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000793
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000794 // Enter a scope to hold everything within the compound stmt. Compound
795 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000796 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000797
798 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000799 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000800}
801
Lang Hames2954cea2012-11-03 22:29:05 +0000802/// Parse any pragmas at the start of the compound expression. We handle these
803/// separately since some pragmas (FP_CONTRACT) must appear before any C
804/// statement in the compound, but may be intermingled with other pragmas.
805void Parser::ParseCompoundStatementLeadingPragmas() {
806 bool checkForPragmas = true;
807 while (checkForPragmas) {
808 switch (Tok.getKind()) {
809 case tok::annot_pragma_vis:
810 HandlePragmaVisibility();
811 break;
812 case tok::annot_pragma_pack:
813 HandlePragmaPack();
814 break;
815 case tok::annot_pragma_msstruct:
816 HandlePragmaMSStruct();
817 break;
818 case tok::annot_pragma_align:
819 HandlePragmaAlign();
820 break;
821 case tok::annot_pragma_weak:
822 HandlePragmaWeak();
823 break;
824 case tok::annot_pragma_weakalias:
825 HandlePragmaWeakAlias();
826 break;
827 case tok::annot_pragma_redefine_extname:
828 HandlePragmaRedefineExtname();
829 break;
830 case tok::annot_pragma_opencl_extension:
831 HandlePragmaOpenCLExtension();
832 break;
833 case tok::annot_pragma_fp_contract:
834 HandlePragmaFPContract();
835 break;
David Majnemer4bb09802014-02-10 19:50:15 +0000836 case tok::annot_pragma_ms_pointers_to_members:
837 HandlePragmaMSPointersToMembers();
838 break;
Warren Huntc3b18962014-04-08 22:30:47 +0000839 case tok::annot_pragma_ms_pragma:
840 HandlePragmaMSPragma();
841 break;
Lang Hames2954cea2012-11-03 22:29:05 +0000842 default:
843 checkForPragmas = false;
844 break;
845 }
846 }
847
848}
849
Chris Lattnerf2978802007-01-21 06:52:16 +0000850/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000851/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000852/// consume the '}' at the end of the block. It does not manipulate the scope
853/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000854StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000855 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000856 Tok.getLocation(),
857 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000858
859 // Record the state of the FP_CONTRACT pragma, restore on leaving the
860 // compound statement.
861 Sema::FPContractStateRAII SaveFPContractState(Actions);
862
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000863 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000864 BalancedDelimiterTracker T(*this, tok::l_brace);
865 if (T.consumeOpen())
866 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000867
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000868 Sema::CompoundScopeRAII CompoundScope(Actions);
869
Lang Hames2954cea2012-11-03 22:29:05 +0000870 // Parse any pragmas at the beginning of the compound statement.
871 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000872
Lang Hames2954cea2012-11-03 22:29:05 +0000873 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000874
Chris Lattner43e7f312011-02-18 02:08:43 +0000875 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
876 // only allowed at the start of a compound stmt regardless of the language.
877 while (Tok.is(tok::kw___label__)) {
878 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000879
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000880 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000881 while (1) {
882 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +0000883 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner43e7f312011-02-18 02:08:43 +0000884 break;
885 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000886
Chris Lattner43e7f312011-02-18 02:08:43 +0000887 IdentifierInfo *II = Tok.getIdentifierInfo();
888 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000889 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000890
Alp Tokerec543272013-12-24 09:48:30 +0000891 if (!TryConsumeToken(tok::comma))
Chris Lattner43e7f312011-02-18 02:08:43 +0000892 break;
Chris Lattner43e7f312011-02-18 02:08:43 +0000893 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000894
John McCall084e83d2011-03-24 11:26:52 +0000895 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000896 DeclGroupPtrTy Res =
897 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000898 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000899
Chris Lattner02f1b612012-04-28 16:12:17 +0000900 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000901 if (R.isUsable())
902 Stmts.push_back(R.release());
903 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000904
Richard Smith34f30512013-11-23 04:06:09 +0000905 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000906 if (Tok.is(tok::annot_pragma_unused)) {
907 HandlePragmaUnused();
908 continue;
909 }
910
David Blaikiebbafb8a2012-03-11 07:00:24 +0000911 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet4a7de3e2011-05-06 20:48:22 +0000912 Tok.is(tok::kw___if_not_exists))) {
913 ParseMicrosoftIfExistsStatement(Stmts);
914 continue;
915 }
916
John McCalldadc5752010-08-24 06:29:42 +0000917 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000918 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000919 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000920 } else {
921 // __extension__ can start declarations and it can also be a unary
922 // operator for expressions. Consume multiple __extension__ markers here
923 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000924 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000925 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000926 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000927 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000928
John McCall084e83d2011-03-24 11:26:52 +0000929 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000930 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000931
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000932 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +0000933 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +0000934 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +0000935 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +0000936 ExtensionRAIIObject O(Diags);
937
Chris Lattner49836b42009-04-02 04:16:50 +0000938 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000939 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
940 Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000941 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000942 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000943 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000944 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +0000945 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +0000946
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000947 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000948 SkipUntil(tok::semi);
949 continue;
950 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +0000951
Alexis Hunt96d5c762009-11-21 08:43:09 +0000952 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +0000953 // Eat the semicolon at the end of stmt and convert the expr into a
954 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000955 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000956 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000957 }
958 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000959
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000960 if (R.isUsable())
Sebastian Redld9f7b1c2008-12-10 00:02:53 +0000961 Stmts.push_back(R.release());
Chris Lattner30f910e2006-10-16 05:52:41 +0000962 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000963
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000964 SourceLocation CloseLoc = Tok.getLocation();
965
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000966 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +0000967 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000968 // Recover by creating a compound statement with what we parsed so far,
969 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +0000970 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +0000971
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000972 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000973 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000974}
Chris Lattnerc951dae2006-08-10 04:23:57 +0000975
Chris Lattnerc0081db2008-12-12 06:31:07 +0000976/// ParseParenExprOrCondition:
977/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +0000978/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +0000979///
980/// This function parses and performs error recovery on the specified condition
981/// or expression (depending on whether we're in C++ or C mode). This function
982/// goes out of its way to recover well. It returns true if there was a parser
983/// error (the right paren couldn't be found), which indicates that the caller
984/// should try to recover harder. It returns false if the condition is
985/// successfully parsed. Note that a successful parse can still have semantic
986/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +0000987bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +0000988 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +0000989 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000990 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000991 BalancedDelimiterTracker T(*this, tok::l_paren);
992 T.consumeOpen();
993
David Blaikiebbafb8a2012-03-11 07:00:24 +0000994 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +0000995 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000996 else {
997 ExprResult = ParseExpression();
John McCall48871652010-08-21 09:40:31 +0000998 DeclResult = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000999
Douglas Gregore60e41a2010-05-06 17:25:47 +00001000 // If required, convert to a boolean value.
1001 if (!ExprResult.isInvalid() && ConvertToBoolean)
1002 ExprResult
John McCallb268a282010-08-23 23:25:46 +00001003 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001004 }
Mike Stump11289f42009-09-09 15:08:12 +00001005
Chris Lattnerc0081db2008-12-12 06:31:07 +00001006 // If the parser was confused by the condition and we don't have a ')', try to
1007 // recover by skipping ahead to a semi and bailing out. If condexp is
1008 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +00001009 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +00001010 SkipUntil(tok::semi);
1011 // Skipping may have stopped if it found the containing ')'. If so, we can
1012 // continue parsing the if statement.
1013 if (Tok.isNot(tok::r_paren))
1014 return true;
1015 }
Mike Stump11289f42009-09-09 15:08:12 +00001016
Chris Lattnerc0081db2008-12-12 06:31:07 +00001017 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001018 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +00001019
Chris Lattner70d44982012-04-28 16:24:20 +00001020 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1021 // that all callers are looking for a statement after the condition, so ")"
1022 // isn't valid.
1023 while (Tok.is(tok::r_paren)) {
1024 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1025 << FixItHint::CreateRemoval(Tok.getLocation());
1026 ConsumeParen();
1027 }
Chad Rosier67055f52012-07-10 21:35:27 +00001028
Chris Lattnerc0081db2008-12-12 06:31:07 +00001029 return false;
1030}
1031
1032
Chris Lattnerc951dae2006-08-10 04:23:57 +00001033/// ParseIfStatement
1034/// if-statement: [C99 6.8.4.1]
1035/// 'if' '(' expression ')' statement
1036/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001037/// [C++] 'if' '(' condition ')' statement
1038/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +00001039///
Richard Smithc202b282012-04-14 00:33:13 +00001040StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001041 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001042 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +00001043
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001044 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001045 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +00001046 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +00001047 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +00001048 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001049
David Blaikiebbafb8a2012-03-11 07:00:24 +00001050 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001051
Chris Lattner2dd1b722007-08-26 23:08:06 +00001052 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1053 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001054 //
1055 // C++ 6.4p3:
1056 // A name introduced by a declaration in a condition is in scope from its
1057 // point of declaration until the end of the substatements controlled by the
1058 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001059 // C++ 3.3.2p4:
1060 // Names declared in the for-init-statement, and in the condition of if,
1061 // while, for, and switch statements are local to the if, while, for, or
1062 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001063 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001064 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001065
Chris Lattnerc951dae2006-08-10 04:23:57 +00001066 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001067 ExprResult CondExp;
John McCall48871652010-08-21 09:40:31 +00001068 Decl *CondVar = 0;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001069 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001070 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001071
David Blaikiea5696df2012-05-16 04:20:04 +00001072 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattner8fb26252007-08-22 05:28:50 +00001074 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001075 // there is no compound stmt. C90 does not have this clause. We only do this
1076 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001077 //
1078 // C++ 6.4p1:
1079 // The substatement in a selection-statement (each substatement, in the else
1080 // form of the if statement) implicitly defines a local scope.
1081 //
1082 // For C++ we create a scope for the condition and a new scope for
1083 // substatements because:
1084 // -When the 'then' scope exits, we want the condition declaration to still be
1085 // active for the 'else' scope too.
1086 // -Sema will detect name clashes by considering declarations of a
1087 // 'ControlScope' as part of its direct subscope.
1088 // -If we wanted the condition and substatement to be in the same scope, we
1089 // would have to notify ParseStatement not to create a new scope. It's
1090 // simpler to let it create a new scope.
1091 //
David Majnemer2206bf52014-03-05 08:57:59 +00001092 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001093
Chris Lattner5c5808a2007-10-29 05:08:52 +00001094 // Read the 'then' stmt.
1095 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001096
1097 SourceLocation InnerStatementTrailingElseLoc;
1098 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001099
Chris Lattner37e54f42007-08-22 05:16:28 +00001100 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001101 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001102
Chris Lattnerc951dae2006-08-10 04:23:57 +00001103 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001104 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001105 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001106 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001107
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001108 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001109 if (TrailingElseLoc)
1110 *TrailingElseLoc = Tok.getLocation();
1111
Chris Lattneraf635312006-10-16 06:06:51 +00001112 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001113 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001114
Chris Lattner8fb26252007-08-22 05:28:50 +00001115 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001116 // there is no compound stmt. C90 does not have this clause. We only do
1117 // this if the body isn't a compound statement to avoid push/pop in common
1118 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001119 //
1120 // C++ 6.4p1:
1121 // The substatement in a selection-statement (each substatement, in the else
1122 // form of the if statement) implicitly defines a local scope.
1123 //
David Majnemer2206bf52014-03-05 08:57:59 +00001124 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001125
Chris Lattner30f910e2006-10-16 05:52:41 +00001126 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001127
Chris Lattner37e54f42007-08-22 05:16:28 +00001128 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001129 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001130 } else if (Tok.is(tok::code_completion)) {
1131 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001132 cutOffParsing();
1133 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001134 } else if (InnerStatementTrailingElseLoc.isValid()) {
1135 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001136 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001137
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001138 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001139
Chris Lattner5c5808a2007-10-29 05:08:52 +00001140 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001141 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001142 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001143 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1144 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1145 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001146 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001147 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001148 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001149
Chris Lattner5c5808a2007-10-29 05:08:52 +00001150 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001151 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001152 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001153 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001154 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001155
John McCallb268a282010-08-23 23:25:46 +00001156 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001157 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001158}
1159
Chris Lattner9075bd72006-08-10 04:59:57 +00001160/// ParseSwitchStatement
1161/// switch-statement:
1162/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001163/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001164StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001165 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001166 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001167
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001168 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001169 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001170 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001171 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001172 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001173
David Blaikiebbafb8a2012-03-11 07:00:24 +00001174 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001175
Chris Lattner2dd1b722007-08-26 23:08:06 +00001176 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1177 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001178 //
1179 // C++ 6.4p3:
1180 // A name introduced by a declaration in a condition is in scope from its
1181 // point of declaration until the end of the substatements controlled by the
1182 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001183 // C++ 3.3.2p4:
1184 // Names declared in the for-init-statement, and in the condition of if,
1185 // while, for, and switch statements are local to the if, while, for, or
1186 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001187 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001188 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001189 if (C99orCXX)
1190 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001191 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001192
Chris Lattner9075bd72006-08-10 04:59:57 +00001193 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001194 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001195 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001196 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001197 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001198
John McCalldadc5752010-08-24 06:29:42 +00001199 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001200 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001201
Douglas Gregore60e41a2010-05-06 17:25:47 +00001202 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001203 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001204 // FIXME: This is not optimal recovery, but parsing the body is more
1205 // dangerous due to the presence of case and default statements, which
1206 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001207 if (Tok.is(tok::l_brace)) {
1208 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001209 SkipUntil(tok::r_brace);
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001210 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001211 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001212 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001213 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001214
Chris Lattner8fb26252007-08-22 05:28:50 +00001215 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001216 // there is no compound stmt. C90 does not have this clause. We only do this
1217 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001218 //
1219 // C++ 6.4p1:
1220 // The substatement in a selection-statement (each substatement, in the else
1221 // form of the if statement) implicitly defines a local scope.
1222 //
1223 // See comments in ParseIfStatement for why we create a scope for the
1224 // condition and a new scope for substatement in C++.
1225 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001226 getCurScope()->AddFlags(Scope::BreakScope);
David Majnemer2206bf52014-03-05 08:57:59 +00001227 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001228
Chris Lattner9075bd72006-08-10 04:59:57 +00001229 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001230 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001231
Chris Lattner8fd2d012010-01-24 01:50:29 +00001232 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001233 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001234 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001235
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001236 if (Body.isInvalid()) {
Chris Lattner8fd2d012010-01-24 01:50:29 +00001237 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001238
1239 // Put the synthesized null statement on the same line as the end of switch
1240 // condition.
1241 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1242 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1243 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001244
John McCallb268a282010-08-23 23:25:46 +00001245 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001246}
1247
1248/// ParseWhileStatement
1249/// while-statement: [C99 6.8.5.1]
1250/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001251/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001252StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001253 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001254 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001255 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001256
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001257 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001258 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001259 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001260 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001261 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001262
David Blaikiebbafb8a2012-03-11 07:00:24 +00001263 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001264
Chris Lattner2dd1b722007-08-26 23:08:06 +00001265 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1266 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001267 //
1268 // C++ 6.4p3:
1269 // A name introduced by a declaration in a condition is in scope from its
1270 // point of declaration until the end of the substatements controlled by the
1271 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001272 // C++ 3.3.2p4:
1273 // Names declared in the for-init-statement, and in the condition of if,
1274 // while, for, and switch statements are local to the if, while, for, or
1275 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001276 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001277 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001278 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001279 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1280 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001281 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001282 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1283 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001284
Chris Lattner9075bd72006-08-10 04:59:57 +00001285 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001286 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001287 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001288 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001289 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001290
David Blaikiea5696df2012-05-16 04:20:04 +00001291 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001292
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001293 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001294 // there is no compound stmt. C90 does not have this clause. We only do this
1295 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001296 //
1297 // C++ 6.5p2:
1298 // The substatement in an iteration-statement implicitly defines a local scope
1299 // which is entered and exited each time through the loop.
1300 //
1301 // See comments in ParseIfStatement for why we create a scope for the
1302 // condition and a new scope for substatement in C++.
1303 //
David Majnemer2206bf52014-03-05 08:57:59 +00001304 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001305
Chris Lattner9075bd72006-08-10 04:59:57 +00001306 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001307 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001308
Chris Lattner8fb26252007-08-22 05:28:50 +00001309 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001310 InnerScope.Exit();
1311 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001312
John McCall48871652010-08-21 09:40:31 +00001313 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001314 return StmtError();
1315
John McCallb268a282010-08-23 23:25:46 +00001316 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001317}
1318
1319/// ParseDoStatement
1320/// do-statement: [C99 6.8.5.2]
1321/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001322/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001323StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001324 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001325 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001326
Chris Lattner2dd1b722007-08-26 23:08:06 +00001327 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1328 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001329 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001330 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001331 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001332 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001333 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001334
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001335 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001336
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001337 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001338 // there is no compound stmt. C90 does not have this clause. We only do this
1339 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001340 //
1341 // C++ 6.5p2:
1342 // The substatement in an iteration-statement implicitly defines a local scope
1343 // which is entered and exited each time through the loop.
1344 //
David Majnemer2206bf52014-03-05 08:57:59 +00001345 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1346 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001347
Chris Lattner9075bd72006-08-10 04:59:57 +00001348 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001349 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001350
Chris Lattner8fb26252007-08-22 05:28:50 +00001351 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001352 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001353
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001354 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001355 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001356 Diag(Tok, diag::err_expected_while);
Alp Tokerec543272013-12-24 09:48:30 +00001357 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001358 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner0046de12008-11-13 18:52:53 +00001359 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001360 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001361 }
Chris Lattneraf635312006-10-16 06:06:51 +00001362 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001363
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001364 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001365 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001366 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001367 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001368 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001369
Richard Smithc2c8bb82013-10-15 01:34:54 +00001370 // Parse the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001371 BalancedDelimiterTracker T(*this, tok::l_paren);
1372 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001373
Richard Smithc2c8bb82013-10-15 01:34:54 +00001374 // A do-while expression is not a condition, so can't have attributes.
1375 DiagnoseAndSkipCXX11Attributes();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001376
John McCalldadc5752010-08-24 06:29:42 +00001377 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001378 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001379 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001380
Sebastian Redlb62406f2008-12-11 19:48:14 +00001381 if (Cond.isInvalid() || Body.isInvalid())
1382 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001383
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001384 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1385 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001386}
1387
1388/// ParseForStatement
1389/// for-statement: [C99 6.8.5.3]
1390/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1391/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001392/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1393/// [C++] statement
Richard Smith02e85f32011-04-14 22:09:26 +00001394/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001395/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1396/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001397///
1398/// [C++] for-init-statement:
1399/// [C++] expression-statement
1400/// [C++] simple-declaration
1401///
Richard Smith02e85f32011-04-14 22:09:26 +00001402/// [C++0x] for-range-declaration:
1403/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1404/// [C++0x] for-range-initializer:
1405/// [C++0x] expression
1406/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001407StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001408 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001409 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001410
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001411 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001412 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001413 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001414 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001415 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001416
Chad Rosier67055f52012-07-10 21:35:27 +00001417 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1418 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001419
Chris Lattner2dd1b722007-08-26 23:08:06 +00001420 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1421 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001422 //
1423 // C++ 6.4p3:
1424 // A name introduced by a declaration in a condition is in scope from its
1425 // point of declaration until the end of the substatements controlled by the
1426 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001427 // C++ 3.3.2p4:
1428 // Names declared in the for-init-statement, and in the condition of if,
1429 // while, for, and switch statements are local to the if, while, for, or
1430 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001431 // C++ 6.5.3p1:
1432 // Names declared in the for-init-statement are in the same declarative-region
1433 // as those declared in the condition.
1434 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001435 unsigned ScopeFlags = 0;
Chris Lattner934074c2009-04-22 00:54:41 +00001436 if (C99orCXXorObjC)
Serge Pavlov09f99242014-01-23 15:05:00 +00001437 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001438
1439 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001440
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001441 BalancedDelimiterTracker T(*this, tok::l_paren);
1442 T.consumeOpen();
1443
John McCalldadc5752010-08-24 06:29:42 +00001444 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001445
Richard Smith02e85f32011-04-14 22:09:26 +00001446 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001447 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001448 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001449 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001450 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001451 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001452 FullExprArg ThirdPart(Actions);
John McCall48871652010-08-21 09:40:31 +00001453 Decl *SecondVar = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001454
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001455 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001456 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001457 C99orCXXorObjC? Sema::PCC_ForInit
1458 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001459 cutOffParsing();
1460 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001461 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001462
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001463 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001464 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001465
Chris Lattner9075bd72006-08-10 04:59:57 +00001466 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001467 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001468 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001469 // no first part, eat the ';'.
1470 ConsumeToken();
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001471 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001472 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001473 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001474 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001475
Richard Smith02e85f32011-04-14 22:09:26 +00001476 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001477 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001478 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1479
Chris Lattner49836b42009-04-02 04:16:50 +00001480 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +00001481 StmtVector Stmts;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001482 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smith02e85f32011-04-14 22:09:26 +00001483 DeclEnd, attrs, false,
1484 MightBeForRangeStmt ?
1485 &ForRangeInit : 0);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001486 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001487
Richard Smith02e85f32011-04-14 22:09:26 +00001488 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001489 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001490 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001491
Richard Smith02e85f32011-04-14 22:09:26 +00001492 ForRange = true;
1493 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001494 ConsumeToken();
1495 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001496 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001497 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001498 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001499
Douglas Gregor68762e72010-08-23 21:17:50 +00001500 if (Tok.is(tok::code_completion)) {
1501 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001502 cutOffParsing();
1503 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001504 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001505 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001506 } else {
1507 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001508 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001509 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001510 ProhibitAttributes(attrs);
Chris Lattner89c50c62006-08-11 06:41:18 +00001511 Value = ParseExpression();
Chris Lattner71e23ce2006-11-04 20:18:38 +00001512
John McCall34376a62010-12-04 03:47:34 +00001513 ForEach = isTokIdentifier_in();
1514
Chris Lattnercd68f642007-06-27 01:06:29 +00001515 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001516 if (!Value.isInvalid()) {
1517 if (ForEach)
1518 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1519 else
Richard Smith945f8d32013-01-14 22:39:08 +00001520 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001521 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001522
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001523 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001524 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001525 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001526 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001527
Douglas Gregor68762e72010-08-23 21:17:50 +00001528 if (Tok.is(tok::code_completion)) {
1529 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001530 cutOffParsing();
1531 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001532 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001533 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001534 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001535 // User tried to write the reasonable, but ill-formed, for-range-statement
1536 // for (expr : expr) { ... }
1537 Diag(Tok, diag::err_for_range_expected_decl)
1538 << FirstPart.get()->getSourceRange();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001539 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smith4f848f12011-12-20 22:56:20 +00001540 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001541 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001542 if (!Value.isInvalid()) {
1543 Diag(Tok, diag::err_expected_semi_for);
1544 } else {
1545 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001546 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001547 if (Tok.is(tok::semi))
1548 ConsumeToken();
1549 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001550 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001551 }
Serge Pavlov09f99242014-01-23 15:05:00 +00001552
1553 // Parse the second part of the for specifier.
1554 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smith02e85f32011-04-14 22:09:26 +00001555 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001556 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001557 // Parse the second part of the for specifier.
1558 if (Tok.is(tok::semi)) { // for (...;;
1559 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001560 } else if (Tok.is(tok::r_paren)) {
1561 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001562 } else {
John McCalldadc5752010-08-24 06:29:42 +00001563 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001564 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001565 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1566 else {
1567 Second = ParseExpression();
1568 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001569 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001570 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001571 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001572 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001573 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001574 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001575
Douglas Gregor230a7e62011-02-17 03:38:46 +00001576 if (Tok.isNot(tok::semi)) {
1577 if (!SecondPartIsInvalid || SecondVar)
1578 Diag(Tok, diag::err_expected_semi_for);
1579 else
1580 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001581 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001582 }
1583
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001584 if (Tok.is(tok::semi)) {
1585 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001586 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001587
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001588 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001589 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001590 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001591 // FIXME: The C++11 standard doesn't actually say that this is a
1592 // discarded-value expression, but it clearly should be.
1593 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001594 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001595 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001596 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001597 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001598
Richard Smith02e85f32011-04-14 22:09:26 +00001599 // We need to perform most of the semantic analysis for a C++0x for-range
1600 // statememt before parsing the body, in order to be able to deduce the type
1601 // of an auto-typed loop variable.
1602 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001603 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001604
John McCall53848232011-07-27 01:07:15 +00001605 if (ForRange) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001606 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smith02e85f32011-04-14 22:09:26 +00001607 ForRangeInit.ColonLoc,
1608 ForRangeInit.RangeExpr.get(),
Richard Smitha05b3b52012-09-20 21:52:32 +00001609 T.getCloseLocation(),
1610 Sema::BFRK_Build);
Richard Smith02e85f32011-04-14 22:09:26 +00001611
John McCall53848232011-07-27 01:07:15 +00001612
1613 // Similarly, we need to do the semantic analysis for a for-range
1614 // statement immediately in order to close over temporaries correctly.
1615 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001616 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001617 FirstPart.take(),
Chad Rosier67055f52012-07-10 21:35:27 +00001618 Collection.take(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001619 T.getCloseLocation());
John McCall53848232011-07-27 01:07:15 +00001620 }
1621
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001622 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001623 // there is no compound stmt. C90 does not have this clause. We only do this
1624 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001625 //
1626 // C++ 6.5p2:
1627 // The substatement in an iteration-statement implicitly defines a local scope
1628 // which is entered and exited each time through the loop.
1629 //
1630 // See comments in ParseIfStatement for why we create a scope for
1631 // for-init-statement/condition and a new scope for substatement in C++.
1632 //
David Majnemer2206bf52014-03-05 08:57:59 +00001633 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1634 Tok.is(tok::l_brace));
1635
1636 // The body of the for loop has the same local mangling number as the
1637 // for-init-statement.
1638 // It will only be incremented if the body contains other things that would
1639 // normally increment the mangling number (like a compound statement).
1640 if (C99orCXXorObjC)
1641 getCurScope()->decrementMSLocalManglingNumber();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001642
Chris Lattner9075bd72006-08-10 04:59:57 +00001643 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001644 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001645
Chris Lattner8fb26252007-08-22 05:28:50 +00001646 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001647 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001648
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001649 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001650 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001651
1652 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001653 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001654
Richard Smith02e85f32011-04-14 22:09:26 +00001655 if (ForEach)
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001656 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1657 Body.take());
Mike Stump11289f42009-09-09 15:08:12 +00001658
Richard Smith02e85f32011-04-14 22:09:26 +00001659 if (ForRange)
1660 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1661
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001662 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1663 SecondPart, SecondVar, ThirdPart,
1664 T.getCloseLocation(), Body.take());
Chris Lattner9075bd72006-08-10 04:59:57 +00001665}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001666
Chris Lattner503fadc2006-08-10 05:45:44 +00001667/// ParseGotoStatement
1668/// jump-statement:
1669/// 'goto' identifier ';'
1670/// [GNU] 'goto' '*' expression ';'
1671///
1672/// Note: this lets the caller parse the end ';'.
1673///
Richard Smithc202b282012-04-14 00:33:13 +00001674StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001675 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001676 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001677
John McCalldadc5752010-08-24 06:29:42 +00001678 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001679 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001680 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1681 Tok.getLocation());
1682 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001683 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001684 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001685 // GNU indirect goto extension.
1686 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001687 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001688 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001689 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001690 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001691 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001692 }
John McCallb268a282010-08-23 23:25:46 +00001693 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001694 } else {
Alp Tokerec543272013-12-24 09:48:30 +00001695 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001696 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001697 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001698
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001699 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001700}
1701
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001702/// ParseContinueStatement
1703/// jump-statement:
1704/// 'continue' ';'
1705///
1706/// Note: this lets the caller parse the end ';'.
1707///
Richard Smithc202b282012-04-14 00:33:13 +00001708StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001709 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001710 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001711}
1712
1713/// ParseBreakStatement
1714/// jump-statement:
1715/// 'break' ';'
1716///
1717/// Note: this lets the caller parse the end ';'.
1718///
Richard Smithc202b282012-04-14 00:33:13 +00001719StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001720 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001721 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001722}
1723
Chris Lattner503fadc2006-08-10 05:45:44 +00001724/// ParseReturnStatement
1725/// jump-statement:
1726/// 'return' expression[opt] ';'
Richard Smithc202b282012-04-14 00:33:13 +00001727StmtResult Parser::ParseReturnStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001728 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001729 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001730
John McCalldadc5752010-08-24 06:29:42 +00001731 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001732 if (Tok.isNot(tok::semi)) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001733 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001734 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001735 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001736 return StmtError();
1737 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001738
David Blaikiebbafb8a2012-03-11 07:00:24 +00001739 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001740 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001741 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001742 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001743 diag::warn_cxx98_compat_generalized_initializer_lists :
1744 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001745 << R.get()->getSourceRange();
1746 } else
1747 R = ParseExpression();
Serge Pavlovf79bd5c2013-12-04 03:51:59 +00001748 if (R.isInvalid()) {
1749 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001750 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001751 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001752 }
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00001753 return Actions.ActOnReturnStmt(ReturnLoc, R.take(), getCurScope());
Chris Lattner503fadc2006-08-10 05:45:44 +00001754}
Chris Lattner0116c472006-08-15 06:03:28 +00001755
John McCallf413f5e2013-05-03 00:10:13 +00001756namespace {
1757 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1758 Parser &TheParser;
1759 SourceLocation AsmLoc;
1760 StringRef AsmString;
1761
1762 /// The tokens we streamed into AsmString and handed off to MC.
1763 ArrayRef<Token> AsmToks;
1764
1765 /// The offset of each token in AsmToks within AsmString.
1766 ArrayRef<unsigned> AsmTokOffsets;
1767
1768 public:
1769 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1770 StringRef AsmString,
1771 ArrayRef<Token> Toks,
1772 ArrayRef<unsigned> Offsets)
1773 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1774 AsmToks(Toks), AsmTokOffsets(Offsets) {
1775 assert(AsmToks.size() == AsmTokOffsets.size());
1776 }
1777
1778 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1779 InlineAsmIdentifierInfo &Info,
Craig Topper2b07f022014-03-12 05:09:18 +00001780 bool IsUnevaluatedContext) override {
John McCallf413f5e2013-05-03 00:10:13 +00001781 // Collect the desired tokens.
1782 SmallVector<Token, 16> LineToks;
1783 const Token *FirstOrigToken = 0;
1784 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1785
1786 unsigned NumConsumedToks;
1787 ExprResult Result =
1788 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1789 IsUnevaluatedContext);
1790
1791 // If we consumed the entire line, tell MC that.
1792 // Also do this if we consumed nothing as a way of reporting failure.
1793 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1794 // By not modifying LineBuf, we're implicitly consuming it all.
1795
1796 // Otherwise, consume up to the original tokens.
1797 } else {
1798 assert(FirstOrigToken && "not using original tokens?");
1799
1800 // Since we're using original tokens, apply that offset.
1801 assert(FirstOrigToken[NumConsumedToks].getLocation()
1802 == LineToks[NumConsumedToks].getLocation());
1803 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1804 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1805
1806 // The total length we've consumed is the relative offset
1807 // of the last token we consumed plus its length.
1808 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1809 + AsmToks[LastIndex].getLength()
1810 - AsmTokOffsets[FirstIndex]);
1811 LineBuf = LineBuf.substr(0, TotalOffset);
1812 }
1813
1814 // Initialize the "decl" with the lookup result.
1815 Info.OpDecl = static_cast<void*>(Result.take());
1816 return Info.OpDecl;
1817 }
1818
1819 bool LookupInlineAsmField(StringRef Base, StringRef Member,
Craig Topper2b07f022014-03-12 05:09:18 +00001820 unsigned &Offset) override {
John McCallf413f5e2013-05-03 00:10:13 +00001821 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1822 Offset, AsmLoc);
1823 }
1824
1825 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1826 void *Context) {
1827 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1828 }
1829
1830 private:
1831 /// Collect the appropriate tokens for the given string.
1832 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1833 const Token *&FirstOrigToken) const {
1834 // For now, assert that the string we're working with is a substring
1835 // of what we gave to MC. This lets us use the original tokens.
1836 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1837 !std::less<const char*>()(AsmString.end(), Str.end()));
1838
1839 // Try to find a token whose offset matches the first token.
1840 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1841 const unsigned *FirstTokOffset
1842 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1843 FirstCharOffset);
1844
1845 // For now, assert that the start of the string exactly
1846 // corresponds to the start of a token.
1847 assert(*FirstTokOffset == FirstCharOffset);
1848
1849 // Use all the original tokens for this line. (We assume the
1850 // end of the line corresponds cleanly to a token break.)
1851 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1852 FirstOrigToken = &AsmToks[FirstTokIndex];
1853 unsigned LastCharOffset = Str.end() - AsmString.begin();
1854 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1855 if (AsmTokOffsets[i] >= LastCharOffset) break;
1856 TempToks.push_back(AsmToks[i]);
1857 }
1858 }
1859
1860 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1861 // Compute an offset into the inline asm buffer.
1862 // FIXME: This isn't right if .macro is involved (but hopefully, no
1863 // real-world code does that).
1864 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1865 const llvm::MemoryBuffer *LBuf =
1866 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1867 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1868
1869 // Figure out which token that offset points into.
1870 const unsigned *TokOffsetPtr =
1871 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1872 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1873 unsigned TokOffset = *TokOffsetPtr;
1874
1875 // If we come up with an answer which seems sane, use it; otherwise,
1876 // just point at the __asm keyword.
1877 // FIXME: Assert the answer is sane once we handle .macro correctly.
1878 SourceLocation Loc = AsmLoc;
1879 if (TokIndex < AsmToks.size()) {
1880 const Token &Tok = AsmToks[TokIndex];
1881 Loc = Tok.getLocation();
1882 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1883 }
1884 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1885 << D.getMessage();
1886 }
1887 };
1888}
1889
1890/// Parse an identifier in an MS-style inline assembly block.
1891///
1892/// \param CastInfo - a void* so that we don't have to teach Parser.h
1893/// about the actual type.
1894ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1895 unsigned &NumLineToksConsumed,
1896 void *CastInfo,
1897 bool IsUnevaluatedContext) {
1898 llvm::InlineAsmIdentifierInfo &Info =
1899 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1900
1901 // Push a fake token on the end so that we don't overrun the token
1902 // stream. We use ';' because it expression-parsing should never
1903 // overrun it.
1904 const tok::TokenKind EndOfStream = tok::semi;
1905 Token EndOfStreamTok;
1906 EndOfStreamTok.startToken();
1907 EndOfStreamTok.setKind(EndOfStream);
1908 LineToks.push_back(EndOfStreamTok);
1909
1910 // Also copy the current token over.
1911 LineToks.push_back(Tok);
1912
1913 PP.EnterTokenStream(LineToks.begin(),
1914 LineToks.size(),
1915 /*disable macros*/ true,
1916 /*owns tokens*/ false);
1917
1918 // Clear the current token and advance to the first token in LineToks.
1919 ConsumeAnyToken();
1920
1921 // Parse an optional scope-specifier if we're in C++.
1922 CXXScopeSpec SS;
1923 if (getLangOpts().CPlusPlus) {
1924 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1925 }
1926
1927 // Require an identifier here.
1928 SourceLocation TemplateKWLoc;
1929 UnqualifiedId Id;
1930 bool Invalid = ParseUnqualifiedId(SS,
1931 /*EnteringContext=*/false,
1932 /*AllowDestructorName=*/false,
1933 /*AllowConstructorName=*/false,
1934 /*ObjectType=*/ ParsedType(),
1935 TemplateKWLoc,
1936 Id);
1937
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001938 // Figure out how many tokens we are into LineToks.
1939 unsigned LineIndex = 0;
1940 if (Tok.is(EndOfStream)) {
1941 LineIndex = LineToks.size() - 2;
John McCallf413f5e2013-05-03 00:10:13 +00001942 } else {
John McCallf413f5e2013-05-03 00:10:13 +00001943 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1944 LineIndex++;
1945 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1946 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001947 }
John McCallf413f5e2013-05-03 00:10:13 +00001948
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001949 // If we've run into the poison token we inserted before, or there
1950 // was a parsing error, then claim the entire line.
1951 if (Invalid || Tok.is(EndOfStream)) {
1952 NumLineToksConsumed = LineToks.size() - 2;
1953 } else {
1954 // Otherwise, claim up to the start of the next token.
John McCallf413f5e2013-05-03 00:10:13 +00001955 NumLineToksConsumed = LineIndex;
1956 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001957
1958 // Finally, restore the old parsing state by consuming all the tokens we
1959 // staged before, implicitly killing off the token-lexer we pushed.
1960 for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
John McCallf413f5e2013-05-03 00:10:13 +00001961 ConsumeAnyToken();
1962 }
Dmitri Gribenkofc13b8b2013-12-03 00:48:09 +00001963 assert(Tok.is(EndOfStream));
1964 ConsumeToken();
John McCallf413f5e2013-05-03 00:10:13 +00001965
1966 // Leave LineToks in its original state.
1967 LineToks.pop_back();
1968 LineToks.pop_back();
1969
1970 // Perform the lookup.
1971 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1972 IsUnevaluatedContext);
1973}
1974
1975/// Turn a sequence of our tokens back into a string that we can hand
1976/// to the MC asm parser.
1977static bool buildMSAsmString(Preprocessor &PP,
1978 SourceLocation AsmLoc,
1979 ArrayRef<Token> AsmToks,
1980 SmallVectorImpl<unsigned> &TokOffsets,
1981 SmallString<512> &Asm) {
1982 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1983
1984 // Is this the start of a new assembly statement?
1985 bool isNewStatement = true;
1986
1987 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1988 const Token &Tok = AsmToks[i];
1989
1990 // Start each new statement with a newline and a tab.
1991 if (!isNewStatement &&
1992 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1993 Asm += "\n\t";
1994 isNewStatement = true;
1995 }
1996
1997 // Preserve the existence of leading whitespace except at the
1998 // start of a statement.
1999 if (!isNewStatement && Tok.hasLeadingSpace())
2000 Asm += ' ';
2001
2002 // Remember the offset of this token.
2003 TokOffsets.push_back(Asm.size());
2004
2005 // Don't actually write '__asm' into the assembly stream.
2006 if (Tok.is(tok::kw_asm)) {
2007 // Complain about __asm at the end of the stream.
2008 if (i + 1 == e) {
2009 PP.Diag(AsmLoc, diag::err_asm_empty);
2010 return true;
2011 }
2012
2013 continue;
2014 }
2015
2016 // Append the spelling of the token.
2017 SmallString<32> SpellingBuffer;
2018 bool SpellingInvalid = false;
2019 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
2020 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
2021
2022 // We are no longer at the start of a statement.
2023 isNewStatement = false;
2024 }
2025
2026 // Ensure that the buffer is null-terminated.
2027 Asm.push_back('\0');
2028 Asm.pop_back();
2029
2030 assert(TokOffsets.size() == AsmToks.size());
2031 return false;
2032}
2033
Eli Friedmana4b02c32011-09-30 01:13:51 +00002034/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
2035/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier32503022012-06-11 20:47:18 +00002036///
2037/// [MS] ms-asm-statement:
2038/// ms-asm-block
2039/// ms-asm-block ms-asm-statement
2040///
2041/// [MS] ms-asm-block:
2042/// '__asm' ms-asm-line '\n'
2043/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
2044///
2045/// [MS] ms-asm-instruction-block
2046/// ms-asm-line
2047/// ms-asm-line '\n' ms-asm-instruction-block
2048///
Eli Friedmana4b02c32011-09-30 01:13:51 +00002049StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
2050 SourceManager &SrcMgr = PP.getSourceManager();
2051 SourceLocation EndLoc = AsmLoc;
Chad Rosier32503022012-06-11 20:47:18 +00002052 SmallVector<Token, 4> AsmToks;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002053
2054 bool InBraces = false;
2055 unsigned short savedBraceCount = 0;
2056 bool InAsmComment = false;
2057 FileID FID;
2058 unsigned LineNo = 0;
2059 unsigned NumTokensRead = 0;
2060 SourceLocation LBraceLoc;
2061
2062 if (Tok.is(tok::l_brace)) {
2063 // Braced inline asm: consume the opening brace.
2064 InBraces = true;
2065 savedBraceCount = BraceCount;
2066 EndLoc = LBraceLoc = ConsumeBrace();
2067 ++NumTokensRead;
2068 } else {
2069 // Single-line inline asm; compute which line it is on.
2070 std::pair<FileID, unsigned> ExpAsmLoc =
2071 SrcMgr.getDecomposedExpansionLoc(EndLoc);
2072 FID = ExpAsmLoc.first;
2073 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2074 }
2075
2076 SourceLocation TokLoc = Tok.getLocation();
Eli Friedmana4b02c32011-09-30 01:13:51 +00002077 do {
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002078 // If we hit EOF, we're done, period.
Richard Smith34f30512013-11-23 04:06:09 +00002079 if (isEofOrEom())
Eli Friedmana4b02c32011-09-30 01:13:51 +00002080 break;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002081
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002082 if (!InAsmComment && Tok.is(tok::semi)) {
2083 // A semicolon in an asm is the start of a comment.
2084 InAsmComment = true;
2085 if (InBraces) {
2086 // Compute which line the comment is on.
2087 std::pair<FileID, unsigned> ExpSemiLoc =
2088 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2089 FID = ExpSemiLoc.first;
2090 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2091 }
2092 } else if (!InBraces || InAsmComment) {
2093 // If end-of-line is significant, check whether this token is on a
2094 // new line.
2095 std::pair<FileID, unsigned> ExpLoc =
2096 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2097 if (ExpLoc.first != FID ||
2098 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2099 // If this is a single-line __asm, we're done.
2100 if (!InBraces)
2101 break;
2102 // We're no longer in a comment.
2103 InAsmComment = false;
2104 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2105 // Single-line asm always ends when a closing brace is seen.
2106 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2107 // does MSVC do here?
2108 break;
2109 }
2110 }
2111 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2112 BraceCount == (savedBraceCount + 1)) {
2113 // Consume the closing brace, and finish
2114 EndLoc = ConsumeBrace();
2115 break;
2116 }
2117
2118 // Consume the next token; make sure we don't modify the brace count etc.
2119 // if we are in a comment.
2120 EndLoc = TokLoc;
2121 if (InAsmComment)
2122 PP.Lex(Tok);
2123 else {
2124 AsmToks.push_back(Tok);
2125 ConsumeAnyToken();
2126 }
2127 TokLoc = Tok.getLocation();
2128 ++NumTokensRead;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002129 } while (1);
Chad Rosier32503022012-06-11 20:47:18 +00002130
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002131 if (InBraces && BraceCount != savedBraceCount) {
2132 // __asm without closing brace (this can happen at EOF).
Alp Tokerec543272013-12-24 09:48:30 +00002133 Diag(Tok, diag::err_expected) << tok::r_brace;
2134 Diag(LBraceLoc, diag::note_matching) << tok::l_brace;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002135 return StmtError();
2136 } else if (NumTokensRead == 0) {
2137 // Empty __asm.
Alp Tokerec543272013-12-24 09:48:30 +00002138 Diag(Tok, diag::err_expected) << tok::l_brace;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002139 return StmtError();
2140 }
2141
John McCallf413f5e2013-05-03 00:10:13 +00002142 // Okay, prepare to use MC to parse the assembly.
2143 SmallVector<StringRef, 4> ConstraintRefs;
2144 SmallVector<Expr*, 4> Exprs;
2145 SmallVector<StringRef, 4> ClobberRefs;
2146
2147 // We need an actual supported target.
Benjamin Kramer9299637dc2014-03-04 19:31:42 +00002148 const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
John McCallf413f5e2013-05-03 00:10:13 +00002149 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
Alp Tokerb3644282013-10-30 15:07:10 +00002150 const std::string &TT = TheTriple.getTriple();
2151 const llvm::Target *TheTarget = 0;
John McCallf413f5e2013-05-03 00:10:13 +00002152 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2153 ArchTy != llvm::Triple::x86_64);
Alp Tokerb3644282013-10-30 15:07:10 +00002154 if (UnsupportedArch) {
John McCallf413f5e2013-05-03 00:10:13 +00002155 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
Alp Tokerb3644282013-10-30 15:07:10 +00002156 } else {
2157 std::string Error;
2158 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2159 if (!TheTarget)
2160 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
2161 }
Alp Toker45cf31f2013-10-30 14:29:28 +00002162
John McCallf413f5e2013-05-03 00:10:13 +00002163 // If we don't support assembly, or the assembly is empty, we don't
2164 // need to instantiate the AsmParser, etc.
Alp Tokerb3644282013-10-30 15:07:10 +00002165 if (!TheTarget || AsmToks.empty()) {
John McCallf413f5e2013-05-03 00:10:13 +00002166 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2167 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2168 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2169 }
2170
2171 // Expand the tokens into a string buffer.
2172 SmallString<512> AsmString;
2173 SmallVector<unsigned, 8> TokOffsets;
2174 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2175 return StmtError();
2176
Ahmed Charlesb8984322014-03-07 20:03:18 +00002177 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2178 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002179 // Get the instruction descriptor.
Nico Weber303ff602014-04-23 22:07:21 +00002180 std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Charlesb8984322014-03-07 20:03:18 +00002181 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2182 std::unique_ptr<llvm::MCSubtargetInfo> STI(
2183 TheTarget->createMCSubtargetInfo(TT, "", ""));
John McCallf413f5e2013-05-03 00:10:13 +00002184
2185 llvm::SourceMgr TempSrcMgr;
Bill Wendlingda1e3e72013-06-18 07:22:05 +00002186 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallf413f5e2013-05-03 00:10:13 +00002187 llvm::MemoryBuffer *Buffer =
2188 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2189
2190 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2191 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2192
Ahmed Charlesb8984322014-03-07 20:03:18 +00002193 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2194 std::unique_ptr<llvm::MCAsmParser> Parser(
2195 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +00002196
2197 // FIXME: init MCOptions from sanitizer flags here.
2198 llvm::MCTargetOptions MCOptions;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002199 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +00002200 TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
John McCallf413f5e2013-05-03 00:10:13 +00002201
Nico Weber01708cd2014-04-23 19:19:20 +00002202 std::unique_ptr<llvm::MCInstPrinter> IP(
2203 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI));
John McCallf413f5e2013-05-03 00:10:13 +00002204
2205 // Change to the Intel dialect.
2206 Parser->setAssemblerDialect(1);
2207 Parser->setTargetParser(*TargetParser.get());
2208 Parser->setParsingInlineAsm(true);
2209 TargetParser->setParsingInlineAsm(true);
2210
2211 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2212 AsmToks, TokOffsets);
2213 TargetParser->setSemaCallback(&Callback);
2214 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2215 &Callback);
2216
2217 unsigned NumOutputs;
2218 unsigned NumInputs;
2219 std::string AsmStringIR;
2220 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2221 SmallVector<std::string, 4> Constraints;
2222 SmallVector<std::string, 4> Clobbers;
2223 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2224 NumOutputs, NumInputs, OpExprs, Constraints,
Nico Weber303ff602014-04-23 22:07:21 +00002225 Clobbers, MII.get(), IP.get(), Callback))
John McCallf413f5e2013-05-03 00:10:13 +00002226 return StmtError();
2227
Reid Kleckner185940a2014-03-27 00:00:03 +00002228 // Filter out "fpsw". Clang doesn't accept it, and it always lists flags and
2229 // fpsr as clobbers.
2230 auto End = std::remove(Clobbers.begin(), Clobbers.end(), "fpsw");
2231 Clobbers.erase(End, Clobbers.end());
2232
John McCallf413f5e2013-05-03 00:10:13 +00002233 // Build the vector of clobber StringRefs.
2234 unsigned NumClobbers = Clobbers.size();
2235 ClobberRefs.resize(NumClobbers);
2236 for (unsigned i = 0; i != NumClobbers; ++i)
2237 ClobberRefs[i] = StringRef(Clobbers[i]);
2238
2239 // Recast the void pointers and build the vector of constraint StringRefs.
2240 unsigned NumExprs = NumOutputs + NumInputs;
2241 ConstraintRefs.resize(NumExprs);
2242 Exprs.resize(NumExprs);
2243 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2244 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2245 if (!OpExpr)
2246 return StmtError();
2247
2248 // Need address of variable.
2249 if (OpExprs[i].second)
2250 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2251 .take();
2252
2253 ConstraintRefs[i] = StringRef(Constraints[i]);
2254 Exprs[i] = OpExpr;
2255 }
2256
Chad Rosierc6c71332012-08-06 20:03:45 +00002257 // FIXME: We should be passing source locations for better diagnostics.
John McCallf413f5e2013-05-03 00:10:13 +00002258 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2259 NumOutputs, NumInputs,
2260 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002261}
2262
Chris Lattner0116c472006-08-15 06:03:28 +00002263/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff69e8f9e2008-02-11 23:15:56 +00002264/// asm-statement:
2265/// gnu-asm-statement
2266/// ms-asm-statement
2267///
2268/// [GNU] gnu-asm-statement:
Chris Lattner0116c472006-08-15 06:03:28 +00002269/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2270///
2271/// [GNU] asm-argument:
2272/// asm-string-literal
2273/// asm-string-literal ':' asm-operands[opt]
2274/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2275/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2276/// ':' asm-clobbers
2277///
2278/// [GNU] asm-clobbers:
2279/// asm-string-literal
2280/// asm-clobbers ',' asm-string-literal
2281///
John McCalldadc5752010-08-24 06:29:42 +00002282StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002283 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattner73c56c02007-10-29 04:04:16 +00002284 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002285
Chad Rosierc8e56e82012-12-05 21:08:21 +00002286 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosier67055f52012-07-10 21:35:27 +00002287 !isTypeQualifier()) {
Steve Naroffb2c80c72008-02-07 03:50:06 +00002288 msAsm = true;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002289 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002290 }
John McCall084e83d2011-03-24 11:26:52 +00002291 DeclSpec DS(AttrFactory);
Chris Lattner0116c472006-08-15 06:03:28 +00002292 SourceLocation Loc = Tok.getLocation();
Alexis Hunt96d5c762009-11-21 08:43:09 +00002293 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002294
Chris Lattner0116c472006-08-15 06:03:28 +00002295 // GNU asms accept, but warn, about type-qualifiers other than volatile.
Chris Lattnera925dc62006-11-28 04:33:46 +00002296 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner6d29c102008-11-18 07:48:38 +00002297 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Chris Lattnera925dc62006-11-28 04:33:46 +00002298 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner6d29c102008-11-18 07:48:38 +00002299 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith8e1ac332013-03-28 01:55:44 +00002300 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2301 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2302 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redlb62406f2008-12-11 19:48:14 +00002303
Chris Lattner0116c472006-08-15 06:03:28 +00002304 // Remember if this was a volatile asm.
Anders Carlsson660bdd12007-11-23 23:12:25 +00002305 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002306 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002307 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Alexey Bataevee6507d2013-11-18 08:17:37 +00002308 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002309 return StmtError();
Chris Lattner0116c472006-08-15 06:03:28 +00002310 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002311 BalancedDelimiterTracker T(*this, tok::l_paren);
2312 T.consumeOpen();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002313
John McCalldadc5752010-08-24 06:29:42 +00002314 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002315 if (AsmString.isInvalid()) {
Richard Smithd67aea22012-03-06 03:21:47 +00002316 // Consume up to and including the closing paren.
2317 T.skipToEnd();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002318 return StmtError();
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002319 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002320
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002321 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002322 ExprVector Constraints;
2323 ExprVector Exprs;
2324 ExprVector Clobbers;
Chris Lattner0116c472006-08-15 06:03:28 +00002325
Anders Carlsson19fe1162008-02-05 23:03:50 +00002326 if (Tok.is(tok::r_paren)) {
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002327 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002328 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002329 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2330 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2331 Constraints, Exprs, AsmString.take(),
2332 Clobbers, T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002333 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002334
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002335 // Parse Outputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002336 bool AteExtraColon = false;
2337 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2338 // In C++ mode, parse "::" like ": :".
2339 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002340 ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002341
Chris Lattner15768502009-12-20 23:08:04 +00002342 if (!AteExtraColon &&
2343 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002344 return StmtError();
2345 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002346
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002347 unsigned NumOutputs = Names.size();
2348
2349 // Parse Inputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002350 if (AteExtraColon ||
2351 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2352 // In C++ mode, parse "::" like ": :".
2353 if (AteExtraColon)
2354 AteExtraColon = false;
2355 else {
2356 AteExtraColon = Tok.is(tok::coloncolon);
2357 ConsumeToken();
2358 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002359
Chris Lattner15768502009-12-20 23:08:04 +00002360 if (!AteExtraColon &&
2361 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002362 return StmtError();
2363 }
2364
2365 assert(Names.size() == Constraints.size() &&
2366 Constraints.size() == Exprs.size() &&
2367 "Input operand size mismatch!");
2368
2369 unsigned NumInputs = Names.size() - NumOutputs;
2370
2371 // Parse the clobbers, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002372 if (AteExtraColon || Tok.is(tok::colon)) {
2373 if (!AteExtraColon)
2374 ConsumeToken();
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002375
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002376 // Parse the asm-string list for clobbers if present.
2377 if (Tok.isNot(tok::r_paren)) {
2378 while (1) {
John McCalldadc5752010-08-24 06:29:42 +00002379 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002380
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002381 if (Clobber.isInvalid())
2382 break;
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002383
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002384 Clobbers.push_back(Clobber.release());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002385
Alp Toker97650562014-01-10 11:19:30 +00002386 if (!TryConsumeToken(tok::comma))
2387 break;
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002388 }
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002389 }
2390 }
2391
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002392 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002393 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2394 NumInputs, Names.data(), Constraints, Exprs,
2395 AsmString.take(), Clobbers,
2396 T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002397}
2398
2399/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002400/// asm-statement, assuming the leading ':' token was eaten.
Chris Lattner0116c472006-08-15 06:03:28 +00002401///
2402/// [GNU] asm-operands:
2403/// asm-operand
2404/// asm-operands ',' asm-operand
2405///
2406/// [GNU] asm-operand:
2407/// asm-string-literal '(' expression ')'
2408/// '[' identifier ']' asm-string-literal '(' expression ')'
2409///
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00002410//
2411// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002412bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieu2bd04012011-09-09 02:00:50 +00002413 SmallVectorImpl<Expr *> &Constraints,
2414 SmallVectorImpl<Expr *> &Exprs) {
Chris Lattner0116c472006-08-15 06:03:28 +00002415 // 'asm-operands' isn't present?
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002416 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002417 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002418
2419 while (1) {
Chris Lattner0116c472006-08-15 06:03:28 +00002420 // Read the [id] if present.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002421 if (Tok.is(tok::l_square)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002422 BalancedDelimiterTracker T(*this, tok::l_square);
2423 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00002424
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002425 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00002426 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00002427 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002428 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002429 }
Mike Stump11289f42009-09-09 15:08:12 +00002430
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002431 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner645ff3f2007-10-29 04:06:22 +00002432 ConsumeToken();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002433
Anders Carlsson9a020f92010-01-30 22:25:16 +00002434 Names.push_back(II);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002435 T.consumeClose();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002436 } else
Anders Carlsson9a020f92010-01-30 22:25:16 +00002437 Names.push_back(0);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002438
John McCalldadc5752010-08-24 06:29:42 +00002439 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002440 if (Constraint.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002441 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002442 return true;
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002443 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002444 Constraints.push_back(Constraint.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002445
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002446 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002447 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Alexey Bataevee6507d2013-11-18 08:17:37 +00002448 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002449 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002450 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002451
Chris Lattner0116c472006-08-15 06:03:28 +00002452 // Read the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002453 BalancedDelimiterTracker T(*this, tok::l_paren);
2454 T.consumeOpen();
John McCalldadc5752010-08-24 06:29:42 +00002455 ExprResult Res(ParseExpression());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002456 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002457 if (Res.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002458 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002459 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002460 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002461 Exprs.push_back(Res.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002462 // Eat the comma and continue parsing if it exists.
Alp Toker97650562014-01-10 11:19:30 +00002463 if (!TryConsumeToken(tok::comma))
2464 return false;
Chris Lattner0116c472006-08-15 06:03:28 +00002465 }
2466}
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002467
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002468Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002469 assert(Tok.is(tok::l_brace));
2470 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002471
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00002472 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00002473 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002474 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002475 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002476 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002477
John McCallfaf5fb42010-08-26 23:41:50 +00002478 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2479 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002480
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002481 // Do not enter a scope for the brace, as the arguments are in the same scope
2482 // (the function body) as the body itself. Instead, just read the statement
2483 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002484 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002485
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002486 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002487 if (FnBody.isInvalid()) {
2488 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002489 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002490 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002491
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002492 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002493 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002494}
Sebastian Redlb219c902008-12-21 16:41:36 +00002495
Sebastian Redla7b98a72009-04-26 20:35:05 +00002496/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2497///
2498/// function-try-block:
2499/// 'try' ctor-initializer[opt] compound-statement handler-seq
2500///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002501Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002502 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2503 SourceLocation TryLoc = ConsumeToken();
2504
John McCallfaf5fb42010-08-26 23:41:50 +00002505 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2506 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002507
2508 // Constructor initializer list?
2509 if (Tok.is(tok::colon))
2510 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002511 else
2512 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002513
Richard Smith1ab34b32012-11-19 21:13:18 +00002514 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2515 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002516 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002517 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002518 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002519
Sebastian Redld98ecd62009-04-26 21:08:36 +00002520 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002521 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00002522 // If we failed to parse the try-catch, we just give the function an empty
2523 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002524 if (FnBody.isInvalid()) {
2525 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002526 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002527 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002528
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002529 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002530 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002531}
2532
Erik Verbruggen6e922512012-04-12 10:11:59 +00002533bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002534 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00002535 assert(SkipFunctionBodies &&
2536 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002537
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002538 if (!PP.isCodeCompletionEnabled()) {
2539 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002540 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002541 return true;
2542 }
2543
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002544 // We're in code-completion mode. Skip parsing for all function bodies unless
2545 // the body contains the code-completion point.
2546 TentativeParsingAction PA(*this);
2547 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002548 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002549 PA.Commit();
2550 return true;
2551 }
2552
2553 PA.Revert();
2554 return false;
2555}
2556
Sebastian Redlb219c902008-12-21 16:41:36 +00002557/// ParseCXXTryBlock - Parse a C++ try-block.
2558///
2559/// try-block:
2560/// 'try' compound-statement handler-seq
2561///
Richard Smithc202b282012-04-14 00:33:13 +00002562StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002563 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2564
2565 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002566 return ParseCXXTryBlockCommon(TryLoc);
2567}
2568
2569/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2570/// function-try-block.
2571///
2572/// try-block:
2573/// 'try' compound-statement handler-seq
2574///
2575/// function-try-block:
2576/// 'try' ctor-initializer[opt] compound-statement handler-seq
2577///
2578/// handler-seq:
2579/// handler handler-seq[opt]
2580///
John Wiegley1c0675e2011-04-28 01:08:34 +00002581/// [Borland] try-block:
2582/// 'try' compound-statement seh-except-block
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002583/// 'try' compound-statement seh-finally-block
John Wiegley1c0675e2011-04-28 01:08:34 +00002584///
David Blaikie1c9c9042012-11-10 01:04:23 +00002585StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002586 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002587 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Alexis Hunt96d5c762009-11-21 08:43:09 +00002588 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002589
2590 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikie3403feb2012-11-13 18:51:45 +00002591 Scope::DeclScope | Scope::TryScope |
2592 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002593 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002594 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002595
John Wiegley1c0675e2011-04-28 01:08:34 +00002596 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002597
Richard Smithc202b282012-04-14 00:33:13 +00002598 if ((Tok.is(tok::identifier) &&
2599 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2600 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002601 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2602 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002603 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002604 SourceLocation Loc = ConsumeToken();
2605 Handler = ParseSEHExceptBlock(Loc);
2606 }
2607 else {
2608 SourceLocation Loc = ConsumeToken();
2609 Handler = ParseSEHFinallyBlock(Loc);
2610 }
2611 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002612 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002613
John Wiegley1c0675e2011-04-28 01:08:34 +00002614 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2615 TryLoc,
2616 TryBlock.take(),
2617 Handler.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002618 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002619 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002620 StmtVector Handlers;
Richard Smithc2c8bb82013-10-15 01:34:54 +00002621
2622 // C++11 attributes can't appear here, despite this context seeming
2623 // statement-like.
2624 DiagnoseAndSkipCXX11Attributes();
Sebastian Redlb219c902008-12-21 16:41:36 +00002625
John Wiegley1c0675e2011-04-28 01:08:34 +00002626 if (Tok.isNot(tok::kw_catch))
2627 return StmtError(Diag(Tok, diag::err_expected_catch));
2628 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002629 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002630 if (!Handler.isInvalid())
2631 Handlers.push_back(Handler.release());
2632 }
2633 // Don't bother creating the full statement if we don't have any usable
2634 // handlers.
2635 if (Handlers.empty())
2636 return StmtError();
2637
Robert Wilhelmcafda822013-08-22 09:20:03 +00002638 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002639 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002640}
2641
2642/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2643///
Richard Smith1dba27c2013-01-29 09:02:09 +00002644/// handler:
2645/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002646///
Richard Smith1dba27c2013-01-29 09:02:09 +00002647/// exception-declaration:
2648/// attribute-specifier-seq[opt] type-specifier-seq declarator
2649/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2650/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002651///
David Blaikie1c9c9042012-11-10 01:04:23 +00002652StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002653 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2654
2655 SourceLocation CatchLoc = ConsumeToken();
2656
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002657 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002658 if (T.expectAndConsume())
Sebastian Redlb219c902008-12-21 16:41:36 +00002659 return StmtError();
2660
2661 // C++ 3.3.2p3:
2662 // The name in a catch exception-declaration is local to the handler and
2663 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002664 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002665 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002666
2667 // exception-declaration is equivalent to '...' or a parameter-declaration
2668 // without default arguments.
John McCall48871652010-08-21 09:40:31 +00002669 Decl *ExceptionDecl = 0;
Sebastian Redlb219c902008-12-21 16:41:36 +00002670 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002671 ParsedAttributesWithRange Attributes(AttrFactory);
2672 MaybeParseCXX11Attributes(Attributes);
2673
John McCall084e83d2011-03-24 11:26:52 +00002674 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002675 DS.takeAttributesFrom(Attributes);
2676
Sebastian Redl54c04d42008-12-22 19:15:10 +00002677 if (ParseCXXTypeSpecifierSeq(DS))
2678 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002679
Sebastian Redlb219c902008-12-21 16:41:36 +00002680 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2681 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002682 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002683 } else
2684 ConsumeToken();
2685
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002686 T.consumeClose();
2687 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002688 return StmtError();
2689
2690 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002691 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redlb219c902008-12-21 16:41:36 +00002692
Alexis Hunt96d5c762009-11-21 08:43:09 +00002693 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002694 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002695 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002696 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002697
John McCallb268a282010-08-23 23:25:46 +00002698 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002699}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002700
2701void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002702 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002703 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002704 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002705
Douglas Gregor43edb322011-10-24 22:31:10 +00002706 // Handle dependent statements by parsing the braces as a compound statement.
2707 // This is not the same behavior as Visual C++, which don't treat this as a
2708 // compound statement, but for Clang's type checking we can't have anything
2709 // inside these braces escaping to the surrounding code.
2710 if (Result.Behavior == IEB_Dependent) {
2711 if (!Tok.is(tok::l_brace)) {
Alp Tokerec543272013-12-24 09:48:30 +00002712 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smithc202b282012-04-14 00:33:13 +00002713 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002714 }
Richard Smithc202b282012-04-14 00:33:13 +00002715
2716 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002717 if (Compound.isInvalid())
2718 return;
Richard Smithc202b282012-04-14 00:33:13 +00002719
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002720 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2721 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002722 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002723 Result.Name,
2724 Compound.get());
2725 if (DepResult.isUsable())
2726 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002727 return;
2728 }
Richard Smithc202b282012-04-14 00:33:13 +00002729
Douglas Gregor43edb322011-10-24 22:31:10 +00002730 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2731 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00002732 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002733 return;
2734 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002735
Douglas Gregor43edb322011-10-24 22:31:10 +00002736 switch (Result.Behavior) {
2737 case IEB_Parse:
2738 // Parse the statements below.
2739 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002740
Douglas Gregor43edb322011-10-24 22:31:10 +00002741 case IEB_Dependent:
2742 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002743
Douglas Gregor43edb322011-10-24 22:31:10 +00002744 case IEB_Skip:
2745 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002746 return;
2747 }
2748
2749 // Condition is true, parse the statements.
2750 while (Tok.isNot(tok::r_brace)) {
2751 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2752 if (R.isUsable())
2753 Stmts.push_back(R.release());
2754 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002755 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002756}