blob: 9d44f51bc972348e417a93c300a7e92866061f8d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerd167ca02009-12-10 00:21:05 +000016#include "RAIIObjectsForParser.h"
John McCallaeeacf72013-05-03 00:10:13 +000017#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/PrettyStackTrace.h"
20#include "clang/Basic/SourceManager.h"
John McCallaeeacf72013-05-03 00:10:13 +000021#include "clang/Basic/TargetInfo.h"
John McCall19510852010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
John McCallf312b1e2010-08-26 23:41:50 +000023#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall19510852010-08-20 18:27:03 +000024#include "clang/Sema/Scope.h"
Richard Smith05766812012-08-18 00:55:03 +000025#include "clang/Sema/TypoCorrection.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070026#include "llvm/ADT/SmallString.h"
John McCallaeeacf72013-05-03 00:10:13 +000027#include "llvm/MC/MCAsmInfo.h"
28#include "llvm/MC/MCContext.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070029#include "llvm/MC/MCInstPrinter.h"
30#include "llvm/MC/MCInstrInfo.h"
John McCallaeeacf72013-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"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070037#include "llvm/MC/MCTargetOptions.h"
John McCallaeeacf72013-05-03 00:10:13 +000038#include "llvm/Support/SourceMgr.h"
39#include "llvm/Support/TargetRegistry.h"
40#include "llvm/Support/TargetSelect.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
44// C99 6.8: Statements and Blocks.
45//===----------------------------------------------------------------------===//
46
Richard Smith961d0572013-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kyrtzidisdcdd55f2008-09-07 18:58:01 +000074/// [C++] declaration-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +000075/// [C++] try-block
John Wiegley28bbe4b2011-04-28 01:08:34 +000076/// [MS] seh-try-block
Fariborz Jahanianb384d322007-10-04 20:19:06 +000077/// [OBC] objc-throw-statement
78/// [OBC] objc-try-catch-statement
Fariborz Jahanianc385c902008-01-29 18:21:32 +000079/// [OBC] objc-synchronized-statement
Reid Spencer5f016e22007-07-11 17:01:13 +000080/// [GNU] asm-statement
81/// [OMP] openmp-construct [TODO]
82///
83/// labeled-statement:
84/// identifier ':' statement
85/// 'case' constant-expression ':' statement
86/// 'default' ':' statement
87///
88/// selection-statement:
89/// if-statement
90/// switch-statement
91///
92/// iteration-statement:
93/// while-statement
94/// do-statement
95/// for-statement
96///
97/// expression-statement:
98/// expression[opt] ';'
99///
100/// jump-statement:
101/// 'goto' identifier ';'
102/// 'continue' ';'
103/// 'break' ';'
104/// 'return' expression[opt] ';'
105/// [GNU] 'goto' '*' expression ';'
106///
Fariborz Jahanianb384d322007-10-04 20:19:06 +0000107/// [OBC] objc-throw-statement:
108/// [OBC] '@' 'throw' expression ';'
Mike Stump1eb44332009-09-09 15:08:12 +0000109/// [OBC] '@' 'throw' ';'
110///
John McCall60d7b3a2010-08-24 06:29:42 +0000111StmtResult
Nico Weber5cb94a72011-12-22 23:26:17 +0000112Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
113 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000114
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +0000115 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000116
Richard Smith534986f2012-04-14 00:33:13 +0000117 ParsedAttributesWithRange Attrs(AttrFactory);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700118 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
Richard Smith534986f2012-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 Uhrain6243f622013-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
Stephen Hines651f13c2014-04-23 16:59:28 -0700148 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain6243f622013-09-27 19:40:12 +0000149 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
Kaelyn Uhraina89ee572013-10-01 22:00:28 +0000150 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain0f90ee02013-09-27 19:40:16 +0000151 if (NextToken.is(tok::equal))
152 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain2ceb67a2013-09-27 23:54:23 +0000153 if (NextToken.is(tok::period) &&
154 candidate.getCorrectionDeclAs<NamespaceDecl>())
155 return false;
Kaelyn Uhrain6243f622013-09-27 19:40:12 +0000156 return CorrectionCandidateCallback::ValidateCandidate(candidate);
157 }
158
159private:
160 Token NextToken;
161};
162}
163
Richard Smith534986f2012-04-14 00:33:13 +0000164StmtResult
165Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
166 bool OnlyStatement, SourceLocation *TrailingElseLoc,
167 ParsedAttributesWithRange &Attrs) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700168 const char *SemiError = nullptr;
Richard Smith534986f2012-04-14 00:33:13 +0000169 StmtResult Res;
Sean Huntbbd37c62009-11-21 08:43:09 +0000170
Reid Spencer5f016e22007-07-11 17:01:13 +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 Gregor312eadb2011-04-24 05:37:28 +0000174Retry:
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000175 tok::TokenKind Kind = Tok.getKind();
176 SourceLocation AtLoc;
177 switch (Kind) {
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000178 case tok::at: // May be a @try or @throw statement
179 {
Richard Smith534986f2012-04-14 00:33:13 +0000180 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000181 AtLoc = ConsumeToken(); // consume @
Sebastian Redl43bc2a02008-12-11 20:12:42 +0000182 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000183 }
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000184
Douglas Gregor791215b2009-09-21 20:51:25 +0000185 case tok::code_completion:
John McCallf312b1e2010-08-26 23:41:50 +0000186 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000187 cutOffParsing();
188 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000189
Douglas Gregor312eadb2011-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 Kyrtzidisb9f930d2008-07-12 21:04:42 +0000193 // identifier ':' statement
Richard Smith534986f2012-04-14 00:33:13 +0000194 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000195 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000196
Richard Smith05766812012-08-18 00:55:03 +0000197 // Look up the identifier, and typo-correct it to a keyword if it's not
198 // found.
Douglas Gregor3b887352011-04-27 04:48:22 +0000199 if (Next.isNot(tok::coloncolon)) {
Richard Smith05766812012-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 Uhrain6243f622013-09-27 19:40:12 +0000202 StatementFilterCCC Validator(Next);
203 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
Richard Smith05766812012-08-18 00:55:03 +0000204 == ANK_Error) {
Douglas Gregor312eadb2011-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 Bataev8fe24752013-11-18 08:17:37 +0000207 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000208 if (Tok.is(tok::semi))
209 ConsumeToken();
210 return StmtError();
Richard Smith05766812012-08-18 00:55:03 +0000211 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000212
Richard Smith05766812012-08-18 00:55:03 +0000213 // If the identifier was typo-corrected, try again.
214 if (Tok.isNot(tok::identifier))
Douglas Gregor312eadb2011-04-24 05:37:28 +0000215 goto Retry;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000216 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000217
Douglas Gregor312eadb2011-04-24 05:37:28 +0000218 // Fall through
219 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000220
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000221 default: {
David Blaikie4e4d0842012-03-11 07:00:24 +0000222 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner97144fc2009-04-02 04:16:50 +0000223 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek8113ecf2010-11-10 05:59:39 +0000224 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smith534986f2012-04-14 00:33:13 +0000225 DeclEnd, Attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000226 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000227 }
228
229 if (Tok.is(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 Diag(Tok, diag::err_expected_statement);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000231 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 }
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Richard Smith534986f2012-04-14 00:33:13 +0000234 return ParseExprStatement();
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000235 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000236
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000238 return ParseCaseStatement();
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000240 return ParseDefaultStatement();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000241
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smith534986f2012-04-14 00:33:13 +0000243 return ParseCompoundStatement();
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000244 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +0000245 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
246 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000247 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smith534986f2012-04-14 00:33:13 +0000250 return ParseIfStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smith534986f2012-04-14 00:33:13 +0000252 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000253
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smith534986f2012-04-14 00:33:13 +0000255 return ParseWhileStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smith534986f2012-04-14 00:33:13 +0000257 Res = ParseDoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000258 SemiError = "do/while";
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 break;
260 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smith534986f2012-04-14 00:33:13 +0000261 return ParseForStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000262
263 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smith534986f2012-04-14 00:33:13 +0000264 Res = ParseGotoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000265 SemiError = "goto";
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 break;
267 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smith534986f2012-04-14 00:33:13 +0000268 Res = ParseContinueStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000269 SemiError = "continue";
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 break;
271 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smith534986f2012-04-14 00:33:13 +0000272 Res = ParseBreakStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000273 SemiError = "break";
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 break;
275 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smith534986f2012-04-14 00:33:13 +0000276 Res = ParseReturnStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000277 SemiError = "return";
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 break;
Sebastian Redl61364dd2008-12-11 19:30:53 +0000279
Sebastian Redla0fd8652008-12-21 16:41:36 +0000280 case tok::kw_asm: {
Richard Smith534986f2012-04-14 00:33:13 +0000281 ProhibitAttributes(Attrs);
Steve Naroffd62701b2008-02-07 03:50:06 +0000282 bool msAsm = false;
283 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +0000284 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000285 if (msAsm) return Res;
Chris Lattner6869d8e2009-06-14 00:07:48 +0000286 SemiError = "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 break;
288 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000289
Sebastian Redla0fd8652008-12-21 16:41:36 +0000290 case tok::kw_try: // C++ 15: try-block
Richard Smith534986f2012-04-14 00:33:13 +0000291 return ParseCXXTryBlock();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000292
293 case tok::kw___try:
Richard Smith534986f2012-04-14 00:33:13 +0000294 ProhibitAttributes(Attrs); // TODO: is it correct?
295 return ParseSEHTryBlock();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000296
297 case tok::annot_pragma_vis:
Richard Smith534986f2012-04-14 00:33:13 +0000298 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000299 HandlePragmaVisibility();
300 return StmtEmpty();
301
302 case tok::annot_pragma_pack:
Richard Smith534986f2012-04-14 00:33:13 +0000303 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000304 HandlePragmaPack();
305 return StmtEmpty();
Eli Friedman9595c7e2012-10-04 02:36:51 +0000306
Eli Friedman8b2bfdd2012-10-09 22:46:54 +0000307 case tok::annot_pragma_msstruct:
308 ProhibitAttributes(Attrs);
309 HandlePragmaMSStruct();
310 return StmtEmpty();
311
Eli Friedman3ef38ee2012-10-08 23:52:38 +0000312 case tok::annot_pragma_align:
313 ProhibitAttributes(Attrs);
314 HandlePragmaAlign();
315 return StmtEmpty();
316
Eli Friedman8b2bfdd2012-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 Friedman9595c7e2012-10-04 02:36:51 +0000332 case tok::annot_pragma_fp_contract:
Richard Smithaed01162013-11-15 21:10:54 +0000333 ProhibitAttributes(Attrs);
Lang Hames860022c2012-10-21 01:10:01 +0000334 Diag(Tok, diag::err_pragma_fp_contract_scope);
335 ConsumeToken();
336 return StmtError();
337
Eli Friedman9595c7e2012-10-04 02:36:51 +0000338 case tok::annot_pragma_opencl_extension:
339 ProhibitAttributes(Attrs);
340 HandlePragmaOpenCLExtension();
341 return StmtEmpty();
Alexey Bataevc6400582013-03-22 06:34:35 +0000342
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000343 case tok::annot_pragma_captured:
Richard Smith175d4172013-09-16 21:17:44 +0000344 ProhibitAttributes(Attrs);
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000345 return HandlePragmaCaptured();
346
Alexey Bataevc6400582013-03-22 06:34:35 +0000347 case tok::annot_pragma_openmp:
Richard Smith175d4172013-09-16 21:17:44 +0000348 ProhibitAttributes(Attrs);
Alexey Bataev4fa7eab2013-07-19 03:13:43 +0000349 return ParseOpenMPDeclarativeOrExecutableDirective();
350
Stephen Hines651f13c2014-04-23 16:59:28 -0700351 case tok::annot_pragma_ms_pointers_to_members:
352 ProhibitAttributes(Attrs);
353 HandlePragmaMSPointersToMembers();
354 return StmtEmpty();
355
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700356 case tok::annot_pragma_ms_pragma:
357 ProhibitAttributes(Attrs);
358 HandlePragmaMSPragma();
359 return StmtEmpty();
Sebastian Redla0fd8652008-12-21 16:41:36 +0000360 }
361
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // If we reached this code, the statement must end in a semicolon.
Stephen Hines651f13c2014-04-23 16:59:28 -0700363 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner7b3684a2009-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 Lattner19504402008-11-13 18:52:53 +0000368 // Skip until we see a } or ;, but don't eat it.
Alexey Bataev8fe24752013-11-18 08:17:37 +0000369 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000372 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000373}
374
Douglas Gregor312eadb2011-04-24 05:37:28 +0000375/// \brief Parse an expression statement.
Richard Smith534986f2012-04-14 00:33:13 +0000376StmtResult Parser::ParseExprStatement() {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000377 // If a case keyword is missing, this is where it should be inserted.
378 Token OldToken = Tok;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000379
Douglas Gregor312eadb2011-04-24 05:37:28 +0000380 // expression[opt] ';'
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000381 ExprResult Expr(ParseExpression());
Douglas Gregor312eadb2011-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 Bataev8fe24752013-11-18 08:17:37 +0000386 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000387 if (Tok.is(tok::semi))
388 ConsumeToken();
John McCallb760f112013-03-22 02:10:40 +0000389 return Actions.ActOnExprStmtError();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000390 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000391
Douglas Gregor312eadb2011-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 Takumia789ca92011-10-08 11:31:46 +0000398
Douglas Gregor312eadb2011-04-24 05:37:28 +0000399 // Recover parsing as a case statement.
Richard Smith534986f2012-04-14 00:33:13 +0000400 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000401 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000402
Douglas Gregor312eadb2011-04-24 05:37:28 +0000403 // Otherwise, eat the semicolon.
404 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000405 return Actions.ActOnExprStmt(Expr);
John Wiegley28bbe4b2011-04-28 01:08:34 +0000406}
Douglas Gregor312eadb2011-04-24 05:37:28 +0000407
Richard Smith534986f2012-04-14 00:33:13 +0000408StmtResult Parser::ParseSEHTryBlock() {
John Wiegley28bbe4b2011-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))
Stephen Hines651f13c2014-04-23 16:59:28 -0700425 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley28bbe4b2011-04-28 01:08:34 +0000426
Joao Matos568ba872012-09-04 17:49:35 +0000427 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000428 if(TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000429 return TryBlock;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000430
431 StmtResult Handler;
Richard Smith534986f2012-04-14 00:33:13 +0000432 if (Tok.is(tok::identifier) &&
Douglas Gregorb57791e2011-10-21 03:57:52 +0000433 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-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 Kramer3fe198b2012-08-23 21:35:17 +0000444 return Handler;
John Wiegley28bbe4b2011-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
Stephen Hines651f13c2014-04-23 16:59:28 -0700462 if (ExpectAndConsume(tok::l_paren))
John Wiegley28bbe4b2011-04-28 01:08:34 +0000463 return StmtError();
464
465 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
466
David Blaikie4e4d0842012-03-11 07:00:24 +0000467 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000468 Ident__exception_info->setIsPoisoned(false);
469 Ident___exception_info->setIsPoisoned(false);
470 Ident_GetExceptionInfo->setIsPoisoned(false);
471 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000472 ExprResult FilterExpr(ParseExpression());
Francois Pichetd7f02df2011-04-28 03:14:31 +0000473
David Blaikie4e4d0842012-03-11 07:00:24 +0000474 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000475 Ident__exception_info->setIsPoisoned(true);
476 Ident___exception_info->setIsPoisoned(true);
477 Ident_GetExceptionInfo->setIsPoisoned(true);
478 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000479
480 if(FilterExpr.isInvalid())
481 return StmtError();
482
Stephen Hines651f13c2014-04-23 16:59:28 -0700483 if (ExpectAndConsume(tok::r_paren))
John Wiegley28bbe4b2011-04-28 01:08:34 +0000484 return StmtError();
485
Richard Smith534986f2012-04-14 00:33:13 +0000486 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000487
488 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000489 return Block;
John Wiegley28bbe4b2011-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 Smith534986f2012-04-14 00:33:13 +0000504 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000505 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000506 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000507
508 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000509}
510
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000511/// ParseLabeledStatement - We have an identifier and a ':' after it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000512///
513/// labeled-statement:
514/// identifier ':' statement
515/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000516///
Richard Smith534986f2012-04-14 00:33:13 +0000517StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidisf7da7262008-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 Redl61364dd2008-12-11 19:30:53 +0000525
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000526 // identifier ':' statement
527 SourceLocation ColonLoc = ConsumeToken();
528
Richard Smith93982a72013-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 Kyrtzidisf7da7262008-07-09 22:53:07 +0000534
Richard Smith93982a72013-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(
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700551 Stmts, /*OnlyStmts*/ true, nullptr, TempAttrs);
Richard Smith93982a72013-11-15 22:45:29 +0000552 if (!TempAttrs.empty() && !SubStmt.isInvalid())
553 SubStmt = Actions.ProcessStmtAttributes(
554 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
555 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -0700556 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smith93982a72013-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 Redl0e9eabc2008-12-09 13:15:23 +0000563
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000564 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000565 if (SubStmt.isInvalid())
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000566 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000567
Chris Lattner337e5502011-02-18 01:27:55 +0000568 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
569 IdentTok.getLocation());
Richard Smith534986f2012-04-14 00:33:13 +0000570 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattner337e5502011-02-18 01:27:55 +0000571 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smith534986f2012-04-14 00:33:13 +0000572 attrs.clear();
573 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000574
Chris Lattner337e5502011-02-18 01:27:55 +0000575 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
576 SubStmt.get());
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000577}
Reid Spencer5f016e22007-07-11 17:01:13 +0000578
579/// ParseCaseStatement
580/// labeled-statement:
581/// 'case' constant-expression ':' statement
582/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
583///
Richard Smith534986f2012-04-14 00:33:13 +0000584StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smith46f11102011-04-21 22:48:40 +0000585 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner24e1e702009-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 Lattner26140c62009-03-04 18:24:58 +0000597 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner24e1e702009-03-04 04:23:07 +0000598 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smith93982a72013-11-15 22:45:29 +0000599 // weirdness in the actions), so this is just local grossness :).
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattner24e1e702009-03-04 04:23:07 +0000601 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
602 // example above.
John McCall60d7b3a2010-08-24 06:29:42 +0000603 StmtResult TopLevelCase(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Chris Lattner24e1e702009-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.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700608 Stmt *DeepestParsedCaseStmt = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattner24e1e702009-03-04 04:23:07 +0000610 // While we have case statements, eat and stack them.
David Majnemer0e1e69c2011-06-13 05:50:12 +0000611 SourceLocation ColonLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000612 do {
Richard Trieubb9b80c2011-04-21 21:44:26 +0000613 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
614 ConsumeToken(); // eat the 'case'.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700615 ColonLoc = SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000617 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000618 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000619 cutOffParsing();
620 return StmtError();
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000621 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000622
Chris Lattner6fb09c82009-12-10 00:38:54 +0000623 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
624 /// Disable this form of error recovery while we're parsing the case
625 /// expression.
626 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000627
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700628 ExprResult LHS;
629 if (!MissingCase) {
630 LHS = ParseConstantExpression();
631 if (LHS.isInvalid()) {
632 // If constant-expression is parsed unsuccessfully, recover by skipping
633 // current case statement (moving to the colon that ends it).
634 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
635 TryConsumeToken(tok::colon, ColonLoc);
636 continue;
637 }
638 return StmtError();
639 }
640 } else {
641 LHS = Expr;
642 MissingCase = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000644
Chris Lattner24e1e702009-03-04 04:23:07 +0000645 // GNU case range extension.
646 SourceLocation DotDotDotLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000647 ExprResult RHS;
Stephen Hines651f13c2014-04-23 16:59:28 -0700648 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
649 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Chris Lattner24e1e702009-03-04 04:23:07 +0000650 RHS = ParseConstantExpression();
651 if (RHS.isInvalid()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700652 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
653 TryConsumeToken(tok::colon, ColonLoc);
654 continue;
655 }
Chris Lattner24e1e702009-03-04 04:23:07 +0000656 return StmtError();
657 }
658 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000659
Chris Lattner6fb09c82009-12-10 00:38:54 +0000660 ColonProtection.restore();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000661
Stephen Hines651f13c2014-04-23 16:59:28 -0700662 if (TryConsumeToken(tok::colon, ColonLoc)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700663 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
664 TryConsumeToken(tok::coloncolon, ColonLoc)) {
665 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Stephen Hines651f13c2014-04-23 16:59:28 -0700666 Diag(ColonLoc, diag::err_expected_after)
667 << "'case'" << tok::colon
668 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCallf6a3ab02011-01-22 09:28:32 +0000669 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000670 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Stephen Hines651f13c2014-04-23 16:59:28 -0700671 Diag(ExpectedLoc, diag::err_expected_after)
672 << "'case'" << tok::colon
673 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor662a4822010-12-23 22:56:40 +0000674 ColonLoc = ExpectedLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000675 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000676
John McCall60d7b3a2010-08-24 06:29:42 +0000677 StmtResult Case =
John McCall9ae2f072010-08-23 23:25:46 +0000678 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
679 RHS.get(), ColonLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Chris Lattner24e1e702009-03-04 04:23:07 +0000681 // If we had a sema error parsing this case, then just ignore it and
682 // continue parsing the sub-stmt.
683 if (Case.isInvalid()) {
684 if (TopLevelCase.isInvalid()) // No parsed case stmts.
685 return ParseStatement();
686 // Otherwise, just don't add it as a nested case.
687 } else {
688 // If this is the first case statement we parsed, it becomes TopLevelCase.
689 // Otherwise we link it into the current chain.
John McCallca0408f2010-08-23 06:44:23 +0000690 Stmt *NextDeepest = Case.get();
Chris Lattner24e1e702009-03-04 04:23:07 +0000691 if (TopLevelCase.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000692 TopLevelCase = Case;
Chris Lattner24e1e702009-03-04 04:23:07 +0000693 else
John McCall9ae2f072010-08-23 23:25:46 +0000694 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner24e1e702009-03-04 04:23:07 +0000695 DeepestParsedCaseStmt = NextDeepest;
696 }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattner24e1e702009-03-04 04:23:07 +0000698 // Handle all case statements.
699 } while (Tok.is(tok::kw_case));
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Chris Lattner24e1e702009-03-04 04:23:07 +0000701 // If we found a non-case statement, start by parsing it.
John McCall60d7b3a2010-08-24 06:29:42 +0000702 StmtResult SubStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattner24e1e702009-03-04 04:23:07 +0000704 if (Tok.isNot(tok::r_brace)) {
705 SubStmt = ParseStatement();
706 } else {
707 // Nicely diagnose the common error "switch (X) { case 4: }", which is
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700708 // not valid. If ColonLoc doesn't point to a valid text location, there was
709 // another parsing error, so avoid producing extra diagnostics.
710 if (ColonLoc.isValid()) {
711 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
712 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
713 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
714 }
715 SubStmt = StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattner24e1e702009-03-04 04:23:07 +0000718 // Install the body into the most deeply-nested case.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700719 if (DeepestParsedCaseStmt) {
720 // Broken sub-stmt shouldn't prevent forming the case statement properly.
721 if (SubStmt.isInvalid())
722 SubStmt = Actions.ActOnNullStmt(SourceLocation());
723 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
724 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000725
Chris Lattner24e1e702009-03-04 04:23:07 +0000726 // Return the top level parsed statement tree.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000727 return TopLevelCase;
Reid Spencer5f016e22007-07-11 17:01:13 +0000728}
729
730/// ParseDefaultStatement
731/// labeled-statement:
732/// 'default' ':' statement
733/// Note that this does not parse the 'statement' at the end.
734///
Richard Smith534986f2012-04-14 00:33:13 +0000735StmtResult Parser::ParseDefaultStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000736 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
738
Douglas Gregor662a4822010-12-23 22:56:40 +0000739 SourceLocation ColonLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -0700740 if (TryConsumeToken(tok::colon, ColonLoc)) {
741 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
742 // Treat "default;" as a typo for "default:".
743 Diag(ColonLoc, diag::err_expected_after)
744 << "'default'" << tok::colon
745 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCallf6a3ab02011-01-22 09:28:32 +0000746 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000747 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Stephen Hines651f13c2014-04-23 16:59:28 -0700748 Diag(ExpectedLoc, diag::err_expected_after)
749 << "'default'" << tok::colon
750 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor662a4822010-12-23 22:56:40 +0000751 ColonLoc = ExpectedLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000753
Richard Smith85b29a42012-02-17 01:35:32 +0000754 StmtResult SubStmt;
755
756 if (Tok.isNot(tok::r_brace)) {
757 SubStmt = ParseStatement();
758 } else {
759 // Diagnose the common error "switch (X) {... default: }", which is
760 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000761 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000762 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
763 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
764 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 }
766
Richard Smith85b29a42012-02-17 01:35:32 +0000767 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000768 if (SubStmt.isInvalid())
Richard Smith85b29a42012-02-17 01:35:32 +0000769 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000770
Sebastian Redl117054a2008-12-28 16:13:43 +0000771 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000772 SubStmt.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +0000773}
774
Richard Smith534986f2012-04-14 00:33:13 +0000775StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
776 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregorbca01b42011-07-06 22:04:06 +0000777}
Reid Spencer5f016e22007-07-11 17:01:13 +0000778
779/// ParseCompoundStatement - Parse a "{}" block.
780///
781/// compound-statement: [C99 6.8.2]
782/// { block-item-list[opt] }
783/// [GNU] { label-declarations block-item-list } [TODO]
784///
785/// block-item-list:
786/// block-item
787/// block-item-list block-item
788///
789/// block-item:
790/// declaration
Chris Lattner45a566c2007-08-27 01:01:57 +0000791/// [GNU] '__extension__' declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000792/// statement
793/// [OMP] openmp-directive [TODO]
794///
795/// [GNU] label-declarations:
796/// [GNU] label-declaration
797/// [GNU] label-declarations label-declaration
798///
799/// [GNU] label-declaration:
800/// [GNU] '__label__' identifier-list ';'
801///
802/// [OMP] openmp-directive: [TODO]
803/// [OMP] barrier-directive
804/// [OMP] flush-directive
805///
Richard Smith534986f2012-04-14 00:33:13 +0000806StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000807 unsigned ScopeFlags) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000808 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000809
Chris Lattner31e05722007-08-26 06:24:45 +0000810 // Enter a scope to hold everything within the compound stmt. Compound
811 // statements can always hold declarations.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000812 ParseScope CompoundScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813
814 // Parse the statements in the body.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000815 return ParseCompoundStatementBody(isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000816}
817
Lang Hamesa60d21d2012-11-03 22:29:05 +0000818/// Parse any pragmas at the start of the compound expression. We handle these
819/// separately since some pragmas (FP_CONTRACT) must appear before any C
820/// statement in the compound, but may be intermingled with other pragmas.
821void Parser::ParseCompoundStatementLeadingPragmas() {
822 bool checkForPragmas = true;
823 while (checkForPragmas) {
824 switch (Tok.getKind()) {
825 case tok::annot_pragma_vis:
826 HandlePragmaVisibility();
827 break;
828 case tok::annot_pragma_pack:
829 HandlePragmaPack();
830 break;
831 case tok::annot_pragma_msstruct:
832 HandlePragmaMSStruct();
833 break;
834 case tok::annot_pragma_align:
835 HandlePragmaAlign();
836 break;
837 case tok::annot_pragma_weak:
838 HandlePragmaWeak();
839 break;
840 case tok::annot_pragma_weakalias:
841 HandlePragmaWeakAlias();
842 break;
843 case tok::annot_pragma_redefine_extname:
844 HandlePragmaRedefineExtname();
845 break;
846 case tok::annot_pragma_opencl_extension:
847 HandlePragmaOpenCLExtension();
848 break;
849 case tok::annot_pragma_fp_contract:
850 HandlePragmaFPContract();
851 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700852 case tok::annot_pragma_ms_pointers_to_members:
853 HandlePragmaMSPointersToMembers();
854 break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700855 case tok::annot_pragma_ms_pragma:
856 HandlePragmaMSPragma();
857 break;
Lang Hamesa60d21d2012-11-03 22:29:05 +0000858 default:
859 checkForPragmas = false;
860 break;
861 }
862 }
863
864}
865
Reid Spencer5f016e22007-07-11 17:01:13 +0000866/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff1b273c42007-09-16 14:56:35 +0000867/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Reid Spencer5f016e22007-07-11 17:01:13 +0000868/// consume the '}' at the end of the block. It does not manipulate the scope
869/// stack.
John McCall60d7b3a2010-08-24 06:29:42 +0000870StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump1eb44332009-09-09 15:08:12 +0000871 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerae50fa02009-03-05 00:00:31 +0000872 Tok.getLocation(),
873 "in compound statement ('{}')");
Lang Hamesbe9af122012-10-02 04:45:10 +0000874
875 // Record the state of the FP_CONTRACT pragma, restore on leaving the
876 // compound statement.
877 Sema::FPContractStateRAII SaveFPContractState(Actions);
878
Douglas Gregor0fbda682010-09-15 14:51:05 +0000879 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000880 BalancedDelimiterTracker T(*this, tok::l_brace);
881 if (T.consumeOpen())
882 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000883
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000884 Sema::CompoundScopeRAII CompoundScope(Actions);
885
Lang Hamesa60d21d2012-11-03 22:29:05 +0000886 // Parse any pragmas at the beginning of the compound statement.
887 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000888
Lang Hamesa60d21d2012-11-03 22:29:05 +0000889 StmtVector Stmts;
Lang Hames860022c2012-10-21 01:10:01 +0000890
Chris Lattner4ae493c2011-02-18 02:08:43 +0000891 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
892 // only allowed at the start of a compound stmt regardless of the language.
893 while (Tok.is(tok::kw___label__)) {
894 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000895
Chris Lattner5f9e2722011-07-23 10:55:15 +0000896 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000897 while (1) {
898 if (Tok.isNot(tok::identifier)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700899 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000900 break;
901 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000902
Chris Lattner4ae493c2011-02-18 02:08:43 +0000903 IdentifierInfo *II = Tok.getIdentifierInfo();
904 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara67843042011-03-05 18:21:20 +0000905 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000906
Stephen Hines651f13c2014-04-23 16:59:28 -0700907 if (!TryConsumeToken(tok::comma))
Chris Lattner4ae493c2011-02-18 02:08:43 +0000908 break;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000909 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000910
John McCall0b7e6782011-03-24 11:26:52 +0000911 DeclSpec DS(AttrFactory);
Rafael Espindola4549d7f2013-07-09 12:05:01 +0000912 DeclGroupPtrTy Res =
913 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000914 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000915
Chris Lattner8bb21d32012-04-28 16:12:17 +0000916 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000917 if (R.isUsable())
918 Stmts.push_back(R.release());
919 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000920
Stephen Hines651f13c2014-04-23 16:59:28 -0700921 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000922 if (Tok.is(tok::annot_pragma_unused)) {
923 HandlePragmaUnused();
924 continue;
925 }
926
David Blaikie4e4d0842012-03-11 07:00:24 +0000927 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet1e862692011-05-06 20:48:22 +0000928 Tok.is(tok::kw___if_not_exists))) {
929 ParseMicrosoftIfExistsStatement(Stmts);
930 continue;
931 }
932
John McCall60d7b3a2010-08-24 06:29:42 +0000933 StmtResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000934 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000935 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattner45a566c2007-08-27 01:01:57 +0000936 } else {
937 // __extension__ can start declarations and it can also be a unary
938 // operator for expressions. Consume multiple __extension__ markers here
939 // until we can determine which is which.
Eli Friedmanadf077f2009-01-27 08:43:38 +0000940 // FIXME: This loses extension expressions in the AST!
Chris Lattner45a566c2007-08-27 01:01:57 +0000941 SourceLocation ExtLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000942 while (Tok.is(tok::kw___extension__))
Chris Lattner45a566c2007-08-27 01:01:57 +0000943 ConsumeToken();
Chris Lattner39146d62008-10-20 06:51:33 +0000944
John McCall0b7e6782011-03-24 11:26:52 +0000945 ParsedAttributesWithRange attrs(AttrFactory);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700946 MaybeParseCXX11Attributes(attrs, nullptr,
947 /*MightBeObjCMessageSend*/ true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000948
Chris Lattner45a566c2007-08-27 01:01:57 +0000949 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis5404a152008-10-05 00:06:24 +0000950 if (isDeclarationStatement()) {
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000951 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner97144fc2009-04-02 04:16:50 +0000952 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000953 ExtensionRAIIObject O(Diags);
954
Chris Lattner97144fc2009-04-02 04:16:50 +0000955 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000956 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
957 Declarator::BlockContext, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000958 attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000959 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattner45a566c2007-08-27 01:01:57 +0000960 } else {
Eli Friedmanadf077f2009-01-27 08:43:38 +0000961 // Otherwise this was a unary __extension__ marker.
John McCall60d7b3a2010-08-24 06:29:42 +0000962 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattner043a0b52008-03-13 06:32:11 +0000963
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000964 if (Res.isInvalid()) {
Chris Lattner45a566c2007-08-27 01:01:57 +0000965 SkipUntil(tok::semi);
966 continue;
967 }
Sebastian Redlf512e822009-01-18 18:03:53 +0000968
Sean Huntbbd37c62009-11-21 08:43:09 +0000969 // FIXME: Use attributes?
Chris Lattner39146d62008-10-20 06:51:33 +0000970 // Eat the semicolon at the end of stmt and convert the expr into a
971 // statement.
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000972 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000973 R = Actions.ActOnExprStmt(Res);
Chris Lattner45a566c2007-08-27 01:01:57 +0000974 }
975 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000976
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000977 if (R.isUsable())
Sebastian Redleffa8d12008-12-10 00:02:53 +0000978 Stmts.push_back(R.release());
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000980
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000981 SourceLocation CloseLoc = Tok.getLocation();
982
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 // We broke out of the while loop because we found a '}' or EOF.
Nico Weberd11f4352012-12-30 23:36:56 +0000984 if (!T.consumeClose())
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000985 // Recover by creating a compound statement with what we parsed so far,
986 // instead of dropping everything and returning StmtError();
Nico Weberd11f4352012-12-30 23:36:56 +0000987 CloseLoc = T.getCloseLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000988
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000989 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000990 Stmts, isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000991}
992
Chris Lattner15ff1112008-12-12 06:31:07 +0000993/// ParseParenExprOrCondition:
994/// [C ] '(' expression ')'
Chris Lattnerff871fb2008-12-12 06:35:28 +0000995/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattner15ff1112008-12-12 06:31:07 +0000996///
997/// This function parses and performs error recovery on the specified condition
998/// or expression (depending on whether we're in C++ or C mode). This function
999/// goes out of its way to recover well. It returns true if there was a parser
1000/// error (the right paren couldn't be found), which indicates that the caller
1001/// should try to recover harder. It returns false if the condition is
1002/// successfully parsed. Note that a successful parse can still have semantic
1003/// errors in the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001004bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCalld226f652010-08-21 09:40:31 +00001005 Decl *&DeclResult,
Douglas Gregor586596f2010-05-06 17:25:47 +00001006 SourceLocation Loc,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001007 bool ConvertToBoolean) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001008 BalancedDelimiterTracker T(*this, tok::l_paren);
1009 T.consumeOpen();
1010
David Blaikie4e4d0842012-03-11 07:00:24 +00001011 if (getLangOpts().CPlusPlus)
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001012 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001013 else {
1014 ExprResult = ParseExpression();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001015 DeclResult = nullptr;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001016
Douglas Gregor586596f2010-05-06 17:25:47 +00001017 // If required, convert to a boolean value.
1018 if (!ExprResult.isInvalid() && ConvertToBoolean)
1019 ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00001020 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001021 }
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chris Lattner15ff1112008-12-12 06:31:07 +00001023 // If the parser was confused by the condition and we don't have a ')', try to
1024 // recover by skipping ahead to a semi and bailing out. If condexp is
1025 // semantically invalid but we have well formed code, keep going.
John McCalld226f652010-08-21 09:40:31 +00001026 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattner15ff1112008-12-12 06:31:07 +00001027 SkipUntil(tok::semi);
1028 // Skipping may have stopped if it found the containing ')'. If so, we can
1029 // continue parsing the if statement.
1030 if (Tok.isNot(tok::r_paren))
1031 return true;
1032 }
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Chris Lattner15ff1112008-12-12 06:31:07 +00001034 // Otherwise the condition is valid or the rparen is present.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001035 T.consumeClose();
Chad Rosierb6604462012-07-10 21:35:27 +00001036
Chris Lattnerbddc7e52012-04-28 16:24:20 +00001037 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1038 // that all callers are looking for a statement after the condition, so ")"
1039 // isn't valid.
1040 while (Tok.is(tok::r_paren)) {
1041 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1042 << FixItHint::CreateRemoval(Tok.getLocation());
1043 ConsumeParen();
1044 }
Chad Rosierb6604462012-07-10 21:35:27 +00001045
Chris Lattner15ff1112008-12-12 06:31:07 +00001046 return false;
1047}
1048
1049
Reid Spencer5f016e22007-07-11 17:01:13 +00001050/// ParseIfStatement
1051/// if-statement: [C99 6.8.4.1]
1052/// 'if' '(' expression ')' statement
1053/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001054/// [C++] 'if' '(' condition ')' statement
1055/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +00001056///
Richard Smith534986f2012-04-14 00:33:13 +00001057StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001058 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1060
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001061 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001062 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +00001063 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +00001064 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001066
David Blaikie4e4d0842012-03-11 07:00:24 +00001067 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001068
Chris Lattner22153252007-08-26 23:08:06 +00001069 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1070 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001071 //
1072 // C++ 6.4p3:
1073 // A name introduced by a declaration in a condition is in scope from its
1074 // point of declaration until the end of the substatements controlled by the
1075 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001076 // C++ 3.3.2p4:
1077 // Names declared in the for-init-statement, and in the condition of if,
1078 // while, for, and switch statements are local to the if, while, for, or
1079 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001080 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001081 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +00001082
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001084 ExprResult CondExp;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001085 Decl *CondVar = nullptr;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001086 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001087 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +00001088
David Blaikiedef07622012-05-16 04:20:04 +00001089 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Chris Lattner0ecea032007-08-22 05:28:50 +00001091 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001092 // there is no compound stmt. C90 does not have this clause. We only do this
1093 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001094 //
1095 // C++ 6.4p1:
1096 // The substatement in a selection-statement (each substatement, in the else
1097 // form of the if statement) implicitly defines a local scope.
1098 //
1099 // For C++ we create a scope for the condition and a new scope for
1100 // substatements because:
1101 // -When the 'then' scope exits, we want the condition declaration to still be
1102 // active for the 'else' scope too.
1103 // -Sema will detect name clashes by considering declarations of a
1104 // 'ControlScope' as part of its direct subscope.
1105 // -If we wanted the condition and substatement to be in the same scope, we
1106 // would have to notify ParseStatement not to create a new scope. It's
1107 // simpler to let it create a new scope.
1108 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001109 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001110
Chris Lattnerb96728d2007-10-29 05:08:52 +00001111 // Read the 'then' stmt.
1112 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +00001113
1114 SourceLocation InnerStatementTrailingElseLoc;
1115 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001116
Chris Lattnera36ce712007-08-22 05:16:28 +00001117 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001118 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 // If it has an else, parse it.
1121 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +00001122 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +00001123 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001124
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001125 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +00001126 if (TrailingElseLoc)
1127 *TrailingElseLoc = Tok.getLocation();
1128
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +00001130 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001131
Chris Lattner0ecea032007-08-22 05:28:50 +00001132 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001133 // there is no compound stmt. C90 does not have this clause. We only do
1134 // this if the body isn't a compound statement to avoid push/pop in common
1135 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001136 //
1137 // C++ 6.4p1:
1138 // The substatement in a selection-statement (each substatement, in the else
1139 // form of the if statement) implicitly defines a local scope.
1140 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001141 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001142
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001144
Chris Lattnera36ce712007-08-22 05:16:28 +00001145 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001146 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +00001147 } else if (Tok.is(tok::code_completion)) {
1148 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001149 cutOffParsing();
1150 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +00001151 } else if (InnerStatementTrailingElseLoc.isValid()) {
1152 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001154
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001155 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Chris Lattnerb96728d2007-10-29 05:08:52 +00001157 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +00001158 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +00001159 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001160 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001161 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1162 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +00001163 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +00001164 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +00001165 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001166
Chris Lattnerb96728d2007-10-29 05:08:52 +00001167 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001168 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001169 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001170 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001171 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001172
John McCall9ae2f072010-08-23 23:25:46 +00001173 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001174 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001175}
1176
1177/// ParseSwitchStatement
1178/// switch-statement:
1179/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001180/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001181StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001182 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1184
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001185 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001186 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001188 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 }
Chris Lattner22153252007-08-26 23:08:06 +00001190
David Blaikie4e4d0842012-03-11 07:00:24 +00001191 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001192
Chris Lattner22153252007-08-26 23:08:06 +00001193 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1194 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001195 //
1196 // C++ 6.4p3:
1197 // A name introduced by a declaration in a condition is in scope from its
1198 // point of declaration until the end of the substatements controlled by the
1199 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001200 // C++ 3.3.2p4:
1201 // Names declared in the for-init-statement, and in the condition of if,
1202 // while, for, and switch statements are local to the if, while, for, or
1203 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001204 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001205 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001206 if (C99orCXX)
1207 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001208 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001209
1210 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001211 ExprResult Cond;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001212 Decl *CondVar = nullptr;
Douglas Gregor586596f2010-05-06 17:25:47 +00001213 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001214 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001215
John McCall60d7b3a2010-08-24 06:29:42 +00001216 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001217 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001218
Douglas Gregor586596f2010-05-06 17:25:47 +00001219 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001220 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001221 // FIXME: This is not optimal recovery, but parsing the body is more
1222 // dangerous due to the presence of case and default statements, which
1223 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001224 if (Tok.is(tok::l_brace)) {
1225 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001226 SkipUntil(tok::r_brace);
Douglas Gregor4186ff42010-05-20 23:20:59 +00001227 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001228 SkipUntil(tok::semi);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001229 return Switch;
Douglas Gregor586596f2010-05-06 17:25:47 +00001230 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001231
Chris Lattner0ecea032007-08-22 05:28:50 +00001232 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001233 // there is no compound stmt. C90 does not have this clause. We only do this
1234 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001235 //
1236 // C++ 6.4p1:
1237 // The substatement in a selection-statement (each substatement, in the else
1238 // form of the if statement) implicitly defines a local scope.
1239 //
1240 // See comments in ParseIfStatement for why we create a scope for the
1241 // condition and a new scope for substatement in C++.
1242 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001243 getCurScope()->AddFlags(Scope::BreakScope);
1244 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001245
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001247 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001248
Chris Lattner7e52de42010-01-24 01:50:29 +00001249 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001250 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001251 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001252
John McCall9ae2f072010-08-23 23:25:46 +00001253 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001254}
1255
1256/// ParseWhileStatement
1257/// while-statement: [C99 6.8.5.1]
1258/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001259/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001260StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001261 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 SourceLocation WhileLoc = Tok.getLocation();
1263 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001264
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001265 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001266 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001268 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001270
David Blaikie4e4d0842012-03-11 07:00:24 +00001271 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001272
Chris Lattner22153252007-08-26 23:08:06 +00001273 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1274 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001275 //
1276 // C++ 6.4p3:
1277 // A name introduced by a declaration in a condition is in scope from its
1278 // point of declaration until the end of the substatements controlled by the
1279 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001280 // C++ 3.3.2p4:
1281 // Names declared in the for-init-statement, and in the condition of if,
1282 // while, for, and switch statements are local to the if, while, for, or
1283 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001284 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001285 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001286 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001287 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1288 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001289 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001290 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1291 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001292
1293 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001294 ExprResult Cond;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001295 Decl *CondVar = nullptr;
Douglas Gregor586596f2010-05-06 17:25:47 +00001296 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001297 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001298
David Blaikiedef07622012-05-16 04:20:04 +00001299 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Stephen Hines651f13c2014-04-23 16:59:28 -07001301 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001302 // there is no compound stmt. C90 does not have this clause. We only do this
1303 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001304 //
1305 // C++ 6.5p2:
1306 // The substatement in an iteration-statement implicitly defines a local scope
1307 // which is entered and exited each time through the loop.
1308 //
1309 // See comments in ParseIfStatement for why we create a scope for the
1310 // condition and a new scope for substatement in C++.
1311 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001312 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001313
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001315 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001316
Chris Lattner0ecea032007-08-22 05:28:50 +00001317 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001318 InnerScope.Exit();
1319 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001320
John McCalld226f652010-08-21 09:40:31 +00001321 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001322 return StmtError();
1323
John McCall9ae2f072010-08-23 23:25:46 +00001324 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001325}
1326
1327/// ParseDoStatement
1328/// do-statement: [C99 6.8.5.2]
1329/// 'do' statement 'while' '(' expression ')' ';'
1330/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001331StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001332 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001334
Chris Lattner22153252007-08-26 23:08:06 +00001335 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1336 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001337 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001338 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001339 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001340 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001341 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001342
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001343 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001344
Stephen Hines651f13c2014-04-23 16:59:28 -07001345 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001346 // there is no compound stmt. C90 does not have this clause. We only do this
1347 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001348 //
1349 // C++ 6.5p2:
1350 // The substatement in an iteration-statement implicitly defines a local scope
1351 // which is entered and exited each time through the loop.
1352 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001353 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1354 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001355
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001357 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001358
Chris Lattner0ecea032007-08-22 05:28:50 +00001359 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001360 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001361
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001362 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001363 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001364 Diag(Tok, diag::err_expected_while);
Stephen Hines651f13c2014-04-23 16:59:28 -07001365 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataev8fe24752013-11-18 08:17:37 +00001366 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner19504402008-11-13 18:52:53 +00001367 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001368 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 }
1370 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001371
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001372 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001373 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataev8fe24752013-11-18 08:17:37 +00001374 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001375 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001377
Richard Smith5eed7e02013-10-15 01:34:54 +00001378 // Parse the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001379 BalancedDelimiterTracker T(*this, tok::l_paren);
1380 T.consumeOpen();
Chad Rosierb6604462012-07-10 21:35:27 +00001381
Richard Smith5eed7e02013-10-15 01:34:54 +00001382 // A do-while expression is not a condition, so can't have attributes.
1383 DiagnoseAndSkipCXX11Attributes();
Sean Hunt2edf0a22012-06-23 05:07:58 +00001384
John McCall60d7b3a2010-08-24 06:29:42 +00001385 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001386 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001387 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001388
Sebastian Redl9a920342008-12-11 19:48:14 +00001389 if (Cond.isInvalid() || Body.isInvalid())
1390 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001391
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001392 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1393 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001394}
1395
1396/// ParseForStatement
1397/// for-statement: [C99 6.8.5.3]
1398/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1399/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001400/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1401/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001402/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001403/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1404/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001405///
1406/// [C++] for-init-statement:
1407/// [C++] expression-statement
1408/// [C++] simple-declaration
1409///
Richard Smithad762fc2011-04-14 22:09:26 +00001410/// [C++0x] for-range-declaration:
1411/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1412/// [C++0x] for-range-initializer:
1413/// [C++0x] expression
1414/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001415StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001416 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001418
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001419 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001420 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001422 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001424
Chad Rosierb6604462012-07-10 21:35:27 +00001425 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1426 getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001427
Chris Lattner22153252007-08-26 23:08:06 +00001428 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1429 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001430 //
1431 // C++ 6.4p3:
1432 // A name introduced by a declaration in a condition is in scope from its
1433 // point of declaration until the end of the substatements controlled by the
1434 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001435 // C++ 3.3.2p4:
1436 // Names declared in the for-init-statement, and in the condition of if,
1437 // while, for, and switch statements are local to the if, while, for, or
1438 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001439 // C++ 6.5.3p1:
1440 // Names declared in the for-init-statement are in the same declarative-region
1441 // as those declared in the condition.
1442 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001443 unsigned ScopeFlags = 0;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001444 if (C99orCXXorObjC)
Stephen Hines651f13c2014-04-23 16:59:28 -07001445 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001446
1447 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001448
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001449 BalancedDelimiterTracker T(*this, tok::l_paren);
1450 T.consumeOpen();
1451
John McCall60d7b3a2010-08-24 06:29:42 +00001452 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001453
Richard Smithad762fc2011-04-14 22:09:26 +00001454 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001455 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001456 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001457 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001458 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001459 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001460 FullExprArg ThirdPart(Actions);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001461 Decl *SecondVar = nullptr;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001462
Douglas Gregor791215b2009-09-21 20:51:25 +00001463 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001464 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001465 C99orCXXorObjC? Sema::PCC_ForInit
1466 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001467 cutOffParsing();
1468 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001469 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001470
Sean Hunt2edf0a22012-06-23 05:07:58 +00001471 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001472 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001473
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001475 if (Tok.is(tok::semi)) { // for (;
Sean Hunt2edf0a22012-06-23 05:07:58 +00001476 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 // no first part, eat the ';'.
1478 ConsumeToken();
Eli Friedman9490ab42011-12-20 01:50:37 +00001479 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001481 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001483
Richard Smithad762fc2011-04-14 22:09:26 +00001484 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001485 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001486 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1487
Chris Lattner97144fc2009-04-02 04:16:50 +00001488 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001489 StmtVector Stmts;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001490 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1491 Stmts, Declarator::ForContext, DeclEnd, attrs, false,
1492 MightBeForRangeStmt ? &ForRangeInit : nullptr);
Chris Lattnercd147752009-03-29 17:27:48 +00001493 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Richard Smithad762fc2011-04-14 22:09:26 +00001494 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001495 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001496 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001497
Richard Smithad762fc2011-04-14 22:09:26 +00001498 ForRange = true;
1499 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001500 ConsumeToken();
1501 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001502 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001503 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001504 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001505
Douglas Gregorfb629412010-08-23 21:17:50 +00001506 if (Tok.is(tok::code_completion)) {
1507 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001508 cutOffParsing();
1509 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001510 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001511 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001512 } else {
1513 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001514 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 } else {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001516 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 Value = ParseExpression();
1518
John McCallf6a16482010-12-04 03:47:34 +00001519 ForEach = isTokIdentifier_in();
1520
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001522 if (!Value.isInvalid()) {
1523 if (ForEach)
1524 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1525 else
Richard Smith41956372013-01-14 22:39:08 +00001526 FirstPart = Actions.ActOnExprStmt(Value);
John McCallf6a16482010-12-04 03:47:34 +00001527 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001528
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001529 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001531 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001532 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001533
Douglas Gregorfb629412010-08-23 21:17:50 +00001534 if (Tok.is(tok::code_completion)) {
1535 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001536 cutOffParsing();
1537 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001538 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001539 Collection = ParseExpression();
Richard Smith80ad52f2013-01-02 11:42:31 +00001540 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001541 // User tried to write the reasonable, but ill-formed, for-range-statement
1542 // for (expr : expr) { ... }
1543 Diag(Tok, diag::err_for_range_expected_decl)
1544 << FirstPart.get()->getSourceRange();
Alexey Bataev8fe24752013-11-18 08:17:37 +00001545 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smitha44854a2011-12-20 22:56:20 +00001546 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001547 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001548 if (!Value.isInvalid()) {
1549 Diag(Tok, diag::err_expected_semi_for);
1550 } else {
1551 // Skip until semicolon or rparen, don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001552 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregorb72c7782011-02-17 03:38:46 +00001553 if (Tok.is(tok::semi))
1554 ConsumeToken();
1555 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 }
1557 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001558
1559 // Parse the second part of the for specifier.
1560 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smithad762fc2011-04-14 22:09:26 +00001561 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001562 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001563 // Parse the second part of the for specifier.
1564 if (Tok.is(tok::semi)) { // for (...;;
1565 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001566 } else if (Tok.is(tok::r_paren)) {
1567 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001568 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001569 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001570 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001571 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1572 else {
1573 Second = ParseExpression();
1574 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001575 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001576 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001577 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001578 SecondPartIsInvalid = Second.isInvalid();
David Blaikiedef07622012-05-16 04:20:04 +00001579 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001580 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001581
Douglas Gregorb72c7782011-02-17 03:38:46 +00001582 if (Tok.isNot(tok::semi)) {
1583 if (!SecondPartIsInvalid || SecondVar)
1584 Diag(Tok, diag::err_expected_semi_for);
1585 else
1586 // Skip until semicolon or rparen, don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001587 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregorb72c7782011-02-17 03:38:46 +00001588 }
1589
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001590 if (Tok.is(tok::semi)) {
1591 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001592 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001593
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001594 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001595 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001596 ExprResult Third = ParseExpression();
Richard Smith41956372013-01-14 22:39:08 +00001597 // FIXME: The C++11 standard doesn't actually say that this is a
1598 // discarded-value expression, but it clearly should be.
1599 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregor586596f2010-05-06 17:25:47 +00001600 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001603 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001604
Richard Smithad762fc2011-04-14 22:09:26 +00001605 // We need to perform most of the semantic analysis for a C++0x for-range
1606 // statememt before parsing the body, in order to be able to deduce the type
1607 // of an auto-typed loop variable.
1608 StmtResult ForRangeStmt;
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001609 StmtResult ForEachStmt;
Chad Rosierb6604462012-07-10 21:35:27 +00001610
John McCall990567c2011-07-27 01:07:15 +00001611 if (ForRange) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001612 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smithad762fc2011-04-14 22:09:26 +00001613 ForRangeInit.ColonLoc,
1614 ForRangeInit.RangeExpr.get(),
Richard Smith8b533d92012-09-20 21:52:32 +00001615 T.getCloseLocation(),
1616 Sema::BFRK_Build);
Richard Smithad762fc2011-04-14 22:09:26 +00001617
John McCall990567c2011-07-27 01:07:15 +00001618
1619 // Similarly, we need to do the semantic analysis for a for-range
1620 // statement immediately in order to close over temporaries correctly.
1621 } else if (ForEach) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001622 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001623 FirstPart.take(),
Chad Rosierb6604462012-07-10 21:35:27 +00001624 Collection.take(),
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001625 T.getCloseLocation());
John McCall990567c2011-07-27 01:07:15 +00001626 }
1627
Stephen Hines651f13c2014-04-23 16:59:28 -07001628 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001629 // there is no compound stmt. C90 does not have this clause. We only do this
1630 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001631 //
1632 // C++ 6.5p2:
1633 // The substatement in an iteration-statement implicitly defines a local scope
1634 // which is entered and exited each time through the loop.
1635 //
1636 // See comments in ParseIfStatement for why we create a scope for
1637 // for-init-statement/condition and a new scope for substatement in C++.
1638 //
Stephen Hines651f13c2014-04-23 16:59:28 -07001639 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1640 Tok.is(tok::l_brace));
1641
1642 // The body of the for loop has the same local mangling number as the
1643 // for-init-statement.
1644 // It will only be incremented if the body contains other things that would
1645 // normally increment the mangling number (like a compound statement).
1646 if (C99orCXXorObjC)
1647 getCurScope()->decrementMSLocalManglingNumber();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001648
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001650 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001651
Chris Lattner0ecea032007-08-22 05:28:50 +00001652 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001653 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001654
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001656 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001657
1658 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001659 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001660
Richard Smithad762fc2011-04-14 22:09:26 +00001661 if (ForEach)
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001662 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1663 Body.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Richard Smithad762fc2011-04-14 22:09:26 +00001665 if (ForRange)
1666 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1667
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001668 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1669 SecondPart, SecondVar, ThirdPart,
1670 T.getCloseLocation(), Body.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001671}
1672
1673/// ParseGotoStatement
1674/// jump-statement:
1675/// 'goto' identifier ';'
1676/// [GNU] 'goto' '*' expression ';'
1677///
1678/// Note: this lets the caller parse the end ';'.
1679///
Richard Smith534986f2012-04-14 00:33:13 +00001680StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001681 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001683
John McCall60d7b3a2010-08-24 06:29:42 +00001684 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001685 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001686 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1687 Tok.getLocation());
1688 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001690 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 // GNU indirect goto extension.
1692 Diag(Tok, diag::ext_gnu_indirect_goto);
1693 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001694 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001695 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataev8fe24752013-11-18 08:17:37 +00001696 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001697 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 }
John McCall9ae2f072010-08-23 23:25:46 +00001699 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattner95cfb852007-07-22 04:13:33 +00001700 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07001701 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redl9a920342008-12-11 19:48:14 +00001702 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001704
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001705 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +00001706}
1707
1708/// ParseContinueStatement
1709/// jump-statement:
1710/// 'continue' ';'
1711///
1712/// Note: this lets the caller parse the end ';'.
1713///
Richard Smith534986f2012-04-14 00:33:13 +00001714StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001716 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001717}
1718
1719/// ParseBreakStatement
1720/// jump-statement:
1721/// 'break' ';'
1722///
1723/// Note: this lets the caller parse the end ';'.
1724///
Richard Smith534986f2012-04-14 00:33:13 +00001725StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001727 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001728}
1729
1730/// ParseReturnStatement
1731/// jump-statement:
1732/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001733StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001734 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001736
John McCall60d7b3a2010-08-24 06:29:42 +00001737 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001738 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001739 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001740 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001741 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001742 return StmtError();
1743 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001744
David Blaikie4e4d0842012-03-11 07:00:24 +00001745 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001746 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001747 if (R.isUsable())
Richard Smith80ad52f2013-01-02 11:42:31 +00001748 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001749 diag::warn_cxx98_compat_generalized_initializer_lists :
1750 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001751 << R.get()->getSourceRange();
1752 } else
1753 R = ParseExpression();
Stephen Hines651f13c2014-04-23 16:59:28 -07001754 if (R.isInvalid()) {
1755 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redl9a920342008-12-11 19:48:14 +00001756 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 }
1758 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001759 return Actions.ActOnReturnStmt(ReturnLoc, R.take(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001760}
1761
John McCallaeeacf72013-05-03 00:10:13 +00001762namespace {
1763 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1764 Parser &TheParser;
1765 SourceLocation AsmLoc;
1766 StringRef AsmString;
1767
1768 /// The tokens we streamed into AsmString and handed off to MC.
1769 ArrayRef<Token> AsmToks;
1770
1771 /// The offset of each token in AsmToks within AsmString.
1772 ArrayRef<unsigned> AsmTokOffsets;
1773
1774 public:
1775 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1776 StringRef AsmString,
1777 ArrayRef<Token> Toks,
1778 ArrayRef<unsigned> Offsets)
1779 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1780 AsmToks(Toks), AsmTokOffsets(Offsets) {
1781 assert(AsmToks.size() == AsmTokOffsets.size());
1782 }
1783
1784 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1785 InlineAsmIdentifierInfo &Info,
Stephen Hines651f13c2014-04-23 16:59:28 -07001786 bool IsUnevaluatedContext) override {
John McCallaeeacf72013-05-03 00:10:13 +00001787 // Collect the desired tokens.
1788 SmallVector<Token, 16> LineToks;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001789 const Token *FirstOrigToken = nullptr;
John McCallaeeacf72013-05-03 00:10:13 +00001790 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1791
1792 unsigned NumConsumedToks;
1793 ExprResult Result =
1794 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1795 IsUnevaluatedContext);
1796
1797 // If we consumed the entire line, tell MC that.
1798 // Also do this if we consumed nothing as a way of reporting failure.
1799 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1800 // By not modifying LineBuf, we're implicitly consuming it all.
1801
1802 // Otherwise, consume up to the original tokens.
1803 } else {
1804 assert(FirstOrigToken && "not using original tokens?");
1805
1806 // Since we're using original tokens, apply that offset.
1807 assert(FirstOrigToken[NumConsumedToks].getLocation()
1808 == LineToks[NumConsumedToks].getLocation());
1809 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1810 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1811
1812 // The total length we've consumed is the relative offset
1813 // of the last token we consumed plus its length.
1814 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1815 + AsmToks[LastIndex].getLength()
1816 - AsmTokOffsets[FirstIndex]);
1817 LineBuf = LineBuf.substr(0, TotalOffset);
1818 }
1819
1820 // Initialize the "decl" with the lookup result.
1821 Info.OpDecl = static_cast<void*>(Result.take());
1822 return Info.OpDecl;
1823 }
1824
1825 bool LookupInlineAsmField(StringRef Base, StringRef Member,
Stephen Hines651f13c2014-04-23 16:59:28 -07001826 unsigned &Offset) override {
John McCallaeeacf72013-05-03 00:10:13 +00001827 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1828 Offset, AsmLoc);
1829 }
1830
1831 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1832 void *Context) {
1833 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1834 }
1835
1836 private:
1837 /// Collect the appropriate tokens for the given string.
1838 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1839 const Token *&FirstOrigToken) const {
1840 // For now, assert that the string we're working with is a substring
1841 // of what we gave to MC. This lets us use the original tokens.
1842 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1843 !std::less<const char*>()(AsmString.end(), Str.end()));
1844
1845 // Try to find a token whose offset matches the first token.
1846 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1847 const unsigned *FirstTokOffset
1848 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1849 FirstCharOffset);
1850
1851 // For now, assert that the start of the string exactly
1852 // corresponds to the start of a token.
1853 assert(*FirstTokOffset == FirstCharOffset);
1854
1855 // Use all the original tokens for this line. (We assume the
1856 // end of the line corresponds cleanly to a token break.)
1857 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1858 FirstOrigToken = &AsmToks[FirstTokIndex];
1859 unsigned LastCharOffset = Str.end() - AsmString.begin();
1860 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1861 if (AsmTokOffsets[i] >= LastCharOffset) break;
1862 TempToks.push_back(AsmToks[i]);
1863 }
1864 }
1865
1866 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1867 // Compute an offset into the inline asm buffer.
1868 // FIXME: This isn't right if .macro is involved (but hopefully, no
1869 // real-world code does that).
1870 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1871 const llvm::MemoryBuffer *LBuf =
1872 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1873 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1874
1875 // Figure out which token that offset points into.
1876 const unsigned *TokOffsetPtr =
1877 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1878 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1879 unsigned TokOffset = *TokOffsetPtr;
1880
1881 // If we come up with an answer which seems sane, use it; otherwise,
1882 // just point at the __asm keyword.
1883 // FIXME: Assert the answer is sane once we handle .macro correctly.
1884 SourceLocation Loc = AsmLoc;
1885 if (TokIndex < AsmToks.size()) {
1886 const Token &Tok = AsmToks[TokIndex];
1887 Loc = Tok.getLocation();
1888 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1889 }
1890 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1891 << D.getMessage();
1892 }
1893 };
1894}
1895
1896/// Parse an identifier in an MS-style inline assembly block.
1897///
1898/// \param CastInfo - a void* so that we don't have to teach Parser.h
1899/// about the actual type.
1900ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1901 unsigned &NumLineToksConsumed,
1902 void *CastInfo,
1903 bool IsUnevaluatedContext) {
1904 llvm::InlineAsmIdentifierInfo &Info =
1905 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1906
1907 // Push a fake token on the end so that we don't overrun the token
1908 // stream. We use ';' because it expression-parsing should never
1909 // overrun it.
1910 const tok::TokenKind EndOfStream = tok::semi;
1911 Token EndOfStreamTok;
1912 EndOfStreamTok.startToken();
1913 EndOfStreamTok.setKind(EndOfStream);
1914 LineToks.push_back(EndOfStreamTok);
1915
1916 // Also copy the current token over.
1917 LineToks.push_back(Tok);
1918
1919 PP.EnterTokenStream(LineToks.begin(),
1920 LineToks.size(),
1921 /*disable macros*/ true,
1922 /*owns tokens*/ false);
1923
1924 // Clear the current token and advance to the first token in LineToks.
1925 ConsumeAnyToken();
1926
1927 // Parse an optional scope-specifier if we're in C++.
1928 CXXScopeSpec SS;
1929 if (getLangOpts().CPlusPlus) {
1930 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1931 }
1932
1933 // Require an identifier here.
1934 SourceLocation TemplateKWLoc;
1935 UnqualifiedId Id;
1936 bool Invalid = ParseUnqualifiedId(SS,
1937 /*EnteringContext=*/false,
1938 /*AllowDestructorName=*/false,
1939 /*AllowConstructorName=*/false,
1940 /*ObjectType=*/ ParsedType(),
1941 TemplateKWLoc,
1942 Id);
1943
Stephen Hines651f13c2014-04-23 16:59:28 -07001944 // Figure out how many tokens we are into LineToks.
1945 unsigned LineIndex = 0;
1946 if (Tok.is(EndOfStream)) {
1947 LineIndex = LineToks.size() - 2;
John McCallaeeacf72013-05-03 00:10:13 +00001948 } else {
John McCallaeeacf72013-05-03 00:10:13 +00001949 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1950 LineIndex++;
1951 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1952 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001953 }
John McCallaeeacf72013-05-03 00:10:13 +00001954
Stephen Hines651f13c2014-04-23 16:59:28 -07001955 // If we've run into the poison token we inserted before, or there
1956 // was a parsing error, then claim the entire line.
1957 if (Invalid || Tok.is(EndOfStream)) {
1958 NumLineToksConsumed = LineToks.size() - 2;
1959 } else {
1960 // Otherwise, claim up to the start of the next token.
John McCallaeeacf72013-05-03 00:10:13 +00001961 NumLineToksConsumed = LineIndex;
1962 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001963
1964 // Finally, restore the old parsing state by consuming all the tokens we
1965 // staged before, implicitly killing off the token-lexer we pushed.
1966 for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
John McCallaeeacf72013-05-03 00:10:13 +00001967 ConsumeAnyToken();
1968 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001969 assert(Tok.is(EndOfStream));
1970 ConsumeToken();
John McCallaeeacf72013-05-03 00:10:13 +00001971
1972 // Leave LineToks in its original state.
1973 LineToks.pop_back();
1974 LineToks.pop_back();
1975
1976 // Perform the lookup.
1977 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1978 IsUnevaluatedContext);
1979}
1980
1981/// Turn a sequence of our tokens back into a string that we can hand
1982/// to the MC asm parser.
1983static bool buildMSAsmString(Preprocessor &PP,
1984 SourceLocation AsmLoc,
1985 ArrayRef<Token> AsmToks,
1986 SmallVectorImpl<unsigned> &TokOffsets,
1987 SmallString<512> &Asm) {
1988 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1989
1990 // Is this the start of a new assembly statement?
1991 bool isNewStatement = true;
1992
1993 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1994 const Token &Tok = AsmToks[i];
1995
1996 // Start each new statement with a newline and a tab.
1997 if (!isNewStatement &&
1998 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1999 Asm += "\n\t";
2000 isNewStatement = true;
2001 }
2002
2003 // Preserve the existence of leading whitespace except at the
2004 // start of a statement.
2005 if (!isNewStatement && Tok.hasLeadingSpace())
2006 Asm += ' ';
2007
2008 // Remember the offset of this token.
2009 TokOffsets.push_back(Asm.size());
2010
2011 // Don't actually write '__asm' into the assembly stream.
2012 if (Tok.is(tok::kw_asm)) {
2013 // Complain about __asm at the end of the stream.
2014 if (i + 1 == e) {
2015 PP.Diag(AsmLoc, diag::err_asm_empty);
2016 return true;
2017 }
2018
2019 continue;
2020 }
2021
2022 // Append the spelling of the token.
2023 SmallString<32> SpellingBuffer;
2024 bool SpellingInvalid = false;
2025 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
2026 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
2027
2028 // We are no longer at the start of a statement.
2029 isNewStatement = false;
2030 }
2031
2032 // Ensure that the buffer is null-terminated.
2033 Asm.push_back('\0');
2034 Asm.pop_back();
2035
2036 assert(TokOffsets.size() == AsmToks.size());
2037 return false;
2038}
2039
Eli Friedman3fedbe12011-09-30 01:13:51 +00002040/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
2041/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier8cd64b42012-06-11 20:47:18 +00002042///
2043/// [MS] ms-asm-statement:
2044/// ms-asm-block
2045/// ms-asm-block ms-asm-statement
2046///
2047/// [MS] ms-asm-block:
2048/// '__asm' ms-asm-line '\n'
2049/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
2050///
2051/// [MS] ms-asm-instruction-block
2052/// ms-asm-line
2053/// ms-asm-line '\n' ms-asm-instruction-block
2054///
Eli Friedman3fedbe12011-09-30 01:13:51 +00002055StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
2056 SourceManager &SrcMgr = PP.getSourceManager();
2057 SourceLocation EndLoc = AsmLoc;
Chad Rosier8cd64b42012-06-11 20:47:18 +00002058 SmallVector<Token, 4> AsmToks;
Chad Rosier21ef7112012-08-14 19:22:06 +00002059
2060 bool InBraces = false;
2061 unsigned short savedBraceCount = 0;
2062 bool InAsmComment = false;
2063 FileID FID;
2064 unsigned LineNo = 0;
2065 unsigned NumTokensRead = 0;
2066 SourceLocation LBraceLoc;
2067
2068 if (Tok.is(tok::l_brace)) {
2069 // Braced inline asm: consume the opening brace.
2070 InBraces = true;
2071 savedBraceCount = BraceCount;
2072 EndLoc = LBraceLoc = ConsumeBrace();
2073 ++NumTokensRead;
2074 } else {
2075 // Single-line inline asm; compute which line it is on.
2076 std::pair<FileID, unsigned> ExpAsmLoc =
2077 SrcMgr.getDecomposedExpansionLoc(EndLoc);
2078 FID = ExpAsmLoc.first;
2079 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2080 }
2081
2082 SourceLocation TokLoc = Tok.getLocation();
Eli Friedman3fedbe12011-09-30 01:13:51 +00002083 do {
Chad Rosier21ef7112012-08-14 19:22:06 +00002084 // If we hit EOF, we're done, period.
Stephen Hines651f13c2014-04-23 16:59:28 -07002085 if (isEofOrEom())
Eli Friedman3fedbe12011-09-30 01:13:51 +00002086 break;
Chad Rosier21ef7112012-08-14 19:22:06 +00002087
Chad Rosier21ef7112012-08-14 19:22:06 +00002088 if (!InAsmComment && Tok.is(tok::semi)) {
2089 // A semicolon in an asm is the start of a comment.
2090 InAsmComment = true;
2091 if (InBraces) {
2092 // Compute which line the comment is on.
2093 std::pair<FileID, unsigned> ExpSemiLoc =
2094 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2095 FID = ExpSemiLoc.first;
2096 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2097 }
2098 } else if (!InBraces || InAsmComment) {
2099 // If end-of-line is significant, check whether this token is on a
2100 // new line.
2101 std::pair<FileID, unsigned> ExpLoc =
2102 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2103 if (ExpLoc.first != FID ||
2104 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2105 // If this is a single-line __asm, we're done.
2106 if (!InBraces)
2107 break;
2108 // We're no longer in a comment.
2109 InAsmComment = false;
2110 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2111 // Single-line asm always ends when a closing brace is seen.
2112 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2113 // does MSVC do here?
2114 break;
2115 }
2116 }
2117 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2118 BraceCount == (savedBraceCount + 1)) {
2119 // Consume the closing brace, and finish
2120 EndLoc = ConsumeBrace();
2121 break;
2122 }
2123
2124 // Consume the next token; make sure we don't modify the brace count etc.
2125 // if we are in a comment.
2126 EndLoc = TokLoc;
2127 if (InAsmComment)
2128 PP.Lex(Tok);
2129 else {
2130 AsmToks.push_back(Tok);
2131 ConsumeAnyToken();
2132 }
2133 TokLoc = Tok.getLocation();
2134 ++NumTokensRead;
Eli Friedman3fedbe12011-09-30 01:13:51 +00002135 } while (1);
Chad Rosier8cd64b42012-06-11 20:47:18 +00002136
Chad Rosier21ef7112012-08-14 19:22:06 +00002137 if (InBraces && BraceCount != savedBraceCount) {
2138 // __asm without closing brace (this can happen at EOF).
Stephen Hines651f13c2014-04-23 16:59:28 -07002139 Diag(Tok, diag::err_expected) << tok::r_brace;
2140 Diag(LBraceLoc, diag::note_matching) << tok::l_brace;
Chad Rosier21ef7112012-08-14 19:22:06 +00002141 return StmtError();
2142 } else if (NumTokensRead == 0) {
2143 // Empty __asm.
Stephen Hines651f13c2014-04-23 16:59:28 -07002144 Diag(Tok, diag::err_expected) << tok::l_brace;
Chad Rosier21ef7112012-08-14 19:22:06 +00002145 return StmtError();
2146 }
2147
John McCallaeeacf72013-05-03 00:10:13 +00002148 // Okay, prepare to use MC to parse the assembly.
2149 SmallVector<StringRef, 4> ConstraintRefs;
2150 SmallVector<Expr*, 4> Exprs;
2151 SmallVector<StringRef, 4> ClobberRefs;
2152
2153 // We need an actual supported target.
Stephen Hines651f13c2014-04-23 16:59:28 -07002154 const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
John McCallaeeacf72013-05-03 00:10:13 +00002155 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
Alp Tokerc94b5ae2013-10-30 15:07:10 +00002156 const std::string &TT = TheTriple.getTriple();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002157 const llvm::Target *TheTarget = nullptr;
John McCallaeeacf72013-05-03 00:10:13 +00002158 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2159 ArchTy != llvm::Triple::x86_64);
Alp Tokerc94b5ae2013-10-30 15:07:10 +00002160 if (UnsupportedArch) {
John McCallaeeacf72013-05-03 00:10:13 +00002161 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
Alp Tokerc94b5ae2013-10-30 15:07:10 +00002162 } else {
2163 std::string Error;
2164 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2165 if (!TheTarget)
2166 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
2167 }
Alp Toker25973152013-10-30 14:29:28 +00002168
John McCallaeeacf72013-05-03 00:10:13 +00002169 // If we don't support assembly, or the assembly is empty, we don't
2170 // need to instantiate the AsmParser, etc.
Alp Tokerc94b5ae2013-10-30 15:07:10 +00002171 if (!TheTarget || AsmToks.empty()) {
John McCallaeeacf72013-05-03 00:10:13 +00002172 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2173 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2174 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2175 }
2176
2177 // Expand the tokens into a string buffer.
2178 SmallString<512> AsmString;
2179 SmallVector<unsigned, 8> TokOffsets;
2180 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2181 return StmtError();
2182
Stephen Hines651f13c2014-04-23 16:59:28 -07002183 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2184 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly12981a72013-09-12 10:59:24 +00002185 // Get the instruction descriptor.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002186 std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Stephen Hines651f13c2014-04-23 16:59:28 -07002187 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2188 std::unique_ptr<llvm::MCSubtargetInfo> STI(
2189 TheTarget->createMCSubtargetInfo(TT, "", ""));
John McCallaeeacf72013-05-03 00:10:13 +00002190
2191 llvm::SourceMgr TempSrcMgr;
Bill Wendling4b7bae32013-06-18 07:22:05 +00002192 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallaeeacf72013-05-03 00:10:13 +00002193 llvm::MemoryBuffer *Buffer =
2194 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2195
2196 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2197 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2198
Stephen Hines651f13c2014-04-23 16:59:28 -07002199 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2200 std::unique_ptr<llvm::MCAsmParser> Parser(
2201 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
John McCallaeeacf72013-05-03 00:10:13 +00002202
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002203 // FIXME: init MCOptions from sanitizer flags here.
2204 llvm::MCTargetOptions MCOptions;
2205 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
2206 TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
2207
2208 std::unique_ptr<llvm::MCInstPrinter> IP(
2209 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI));
John McCallaeeacf72013-05-03 00:10:13 +00002210
2211 // Change to the Intel dialect.
2212 Parser->setAssemblerDialect(1);
2213 Parser->setTargetParser(*TargetParser.get());
2214 Parser->setParsingInlineAsm(true);
2215 TargetParser->setParsingInlineAsm(true);
2216
2217 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2218 AsmToks, TokOffsets);
2219 TargetParser->setSemaCallback(&Callback);
2220 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2221 &Callback);
2222
2223 unsigned NumOutputs;
2224 unsigned NumInputs;
2225 std::string AsmStringIR;
2226 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2227 SmallVector<std::string, 4> Constraints;
2228 SmallVector<std::string, 4> Clobbers;
2229 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2230 NumOutputs, NumInputs, OpExprs, Constraints,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002231 Clobbers, MII.get(), IP.get(), Callback))
John McCallaeeacf72013-05-03 00:10:13 +00002232 return StmtError();
2233
Stephen Hines651f13c2014-04-23 16:59:28 -07002234 // Filter out "fpsw". Clang doesn't accept it, and it always lists flags and
2235 // fpsr as clobbers.
2236 auto End = std::remove(Clobbers.begin(), Clobbers.end(), "fpsw");
2237 Clobbers.erase(End, Clobbers.end());
2238
John McCallaeeacf72013-05-03 00:10:13 +00002239 // Build the vector of clobber StringRefs.
2240 unsigned NumClobbers = Clobbers.size();
2241 ClobberRefs.resize(NumClobbers);
2242 for (unsigned i = 0; i != NumClobbers; ++i)
2243 ClobberRefs[i] = StringRef(Clobbers[i]);
2244
2245 // Recast the void pointers and build the vector of constraint StringRefs.
2246 unsigned NumExprs = NumOutputs + NumInputs;
2247 ConstraintRefs.resize(NumExprs);
2248 Exprs.resize(NumExprs);
2249 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2250 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2251 if (!OpExpr)
2252 return StmtError();
2253
2254 // Need address of variable.
2255 if (OpExprs[i].second)
2256 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2257 .take();
2258
2259 ConstraintRefs[i] = StringRef(Constraints[i]);
2260 Exprs[i] = OpExpr;
2261 }
2262
Chad Rosier8f726de2012-08-06 20:03:45 +00002263 // FIXME: We should be passing source locations for better diagnostics.
John McCallaeeacf72013-05-03 00:10:13 +00002264 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2265 NumOutputs, NumInputs,
2266 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00002267}
2268
Reid Spencer5f016e22007-07-11 17:01:13 +00002269/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff5f8aa692008-02-11 23:15:56 +00002270/// asm-statement:
2271/// gnu-asm-statement
2272/// ms-asm-statement
2273///
2274/// [GNU] gnu-asm-statement:
Reid Spencer5f016e22007-07-11 17:01:13 +00002275/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2276///
2277/// [GNU] asm-argument:
2278/// asm-string-literal
2279/// asm-string-literal ':' asm-operands[opt]
2280/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2281/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2282/// ':' asm-clobbers
2283///
2284/// [GNU] asm-clobbers:
2285/// asm-string-literal
2286/// asm-clobbers ',' asm-string-literal
2287///
John McCall60d7b3a2010-08-24 06:29:42 +00002288StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002289 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattnerfe795952007-10-29 04:04:16 +00002290 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00002291
Chad Rosier15490fd2012-12-05 21:08:21 +00002292 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosierb6604462012-07-10 21:35:27 +00002293 !isTypeQualifier()) {
Steve Naroffd62701b2008-02-07 03:50:06 +00002294 msAsm = true;
Eli Friedman3fedbe12011-09-30 01:13:51 +00002295 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00002296 }
John McCall0b7e6782011-03-24 11:26:52 +00002297 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 SourceLocation Loc = Tok.getLocation();
Sean Huntbbd37c62009-11-21 08:43:09 +00002299 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redl9a920342008-12-11 19:48:14 +00002300
Reid Spencer5f016e22007-07-11 17:01:13 +00002301 // GNU asms accept, but warn, about type-qualifiers other than volatile.
2302 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner1ab3b962008-11-18 07:48:38 +00002303 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Reid Spencer5f016e22007-07-11 17:01:13 +00002304 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner1ab3b962008-11-18 07:48:38 +00002305 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith4cf4a5e2013-03-28 01:55:44 +00002306 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2307 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2308 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redl9a920342008-12-11 19:48:14 +00002309
Reid Spencer5f016e22007-07-11 17:01:13 +00002310 // Remember if this was a volatile asm.
Anders Carlsson39c47b52007-11-23 23:12:25 +00002311 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002312 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00002313 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Alexey Bataev8fe24752013-11-18 08:17:37 +00002314 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl9a920342008-12-11 19:48:14 +00002315 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002317 BalancedDelimiterTracker T(*this, tok::l_paren);
2318 T.consumeOpen();
Sebastian Redl9a920342008-12-11 19:48:14 +00002319
John McCall60d7b3a2010-08-24 06:29:42 +00002320 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenek320fa4b2011-12-02 01:30:14 +00002321 if (AsmString.isInvalid()) {
Richard Smith99831e42012-03-06 03:21:47 +00002322 // Consume up to and including the closing paren.
2323 T.skipToEnd();
Sebastian Redl9a920342008-12-11 19:48:14 +00002324 return StmtError();
Ted Kremenek320fa4b2011-12-02 01:30:14 +00002325 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002326
Chris Lattner5f9e2722011-07-23 10:55:15 +00002327 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002328 ExprVector Constraints;
2329 ExprVector Exprs;
2330 ExprVector Clobbers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002331
Anders Carlssondfab34a2008-02-05 23:03:50 +00002332 if (Tok.is(tok::r_paren)) {
Chris Lattner64cb4752009-12-20 23:00:41 +00002333 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002334 T.consumeClose();
Chad Rosierdf5faf52012-08-25 00:11:56 +00002335 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002336 /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr,
Chad Rosierdf5faf52012-08-25 00:11:56 +00002337 Constraints, Exprs, AsmString.take(),
2338 Clobbers, T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002340
Chris Lattner64cb4752009-12-20 23:00:41 +00002341 // Parse Outputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002342 bool AteExtraColon = false;
2343 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2344 // In C++ mode, parse "::" like ": :".
2345 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattner64cb4752009-12-20 23:00:41 +00002346 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002347
Chris Lattner64056462009-12-20 23:08:04 +00002348 if (!AteExtraColon &&
2349 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00002350 return StmtError();
2351 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002352
Chris Lattner64cb4752009-12-20 23:00:41 +00002353 unsigned NumOutputs = Names.size();
2354
2355 // Parse Inputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002356 if (AteExtraColon ||
2357 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2358 // In C++ mode, parse "::" like ": :".
2359 if (AteExtraColon)
2360 AteExtraColon = false;
2361 else {
2362 AteExtraColon = Tok.is(tok::coloncolon);
2363 ConsumeToken();
2364 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002365
Chris Lattner64056462009-12-20 23:08:04 +00002366 if (!AteExtraColon &&
2367 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00002368 return StmtError();
2369 }
2370
2371 assert(Names.size() == Constraints.size() &&
2372 Constraints.size() == Exprs.size() &&
2373 "Input operand size mismatch!");
2374
2375 unsigned NumInputs = Names.size() - NumOutputs;
2376
2377 // Parse the clobbers, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002378 if (AteExtraColon || Tok.is(tok::colon)) {
2379 if (!AteExtraColon)
2380 ConsumeToken();
Chris Lattner64cb4752009-12-20 23:00:41 +00002381
Chandler Carruth102e1b62010-07-22 07:11:21 +00002382 // Parse the asm-string list for clobbers if present.
2383 if (Tok.isNot(tok::r_paren)) {
2384 while (1) {
John McCall60d7b3a2010-08-24 06:29:42 +00002385 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattner64cb4752009-12-20 23:00:41 +00002386
Chandler Carruth102e1b62010-07-22 07:11:21 +00002387 if (Clobber.isInvalid())
2388 break;
Chris Lattner64cb4752009-12-20 23:00:41 +00002389
Chandler Carruth102e1b62010-07-22 07:11:21 +00002390 Clobbers.push_back(Clobber.release());
Chris Lattner64cb4752009-12-20 23:00:41 +00002391
Stephen Hines651f13c2014-04-23 16:59:28 -07002392 if (!TryConsumeToken(tok::comma))
2393 break;
Chandler Carruth102e1b62010-07-22 07:11:21 +00002394 }
Chris Lattner64cb4752009-12-20 23:00:41 +00002395 }
2396 }
2397
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002398 T.consumeClose();
Chad Rosierdf5faf52012-08-25 00:11:56 +00002399 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2400 NumInputs, Names.data(), Constraints, Exprs,
2401 AsmString.take(), Clobbers,
2402 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002403}
2404
2405/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattner64cb4752009-12-20 23:00:41 +00002406/// asm-statement, assuming the leading ':' token was eaten.
Reid Spencer5f016e22007-07-11 17:01:13 +00002407///
2408/// [GNU] asm-operands:
2409/// asm-operand
2410/// asm-operands ',' asm-operand
2411///
2412/// [GNU] asm-operand:
2413/// asm-string-literal '(' expression ')'
2414/// '[' identifier ']' asm-string-literal '(' expression ')'
2415///
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00002416//
2417// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002418bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002419 SmallVectorImpl<Expr *> &Constraints,
2420 SmallVectorImpl<Expr *> &Exprs) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002421 // 'asm-operands' isn't present?
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002422 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002423 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002424
2425 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002426 // Read the [id] if present.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002427 if (Tok.is(tok::l_square)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002428 BalancedDelimiterTracker T(*this, tok::l_square);
2429 T.consumeOpen();
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002431 if (Tok.isNot(tok::identifier)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002432 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataev8fe24752013-11-18 08:17:37 +00002433 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002434 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002435 }
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Anders Carlssonb235fc22007-11-22 01:36:19 +00002437 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner69efba72007-10-29 04:06:22 +00002438 ConsumeToken();
Anders Carlssonb235fc22007-11-22 01:36:19 +00002439
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002440 Names.push_back(II);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002441 T.consumeClose();
Anders Carlssonb235fc22007-11-22 01:36:19 +00002442 } else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002443 Names.push_back(nullptr);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002444
John McCall60d7b3a2010-08-24 06:29:42 +00002445 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002446 if (Constraint.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002447 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002448 return true;
Anders Carlssonb235fc22007-11-22 01:36:19 +00002449 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002450 Constraints.push_back(Constraint.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00002451
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002452 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00002453 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Alexey Bataev8fe24752013-11-18 08:17:37 +00002454 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002455 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002456 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002457
Reid Spencer5f016e22007-07-11 17:01:13 +00002458 // Read the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002459 BalancedDelimiterTracker T(*this, tok::l_paren);
2460 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00002461 ExprResult Res(ParseExpression());
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002462 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002463 if (Res.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002464 SkipUntil(tok::r_paren, StopAtSemi);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002465 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002466 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002467 Exprs.push_back(Res.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 // Eat the comma and continue parsing if it exists.
Stephen Hines651f13c2014-04-23 16:59:28 -07002469 if (!TryConsumeToken(tok::comma))
2470 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 }
2472}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002473
Douglas Gregorc9977d02011-03-16 17:05:57 +00002474Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00002475 assert(Tok.is(tok::l_brace));
2476 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002477
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00002478 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1a5bd5d2012-11-19 21:13:18 +00002479 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002480 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00002481 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002482 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002483
John McCallf312b1e2010-08-26 23:41:50 +00002484 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2485 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002487 // Do not enter a scope for the brace, as the arguments are in the same scope
2488 // (the function body) as the body itself. Instead, just read the statement
2489 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00002490 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00002491
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002492 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002493 if (FnBody.isInvalid()) {
2494 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00002495 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002496 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00002497
Douglas Gregorc9977d02011-03-16 17:05:57 +00002498 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002499 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00002500}
Sebastian Redla0fd8652008-12-21 16:41:36 +00002501
Sebastian Redld3a413d2009-04-26 20:35:05 +00002502/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2503///
2504/// function-try-block:
2505/// 'try' ctor-initializer[opt] compound-statement handler-seq
2506///
Douglas Gregorc9977d02011-03-16 17:05:57 +00002507Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00002508 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2509 SourceLocation TryLoc = ConsumeToken();
2510
John McCallf312b1e2010-08-26 23:41:50 +00002511 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2512 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00002513
2514 // Constructor initializer list?
2515 if (Tok.is(tok::colon))
2516 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00002517 else
2518 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002519
Richard Smith1a5bd5d2012-11-19 21:13:18 +00002520 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2521 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002522 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00002523 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002524 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002525
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002526 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikiec4027c82012-11-10 01:04:23 +00002527 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redld3a413d2009-04-26 20:35:05 +00002528 // If we failed to parse the try-catch, we just give the function an empty
2529 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002530 if (FnBody.isInvalid()) {
2531 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00002532 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002533 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00002534
Douglas Gregorc9977d02011-03-16 17:05:57 +00002535 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002536 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redld3a413d2009-04-26 20:35:05 +00002537}
2538
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002539bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002540 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002541 assert(SkipFunctionBodies &&
2542 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002543
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00002544 if (!PP.isCodeCompletionEnabled()) {
2545 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00002546 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00002547 return true;
2548 }
2549
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002550 // We're in code-completion mode. Skip parsing for all function bodies unless
2551 // the body contains the code-completion point.
2552 TentativeParsingAction PA(*this);
2553 ConsumeBrace();
Alexey Bataev8fe24752013-11-18 08:17:37 +00002554 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002555 PA.Commit();
2556 return true;
2557 }
2558
2559 PA.Revert();
2560 return false;
2561}
2562
Sebastian Redla0fd8652008-12-21 16:41:36 +00002563/// ParseCXXTryBlock - Parse a C++ try-block.
2564///
2565/// try-block:
2566/// 'try' compound-statement handler-seq
2567///
Richard Smith534986f2012-04-14 00:33:13 +00002568StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002569 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2570
2571 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002572 return ParseCXXTryBlockCommon(TryLoc);
2573}
2574
2575/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2576/// function-try-block.
2577///
2578/// try-block:
2579/// 'try' compound-statement handler-seq
2580///
2581/// function-try-block:
2582/// 'try' ctor-initializer[opt] compound-statement handler-seq
2583///
2584/// handler-seq:
2585/// handler handler-seq[opt]
2586///
John Wiegley28bbe4b2011-04-28 01:08:34 +00002587/// [Borland] try-block:
2588/// 'try' compound-statement seh-except-block
Stephen Hines651f13c2014-04-23 16:59:28 -07002589/// 'try' compound-statement seh-finally-block
John Wiegley28bbe4b2011-04-28 01:08:34 +00002590///
David Blaikiec4027c82012-11-10 01:04:23 +00002591StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002592 if (Tok.isNot(tok::l_brace))
Stephen Hines651f13c2014-04-23 16:59:28 -07002593 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sean Huntbbd37c62009-11-21 08:43:09 +00002594 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002595
2596 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikiee5afdcf2012-11-13 18:51:45 +00002597 Scope::DeclScope | Scope::TryScope |
2598 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002599 if (TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002600 return TryBlock;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002601
John Wiegley28bbe4b2011-04-28 01:08:34 +00002602 // Borland allows SEH-handlers with 'try'
Chad Rosierb6604462012-07-10 21:35:27 +00002603
Richard Smith534986f2012-04-14 00:33:13 +00002604 if ((Tok.is(tok::identifier) &&
2605 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2606 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002607 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2608 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00002609 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002610 SourceLocation Loc = ConsumeToken();
2611 Handler = ParseSEHExceptBlock(Loc);
2612 }
2613 else {
2614 SourceLocation Loc = ConsumeToken();
2615 Handler = ParseSEHFinallyBlock(Loc);
2616 }
2617 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002618 return Handler;
John McCall7f040a92010-12-24 02:08:15 +00002619
John Wiegley28bbe4b2011-04-28 01:08:34 +00002620 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2621 TryLoc,
2622 TryBlock.take(),
2623 Handler.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002624 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00002625 else {
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002626 StmtVector Handlers;
Richard Smith5eed7e02013-10-15 01:34:54 +00002627
2628 // C++11 attributes can't appear here, despite this context seeming
2629 // statement-like.
2630 DiagnoseAndSkipCXX11Attributes();
Sebastian Redla0fd8652008-12-21 16:41:36 +00002631
John Wiegley28bbe4b2011-04-28 01:08:34 +00002632 if (Tok.isNot(tok::kw_catch))
2633 return StmtError(Diag(Tok, diag::err_expected_catch));
2634 while (Tok.is(tok::kw_catch)) {
David Blaikiec4027c82012-11-10 01:04:23 +00002635 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley28bbe4b2011-04-28 01:08:34 +00002636 if (!Handler.isInvalid())
2637 Handlers.push_back(Handler.release());
2638 }
2639 // Don't bother creating the full statement if we don't have any usable
2640 // handlers.
2641 if (Handlers.empty())
2642 return StmtError();
2643
Robert Wilhelm21adb0c2013-08-22 09:20:03 +00002644 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002645 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002646}
2647
2648/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2649///
Richard Smith4cd81c52013-01-29 09:02:09 +00002650/// handler:
2651/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +00002652///
Richard Smith4cd81c52013-01-29 09:02:09 +00002653/// exception-declaration:
2654/// attribute-specifier-seq[opt] type-specifier-seq declarator
2655/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2656/// '...'
Sebastian Redla0fd8652008-12-21 16:41:36 +00002657///
David Blaikiec4027c82012-11-10 01:04:23 +00002658StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002659 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2660
2661 SourceLocation CatchLoc = ConsumeToken();
2662
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002663 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002664 if (T.expectAndConsume())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002665 return StmtError();
2666
2667 // C++ 3.3.2p3:
2668 // The name in a catch exception-declaration is local to the handler and
2669 // shall not be redeclared in the outermost block of the handler.
David Blaikiec4027c82012-11-10 01:04:23 +00002670 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikiee5afdcf2012-11-13 18:51:45 +00002671 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002672
2673 // exception-declaration is equivalent to '...' or a parameter-declaration
2674 // without default arguments.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002675 Decl *ExceptionDecl = nullptr;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002676 if (Tok.isNot(tok::ellipsis)) {
Richard Smith4cd81c52013-01-29 09:02:09 +00002677 ParsedAttributesWithRange Attributes(AttrFactory);
2678 MaybeParseCXX11Attributes(Attributes);
2679
John McCall0b7e6782011-03-24 11:26:52 +00002680 DeclSpec DS(AttrFactory);
Richard Smith4cd81c52013-01-29 09:02:09 +00002681 DS.takeAttributesFrom(Attributes);
2682
Sebastian Redl4b07b292008-12-22 19:15:10 +00002683 if (ParseCXXTypeSpecifierSeq(DS))
2684 return StmtError();
Richard Smith4cd81c52013-01-29 09:02:09 +00002685
Sebastian Redla0fd8652008-12-21 16:41:36 +00002686 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2687 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002688 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002689 } else
2690 ConsumeToken();
2691
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002692 T.consumeClose();
2693 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002694 return StmtError();
2695
2696 if (Tok.isNot(tok::l_brace))
Stephen Hines651f13c2014-04-23 16:59:28 -07002697 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002698
Sean Huntbbd37c62009-11-21 08:43:09 +00002699 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002700 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002701 if (Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002702 return Block;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002703
John McCall9ae2f072010-08-23 23:25:46 +00002704 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002705}
Francois Pichet1e862692011-05-06 20:48:22 +00002706
2707void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002708 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002709 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002710 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002711
Douglas Gregor3896fc52011-10-24 22:31:10 +00002712 // Handle dependent statements by parsing the braces as a compound statement.
2713 // This is not the same behavior as Visual C++, which don't treat this as a
2714 // compound statement, but for Clang's type checking we can't have anything
2715 // inside these braces escaping to the surrounding code.
2716 if (Result.Behavior == IEB_Dependent) {
2717 if (!Tok.is(tok::l_brace)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002718 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smith534986f2012-04-14 00:33:13 +00002719 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002720 }
Richard Smith534986f2012-04-14 00:33:13 +00002721
2722 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002723 if (Compound.isInvalid())
2724 return;
Richard Smith534986f2012-04-14 00:33:13 +00002725
Douglas Gregorba0513d2011-10-25 01:33:02 +00002726 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2727 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002728 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002729 Result.Name,
2730 Compound.get());
2731 if (DepResult.isUsable())
2732 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002733 return;
2734 }
Richard Smith534986f2012-04-14 00:33:13 +00002735
Douglas Gregor3896fc52011-10-24 22:31:10 +00002736 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2737 if (Braces.consumeOpen()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002738 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet1e862692011-05-06 20:48:22 +00002739 return;
2740 }
Francois Pichet1e862692011-05-06 20:48:22 +00002741
Douglas Gregor3896fc52011-10-24 22:31:10 +00002742 switch (Result.Behavior) {
2743 case IEB_Parse:
2744 // Parse the statements below.
2745 break;
Chad Rosierb6604462012-07-10 21:35:27 +00002746
Douglas Gregor3896fc52011-10-24 22:31:10 +00002747 case IEB_Dependent:
2748 llvm_unreachable("Dependent case handled above");
Chad Rosierb6604462012-07-10 21:35:27 +00002749
Douglas Gregor3896fc52011-10-24 22:31:10 +00002750 case IEB_Skip:
2751 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002752 return;
2753 }
2754
2755 // Condition is true, parse the statements.
2756 while (Tok.isNot(tok::r_brace)) {
2757 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2758 if (R.isUsable())
2759 Stmts.push_back(R.release());
2760 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002761 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002762}