blob: e32d61928d14d7c5bae31f1aa4a364d91d076b2e [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"
John McCallaeeacf72013-05-03 00:10:13 +000026#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCObjectFileInfo.h"
29#include "llvm/MC/MCParser/MCAsmParser.h"
30#include "llvm/MC/MCRegisterInfo.h"
31#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSubtargetInfo.h"
33#include "llvm/MC/MCTargetAsmParser.h"
34#include "llvm/Support/SourceMgr.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
Chad Rosier8cd64b42012-06-11 20:47:18 +000037#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// C99 6.8: Statements and Blocks.
42//===----------------------------------------------------------------------===//
43
Richard Smith961d0572013-10-28 22:04:30 +000044/// \brief Parse a standalone statement (for instance, as the body of an 'if',
45/// 'while', or 'for').
46StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) {
47 StmtResult Res;
48
49 // We may get back a null statement if we found a #pragma. Keep going until
50 // we get an actual statement.
51 do {
52 StmtVector Stmts;
53 Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
54 } while (!Res.isInvalid() && !Res.get());
55
56 return Res;
57}
58
Reid Spencer5f016e22007-07-11 17:01:13 +000059/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
60/// StatementOrDeclaration:
61/// statement
62/// declaration
63///
64/// statement:
65/// labeled-statement
66/// compound-statement
67/// expression-statement
68/// selection-statement
69/// iteration-statement
70/// jump-statement
Argyrios Kyrtzidisdcdd55f2008-09-07 18:58:01 +000071/// [C++] declaration-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +000072/// [C++] try-block
John Wiegley28bbe4b2011-04-28 01:08:34 +000073/// [MS] seh-try-block
Fariborz Jahanianb384d322007-10-04 20:19:06 +000074/// [OBC] objc-throw-statement
75/// [OBC] objc-try-catch-statement
Fariborz Jahanianc385c902008-01-29 18:21:32 +000076/// [OBC] objc-synchronized-statement
Reid Spencer5f016e22007-07-11 17:01:13 +000077/// [GNU] asm-statement
78/// [OMP] openmp-construct [TODO]
79///
80/// labeled-statement:
81/// identifier ':' statement
82/// 'case' constant-expression ':' statement
83/// 'default' ':' statement
84///
85/// selection-statement:
86/// if-statement
87/// switch-statement
88///
89/// iteration-statement:
90/// while-statement
91/// do-statement
92/// for-statement
93///
94/// expression-statement:
95/// expression[opt] ';'
96///
97/// jump-statement:
98/// 'goto' identifier ';'
99/// 'continue' ';'
100/// 'break' ';'
101/// 'return' expression[opt] ';'
102/// [GNU] 'goto' '*' expression ';'
103///
Fariborz Jahanianb384d322007-10-04 20:19:06 +0000104/// [OBC] objc-throw-statement:
105/// [OBC] '@' 'throw' expression ';'
Mike Stump1eb44332009-09-09 15:08:12 +0000106/// [OBC] '@' 'throw' ';'
107///
John McCall60d7b3a2010-08-24 06:29:42 +0000108StmtResult
Nico Weber5cb94a72011-12-22 23:26:17 +0000109Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
110 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000111
Argyrios Kyrtzidis36d36802010-06-17 10:52:18 +0000112 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000113
Richard Smith534986f2012-04-14 00:33:13 +0000114 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +0000115 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
Richard Smith534986f2012-04-14 00:33:13 +0000116
117 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
118 OnlyStatement, TrailingElseLoc, Attrs);
119
120 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
121 "attributes on empty statement");
122
123 if (Attrs.empty() || Res.isInvalid())
124 return Res;
125
126 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
127}
128
Kaelyn Uhrain6243f622013-09-27 19:40:12 +0000129namespace {
130class StatementFilterCCC : public CorrectionCandidateCallback {
131public:
132 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
133 WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) ||
134 nextTok.is(tok::identifier) || nextTok.is(tok::star) ||
135 nextTok.is(tok::amp) || nextTok.is(tok::l_square);
136 WantExpressionKeywords = nextTok.is(tok::l_paren) ||
137 nextTok.is(tok::identifier) ||
138 nextTok.is(tok::arrow) || nextTok.is(tok::period);
139 WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) ||
140 nextTok.is(tok::identifier) ||
141 nextTok.is(tok::l_brace);
142 WantCXXNamedCasts = false;
143 }
144
145 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
146 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
Kaelyn Uhraina89ee572013-10-01 22:00:28 +0000147 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain0f90ee02013-09-27 19:40:16 +0000148 if (NextToken.is(tok::equal))
149 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain2ceb67a2013-09-27 23:54:23 +0000150 if (NextToken.is(tok::period) &&
151 candidate.getCorrectionDeclAs<NamespaceDecl>())
152 return false;
Kaelyn Uhrain6243f622013-09-27 19:40:12 +0000153 return CorrectionCandidateCallback::ValidateCandidate(candidate);
154 }
155
156private:
157 Token NextToken;
158};
159}
160
Richard Smith534986f2012-04-14 00:33:13 +0000161StmtResult
162Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
163 bool OnlyStatement, SourceLocation *TrailingElseLoc,
164 ParsedAttributesWithRange &Attrs) {
165 const char *SemiError = 0;
166 StmtResult Res;
Sean Huntbbd37c62009-11-21 08:43:09 +0000167
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 // Cases in this switch statement should fall through if the parser expects
169 // the token to end in a semicolon (in which case SemiError should be set),
170 // or they directly 'return;' if not.
Douglas Gregor312eadb2011-04-24 05:37:28 +0000171Retry:
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000172 tok::TokenKind Kind = Tok.getKind();
173 SourceLocation AtLoc;
174 switch (Kind) {
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000175 case tok::at: // May be a @try or @throw statement
176 {
Richard Smith534986f2012-04-14 00:33:13 +0000177 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000178 AtLoc = ConsumeToken(); // consume @
Sebastian Redl43bc2a02008-12-11 20:12:42 +0000179 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000180 }
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000181
Douglas Gregor791215b2009-09-21 20:51:25 +0000182 case tok::code_completion:
John McCallf312b1e2010-08-26 23:41:50 +0000183 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000184 cutOffParsing();
185 return StmtError();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000186
Douglas Gregor312eadb2011-04-24 05:37:28 +0000187 case tok::identifier: {
188 Token Next = NextToken();
189 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000190 // identifier ':' statement
Richard Smith534986f2012-04-14 00:33:13 +0000191 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidisb9f930d2008-07-12 21:04:42 +0000192 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000193
Richard Smith05766812012-08-18 00:55:03 +0000194 // Look up the identifier, and typo-correct it to a keyword if it's not
195 // found.
Douglas Gregor3b887352011-04-27 04:48:22 +0000196 if (Next.isNot(tok::coloncolon)) {
Richard Smith05766812012-08-18 00:55:03 +0000197 // Try to limit which sets of keywords should be included in typo
198 // correction based on what the next token is.
Kaelyn Uhrain6243f622013-09-27 19:40:12 +0000199 StatementFilterCCC Validator(Next);
200 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
Richard Smith05766812012-08-18 00:55:03 +0000201 == ANK_Error) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000202 // Handle errors here by skipping up to the next semicolon or '}', and
203 // eat the semicolon if that's what stopped us.
204 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
205 if (Tok.is(tok::semi))
206 ConsumeToken();
207 return StmtError();
Richard Smith05766812012-08-18 00:55:03 +0000208 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000209
Richard Smith05766812012-08-18 00:55:03 +0000210 // If the identifier was typo-corrected, try again.
211 if (Tok.isNot(tok::identifier))
Douglas Gregor312eadb2011-04-24 05:37:28 +0000212 goto Retry;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000213 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000214
Douglas Gregor312eadb2011-04-24 05:37:28 +0000215 // Fall through
216 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000217
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000218 default: {
David Blaikie4e4d0842012-03-11 07:00:24 +0000219 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner97144fc2009-04-02 04:16:50 +0000220 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek8113ecf2010-11-10 05:59:39 +0000221 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smith534986f2012-04-14 00:33:13 +0000222 DeclEnd, Attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000223 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000224 }
225
226 if (Tok.is(tok::r_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 Diag(Tok, diag::err_expected_statement);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000228 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 }
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Richard Smith534986f2012-04-14 00:33:13 +0000231 return ParseExprStatement();
Chris Lattnerf919bfe2009-03-24 17:04:48 +0000232 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000233
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000235 return ParseCaseStatement();
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smith534986f2012-04-14 00:33:13 +0000237 return ParseDefaultStatement();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000238
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smith534986f2012-04-14 00:33:13 +0000240 return ParseCompoundStatement();
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000241 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +0000242 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
243 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000244 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000245
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smith534986f2012-04-14 00:33:13 +0000247 return ParseIfStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smith534986f2012-04-14 00:33:13 +0000249 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000250
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smith534986f2012-04-14 00:33:13 +0000252 return ParseWhileStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smith534986f2012-04-14 00:33:13 +0000254 Res = ParseDoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000255 SemiError = "do/while";
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 break;
257 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smith534986f2012-04-14 00:33:13 +0000258 return ParseForStatement(TrailingElseLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000259
260 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smith534986f2012-04-14 00:33:13 +0000261 Res = ParseGotoStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000262 SemiError = "goto";
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 break;
264 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smith534986f2012-04-14 00:33:13 +0000265 Res = ParseContinueStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000266 SemiError = "continue";
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 break;
268 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smith534986f2012-04-14 00:33:13 +0000269 Res = ParseBreakStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000270 SemiError = "break";
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 break;
272 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smith534986f2012-04-14 00:33:13 +0000273 Res = ParseReturnStatement();
Chris Lattner6869d8e2009-06-14 00:07:48 +0000274 SemiError = "return";
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 break;
Sebastian Redl61364dd2008-12-11 19:30:53 +0000276
Sebastian Redla0fd8652008-12-21 16:41:36 +0000277 case tok::kw_asm: {
Richard Smith534986f2012-04-14 00:33:13 +0000278 ProhibitAttributes(Attrs);
Steve Naroffd62701b2008-02-07 03:50:06 +0000279 bool msAsm = false;
280 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +0000281 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000282 if (msAsm) return Res;
Chris Lattner6869d8e2009-06-14 00:07:48 +0000283 SemiError = "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 break;
285 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000286
Sebastian Redla0fd8652008-12-21 16:41:36 +0000287 case tok::kw_try: // C++ 15: try-block
Richard Smith534986f2012-04-14 00:33:13 +0000288 return ParseCXXTryBlock();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000289
290 case tok::kw___try:
Richard Smith534986f2012-04-14 00:33:13 +0000291 ProhibitAttributes(Attrs); // TODO: is it correct?
292 return ParseSEHTryBlock();
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000293
294 case tok::annot_pragma_vis:
Richard Smith534986f2012-04-14 00:33:13 +0000295 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000296 HandlePragmaVisibility();
297 return StmtEmpty();
298
299 case tok::annot_pragma_pack:
Richard Smith534986f2012-04-14 00:33:13 +0000300 ProhibitAttributes(Attrs);
Eli Friedmanaa5ab262012-02-23 23:47:16 +0000301 HandlePragmaPack();
302 return StmtEmpty();
Eli Friedman9595c7e2012-10-04 02:36:51 +0000303
Eli Friedman8b2bfdd2012-10-09 22:46:54 +0000304 case tok::annot_pragma_msstruct:
305 ProhibitAttributes(Attrs);
306 HandlePragmaMSStruct();
307 return StmtEmpty();
308
Eli Friedman3ef38ee2012-10-08 23:52:38 +0000309 case tok::annot_pragma_align:
310 ProhibitAttributes(Attrs);
311 HandlePragmaAlign();
312 return StmtEmpty();
313
Eli Friedman8b2bfdd2012-10-09 22:46:54 +0000314 case tok::annot_pragma_weak:
315 ProhibitAttributes(Attrs);
316 HandlePragmaWeak();
317 return StmtEmpty();
318
319 case tok::annot_pragma_weakalias:
320 ProhibitAttributes(Attrs);
321 HandlePragmaWeakAlias();
322 return StmtEmpty();
323
324 case tok::annot_pragma_redefine_extname:
325 ProhibitAttributes(Attrs);
326 HandlePragmaRedefineExtname();
327 return StmtEmpty();
328
Eli Friedman9595c7e2012-10-04 02:36:51 +0000329 case tok::annot_pragma_fp_contract:
Richard Smithaed01162013-11-15 21:10:54 +0000330 ProhibitAttributes(Attrs);
Lang Hames860022c2012-10-21 01:10:01 +0000331 Diag(Tok, diag::err_pragma_fp_contract_scope);
332 ConsumeToken();
333 return StmtError();
334
Eli Friedman9595c7e2012-10-04 02:36:51 +0000335 case tok::annot_pragma_opencl_extension:
336 ProhibitAttributes(Attrs);
337 HandlePragmaOpenCLExtension();
338 return StmtEmpty();
Alexey Bataevc6400582013-03-22 06:34:35 +0000339
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000340 case tok::annot_pragma_captured:
Richard Smith175d4172013-09-16 21:17:44 +0000341 ProhibitAttributes(Attrs);
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000342 return HandlePragmaCaptured();
343
Alexey Bataevc6400582013-03-22 06:34:35 +0000344 case tok::annot_pragma_openmp:
Richard Smith175d4172013-09-16 21:17:44 +0000345 ProhibitAttributes(Attrs);
Alexey Bataev4fa7eab2013-07-19 03:13:43 +0000346 return ParseOpenMPDeclarativeOrExecutableDirective();
347
Sebastian Redla0fd8652008-12-21 16:41:36 +0000348 }
349
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 // If we reached this code, the statement must end in a semicolon.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000351 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 ConsumeToken();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000353 } else if (!Res.isInvalid()) {
Chris Lattner7b3684a2009-06-14 00:23:56 +0000354 // If the result was valid, then we do want to diagnose this. Use
355 // ExpectAndConsume to emit the diagnostic, even though we know it won't
356 // succeed.
357 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner19504402008-11-13 18:52:53 +0000358 // Skip until we see a } or ;, but don't eat it.
359 SkipUntil(tok::r_brace, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000362 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000363}
364
Douglas Gregor312eadb2011-04-24 05:37:28 +0000365/// \brief Parse an expression statement.
Richard Smith534986f2012-04-14 00:33:13 +0000366StmtResult Parser::ParseExprStatement() {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000367 // If a case keyword is missing, this is where it should be inserted.
368 Token OldToken = Tok;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000369
Douglas Gregor312eadb2011-04-24 05:37:28 +0000370 // expression[opt] ';'
Douglas Gregor5ecdd782011-04-27 06:18:01 +0000371 ExprResult Expr(ParseExpression());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000372 if (Expr.isInvalid()) {
373 // If the expression is invalid, skip ahead to the next semicolon or '}'.
374 // Not doing this opens us up to the possibility of infinite loops if
375 // ParseExpression does not consume any tokens.
376 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
377 if (Tok.is(tok::semi))
378 ConsumeToken();
John McCallb760f112013-03-22 02:10:40 +0000379 return Actions.ActOnExprStmtError();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000380 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000381
Douglas Gregor312eadb2011-04-24 05:37:28 +0000382 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
383 Actions.CheckCaseExpression(Expr.get())) {
384 // If a constant expression is followed by a colon inside a switch block,
385 // suggest a missing case keyword.
386 Diag(OldToken, diag::err_expected_case_before_expression)
387 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000388
Douglas Gregor312eadb2011-04-24 05:37:28 +0000389 // Recover parsing as a case statement.
Richard Smith534986f2012-04-14 00:33:13 +0000390 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000391 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000392
Douglas Gregor312eadb2011-04-24 05:37:28 +0000393 // Otherwise, eat the semicolon.
394 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000395 return Actions.ActOnExprStmt(Expr);
John Wiegley28bbe4b2011-04-28 01:08:34 +0000396}
Douglas Gregor312eadb2011-04-24 05:37:28 +0000397
Richard Smith534986f2012-04-14 00:33:13 +0000398StmtResult Parser::ParseSEHTryBlock() {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000399 assert(Tok.is(tok::kw___try) && "Expected '__try'");
400 SourceLocation Loc = ConsumeToken();
401 return ParseSEHTryBlockCommon(Loc);
402}
403
404/// ParseSEHTryBlockCommon
405///
406/// seh-try-block:
407/// '__try' compound-statement seh-handler
408///
409/// seh-handler:
410/// seh-except-block
411/// seh-finally-block
412///
413StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
414 if(Tok.isNot(tok::l_brace))
415 return StmtError(Diag(Tok,diag::err_expected_lbrace));
416
Joao Matos568ba872012-09-04 17:49:35 +0000417 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000418 if(TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000419 return TryBlock;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000420
421 StmtResult Handler;
Richard Smith534986f2012-04-14 00:33:13 +0000422 if (Tok.is(tok::identifier) &&
Douglas Gregorb57791e2011-10-21 03:57:52 +0000423 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000424 SourceLocation Loc = ConsumeToken();
425 Handler = ParseSEHExceptBlock(Loc);
426 } else if (Tok.is(tok::kw___finally)) {
427 SourceLocation Loc = ConsumeToken();
428 Handler = ParseSEHFinallyBlock(Loc);
429 } else {
430 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
431 }
432
433 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000434 return Handler;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000435
436 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
437 TryLoc,
438 TryBlock.take(),
439 Handler.take());
440}
441
442/// ParseSEHExceptBlock - Handle __except
443///
444/// seh-except-block:
445/// '__except' '(' seh-filter-expression ')' compound-statement
446///
447StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
448 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
449 raii2(Ident___exception_code, false),
450 raii3(Ident_GetExceptionCode, false);
451
452 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
453 return StmtError();
454
455 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
456
David Blaikie4e4d0842012-03-11 07:00:24 +0000457 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000458 Ident__exception_info->setIsPoisoned(false);
459 Ident___exception_info->setIsPoisoned(false);
460 Ident_GetExceptionInfo->setIsPoisoned(false);
461 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000462 ExprResult FilterExpr(ParseExpression());
Francois Pichetd7f02df2011-04-28 03:14:31 +0000463
David Blaikie4e4d0842012-03-11 07:00:24 +0000464 if (getLangOpts().Borland) {
Francois Pichetd7f02df2011-04-28 03:14:31 +0000465 Ident__exception_info->setIsPoisoned(true);
466 Ident___exception_info->setIsPoisoned(true);
467 Ident_GetExceptionInfo->setIsPoisoned(true);
468 }
John Wiegley28bbe4b2011-04-28 01:08:34 +0000469
470 if(FilterExpr.isInvalid())
471 return StmtError();
472
473 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
474 return StmtError();
475
Richard Smith534986f2012-04-14 00:33:13 +0000476 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000477
478 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000479 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000480
481 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
482}
483
484/// ParseSEHFinallyBlock - Handle __finally
485///
486/// seh-finally-block:
487/// '__finally' compound-statement
488///
489StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
490 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
491 raii2(Ident___abnormal_termination, false),
492 raii3(Ident_AbnormalTermination, false);
493
Richard Smith534986f2012-04-14 00:33:13 +0000494 StmtResult Block(ParseCompoundStatement());
John Wiegley28bbe4b2011-04-28 01:08:34 +0000495 if(Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000496 return Block;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000497
498 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor312eadb2011-04-24 05:37:28 +0000499}
500
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000501/// ParseLabeledStatement - We have an identifier and a ':' after it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000502///
503/// labeled-statement:
504/// identifier ':' statement
505/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000506///
Richard Smith534986f2012-04-14 00:33:13 +0000507StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000508 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
509 "Not an identifier!");
510
511 Token IdentTok = Tok; // Save the whole token.
512 ConsumeToken(); // eat the identifier.
513
514 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000515
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000516 // identifier ':' statement
517 SourceLocation ColonLoc = ConsumeToken();
518
Richard Smith93982a72013-11-15 22:45:29 +0000519 // Read label attributes, if present.
520 StmtResult SubStmt;
521 if (Tok.is(tok::kw___attribute)) {
522 ParsedAttributesWithRange TempAttrs(AttrFactory);
523 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000524
Richard Smith93982a72013-11-15 22:45:29 +0000525 // In C++, GNU attributes only apply to the label if they are followed by a
526 // semicolon, to disambiguate label attributes from attributes on a labeled
527 // declaration.
528 //
529 // This doesn't quite match what GCC does; if the attribute list is empty
530 // and followed by a semicolon, GCC will reject (it appears to parse the
531 // attributes as part of a statement in that case). That looks like a bug.
532 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
533 attrs.takeAllFrom(TempAttrs);
534 else if (isDeclarationStatement()) {
535 StmtVector Stmts;
536 // FIXME: We should do this whether or not we have a declaration
537 // statement, but that doesn't work correctly (because ProhibitAttributes
538 // can't handle GNU attributes), so only call it in the one case where
539 // GNU attributes are allowed.
540 SubStmt = ParseStatementOrDeclarationAfterAttributes(
541 Stmts, /*OnlyStmts*/ true, 0, TempAttrs);
542 if (!TempAttrs.empty() && !SubStmt.isInvalid())
543 SubStmt = Actions.ProcessStmtAttributes(
544 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
545 } else {
546 Diag(Tok, diag::err_expected_semi_after) << "__attribute__";
547 }
548 }
549
550 // If we've not parsed a statement yet, parse one now.
551 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
552 SubStmt = ParseStatement();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000553
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000554 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000555 if (SubStmt.isInvalid())
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000556 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000557
Chris Lattner337e5502011-02-18 01:27:55 +0000558 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
559 IdentTok.getLocation());
Richard Smith534986f2012-04-14 00:33:13 +0000560 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattner337e5502011-02-18 01:27:55 +0000561 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smith534986f2012-04-14 00:33:13 +0000562 attrs.clear();
563 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000564
Chris Lattner337e5502011-02-18 01:27:55 +0000565 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
566 SubStmt.get());
Argyrios Kyrtzidisf7da7262008-07-09 22:53:07 +0000567}
Reid Spencer5f016e22007-07-11 17:01:13 +0000568
569/// ParseCaseStatement
570/// labeled-statement:
571/// 'case' constant-expression ':' statement
572/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
573///
Richard Smith534986f2012-04-14 00:33:13 +0000574StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smith46f11102011-04-21 22:48:40 +0000575 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner24e1e702009-03-04 04:23:07 +0000577 // It is very very common for code to contain many case statements recursively
578 // nested, as in (but usually without indentation):
579 // case 1:
580 // case 2:
581 // case 3:
582 // case 4:
583 // case 5: etc.
584 //
585 // Parsing this naively works, but is both inefficient and can cause us to run
586 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner26140c62009-03-04 18:24:58 +0000587 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner24e1e702009-03-04 04:23:07 +0000588 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smith93982a72013-11-15 22:45:29 +0000589 // weirdness in the actions), so this is just local grossness :).
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattner24e1e702009-03-04 04:23:07 +0000591 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
592 // example above.
John McCall60d7b3a2010-08-24 06:29:42 +0000593 StmtResult TopLevelCase(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Chris Lattner24e1e702009-03-04 04:23:07 +0000595 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
596 // gets updated each time a new case is parsed, and whose body is unset so
597 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieub2fc6902011-09-09 02:16:15 +0000598 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Chris Lattner24e1e702009-03-04 04:23:07 +0000600 // While we have case statements, eat and stack them.
David Majnemer0e1e69c2011-06-13 05:50:12 +0000601 SourceLocation ColonLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000602 do {
Richard Trieubb9b80c2011-04-21 21:44:26 +0000603 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
604 ConsumeToken(); // eat the 'case'.
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000606 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +0000607 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000608 cutOffParsing();
609 return StmtError();
Douglas Gregor3e1005f2009-09-21 18:10:23 +0000610 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000611
Chris Lattner6fb09c82009-12-10 00:38:54 +0000612 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
613 /// Disable this form of error recovery while we're parsing the case
614 /// expression.
615 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000616
Richard Trieubb9b80c2011-04-21 21:44:26 +0000617 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
618 MissingCase = false;
Chris Lattner24e1e702009-03-04 04:23:07 +0000619 if (LHS.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 SkipUntil(tok::colon);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000621 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000623
Chris Lattner24e1e702009-03-04 04:23:07 +0000624 // GNU case range extension.
625 SourceLocation DotDotDotLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000626 ExprResult RHS;
Chris Lattner24e1e702009-03-04 04:23:07 +0000627 if (Tok.is(tok::ellipsis)) {
628 Diag(Tok, diag::ext_gnu_case_range);
629 DotDotDotLoc = ConsumeToken();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000630
Chris Lattner24e1e702009-03-04 04:23:07 +0000631 RHS = ParseConstantExpression();
632 if (RHS.isInvalid()) {
633 SkipUntil(tok::colon);
634 return StmtError();
635 }
636 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000637
Chris Lattner6fb09c82009-12-10 00:38:54 +0000638 ColonProtection.restore();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000639
John McCallf6a3ab02011-01-22 09:28:32 +0000640 if (Tok.is(tok::colon)) {
641 ColonLoc = ConsumeToken();
642
643 // Treat "case blah;" as a typo for "case blah:".
644 } else if (Tok.is(tok::semi)) {
645 ColonLoc = ConsumeToken();
646 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
647 << FixItHint::CreateReplacement(ColonLoc, ":");
648 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000649 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
650 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
651 << FixItHint::CreateInsertion(ExpectedLoc, ":");
652 ColonLoc = ExpectedLoc;
Chris Lattner24e1e702009-03-04 04:23:07 +0000653 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000654
John McCall60d7b3a2010-08-24 06:29:42 +0000655 StmtResult Case =
John McCall9ae2f072010-08-23 23:25:46 +0000656 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
657 RHS.get(), ColonLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattner24e1e702009-03-04 04:23:07 +0000659 // If we had a sema error parsing this case, then just ignore it and
660 // continue parsing the sub-stmt.
661 if (Case.isInvalid()) {
662 if (TopLevelCase.isInvalid()) // No parsed case stmts.
663 return ParseStatement();
664 // Otherwise, just don't add it as a nested case.
665 } else {
666 // If this is the first case statement we parsed, it becomes TopLevelCase.
667 // Otherwise we link it into the current chain.
John McCallca0408f2010-08-23 06:44:23 +0000668 Stmt *NextDeepest = Case.get();
Chris Lattner24e1e702009-03-04 04:23:07 +0000669 if (TopLevelCase.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000670 TopLevelCase = Case;
Chris Lattner24e1e702009-03-04 04:23:07 +0000671 else
John McCall9ae2f072010-08-23 23:25:46 +0000672 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner24e1e702009-03-04 04:23:07 +0000673 DeepestParsedCaseStmt = NextDeepest;
674 }
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Chris Lattner24e1e702009-03-04 04:23:07 +0000676 // Handle all case statements.
677 } while (Tok.is(tok::kw_case));
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattner24e1e702009-03-04 04:23:07 +0000679 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Chris Lattner24e1e702009-03-04 04:23:07 +0000681 // If we found a non-case statement, start by parsing it.
John McCall60d7b3a2010-08-24 06:29:42 +0000682 StmtResult SubStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner24e1e702009-03-04 04:23:07 +0000684 if (Tok.isNot(tok::r_brace)) {
685 SubStmt = ParseStatement();
686 } else {
687 // Nicely diagnose the common error "switch (X) { case 4: }", which is
688 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000689 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000690 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
691 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner24e1e702009-03-04 04:23:07 +0000692 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000693 }
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner24e1e702009-03-04 04:23:07 +0000695 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000696 if (SubStmt.isInvalid())
Chris Lattner24e1e702009-03-04 04:23:07 +0000697 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattner24e1e702009-03-04 04:23:07 +0000699 // Install the body into the most deeply-nested case.
John McCall9ae2f072010-08-23 23:25:46 +0000700 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl61364dd2008-12-11 19:30:53 +0000701
Chris Lattner24e1e702009-03-04 04:23:07 +0000702 // Return the top level parsed statement tree.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000703 return TopLevelCase;
Reid Spencer5f016e22007-07-11 17:01:13 +0000704}
705
706/// ParseDefaultStatement
707/// labeled-statement:
708/// 'default' ':' statement
709/// Note that this does not parse the 'statement' at the end.
710///
Richard Smith534986f2012-04-14 00:33:13 +0000711StmtResult Parser::ParseDefaultStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000712 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
714
Douglas Gregor662a4822010-12-23 22:56:40 +0000715 SourceLocation ColonLoc;
John McCallf6a3ab02011-01-22 09:28:32 +0000716 if (Tok.is(tok::colon)) {
717 ColonLoc = ConsumeToken();
718
719 // Treat "default;" as a typo for "default:".
720 } else if (Tok.is(tok::semi)) {
721 ColonLoc = ConsumeToken();
722 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
723 << FixItHint::CreateReplacement(ColonLoc, ":");
724 } else {
Douglas Gregor662a4822010-12-23 22:56:40 +0000725 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
726 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
727 << FixItHint::CreateInsertion(ExpectedLoc, ":");
728 ColonLoc = ExpectedLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000730
Richard Smith85b29a42012-02-17 01:35:32 +0000731 StmtResult SubStmt;
732
733 if (Tok.isNot(tok::r_brace)) {
734 SubStmt = ParseStatement();
735 } else {
736 // Diagnose the common error "switch (X) {... default: }", which is
737 // not valid.
David Majnemer63f04ab2011-06-14 15:24:38 +0000738 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith85b29a42012-02-17 01:35:32 +0000739 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
740 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
741 SubStmt = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 }
743
Richard Smith85b29a42012-02-17 01:35:32 +0000744 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000745 if (SubStmt.isInvalid())
Richard Smith85b29a42012-02-17 01:35:32 +0000746 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl61364dd2008-12-11 19:30:53 +0000747
Sebastian Redl117054a2008-12-28 16:13:43 +0000748 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000749 SubStmt.get(), getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +0000750}
751
Richard Smith534986f2012-04-14 00:33:13 +0000752StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
753 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregorbca01b42011-07-06 22:04:06 +0000754}
Reid Spencer5f016e22007-07-11 17:01:13 +0000755
756/// ParseCompoundStatement - Parse a "{}" block.
757///
758/// compound-statement: [C99 6.8.2]
759/// { block-item-list[opt] }
760/// [GNU] { label-declarations block-item-list } [TODO]
761///
762/// block-item-list:
763/// block-item
764/// block-item-list block-item
765///
766/// block-item:
767/// declaration
Chris Lattner45a566c2007-08-27 01:01:57 +0000768/// [GNU] '__extension__' declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000769/// statement
770/// [OMP] openmp-directive [TODO]
771///
772/// [GNU] label-declarations:
773/// [GNU] label-declaration
774/// [GNU] label-declarations label-declaration
775///
776/// [GNU] label-declaration:
777/// [GNU] '__label__' identifier-list ';'
778///
779/// [OMP] openmp-directive: [TODO]
780/// [OMP] barrier-directive
781/// [OMP] flush-directive
782///
Richard Smith534986f2012-04-14 00:33:13 +0000783StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000784 unsigned ScopeFlags) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000785 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl61364dd2008-12-11 19:30:53 +0000786
Chris Lattner31e05722007-08-26 06:24:45 +0000787 // Enter a scope to hold everything within the compound stmt. Compound
788 // statements can always hold declarations.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000789 ParseScope CompoundScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +0000790
791 // Parse the statements in the body.
Sebastian Redl61364dd2008-12-11 19:30:53 +0000792 return ParseCompoundStatementBody(isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000793}
794
Lang Hamesa60d21d2012-11-03 22:29:05 +0000795/// Parse any pragmas at the start of the compound expression. We handle these
796/// separately since some pragmas (FP_CONTRACT) must appear before any C
797/// statement in the compound, but may be intermingled with other pragmas.
798void Parser::ParseCompoundStatementLeadingPragmas() {
799 bool checkForPragmas = true;
800 while (checkForPragmas) {
801 switch (Tok.getKind()) {
802 case tok::annot_pragma_vis:
803 HandlePragmaVisibility();
804 break;
805 case tok::annot_pragma_pack:
806 HandlePragmaPack();
807 break;
808 case tok::annot_pragma_msstruct:
809 HandlePragmaMSStruct();
810 break;
811 case tok::annot_pragma_align:
812 HandlePragmaAlign();
813 break;
814 case tok::annot_pragma_weak:
815 HandlePragmaWeak();
816 break;
817 case tok::annot_pragma_weakalias:
818 HandlePragmaWeakAlias();
819 break;
820 case tok::annot_pragma_redefine_extname:
821 HandlePragmaRedefineExtname();
822 break;
823 case tok::annot_pragma_opencl_extension:
824 HandlePragmaOpenCLExtension();
825 break;
826 case tok::annot_pragma_fp_contract:
827 HandlePragmaFPContract();
828 break;
829 default:
830 checkForPragmas = false;
831 break;
832 }
833 }
834
835}
836
Reid Spencer5f016e22007-07-11 17:01:13 +0000837/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff1b273c42007-09-16 14:56:35 +0000838/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Reid Spencer5f016e22007-07-11 17:01:13 +0000839/// consume the '}' at the end of the block. It does not manipulate the scope
840/// stack.
John McCall60d7b3a2010-08-24 06:29:42 +0000841StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump1eb44332009-09-09 15:08:12 +0000842 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerae50fa02009-03-05 00:00:31 +0000843 Tok.getLocation(),
844 "in compound statement ('{}')");
Lang Hamesbe9af122012-10-02 04:45:10 +0000845
846 // Record the state of the FP_CONTRACT pragma, restore on leaving the
847 // compound statement.
848 Sema::FPContractStateRAII SaveFPContractState(Actions);
849
Douglas Gregor0fbda682010-09-15 14:51:05 +0000850 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000851 BalancedDelimiterTracker T(*this, tok::l_brace);
852 if (T.consumeOpen())
853 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000854
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000855 Sema::CompoundScopeRAII CompoundScope(Actions);
856
Lang Hamesa60d21d2012-11-03 22:29:05 +0000857 // Parse any pragmas at the beginning of the compound statement.
858 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000859
Lang Hamesa60d21d2012-11-03 22:29:05 +0000860 StmtVector Stmts;
Lang Hames860022c2012-10-21 01:10:01 +0000861
Chris Lattner4ae493c2011-02-18 02:08:43 +0000862 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
863 // only allowed at the start of a compound stmt regardless of the language.
864 while (Tok.is(tok::kw___label__)) {
865 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000866
Chris Lattner5f9e2722011-07-23 10:55:15 +0000867 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4ae493c2011-02-18 02:08:43 +0000868 while (1) {
869 if (Tok.isNot(tok::identifier)) {
870 Diag(Tok, diag::err_expected_ident);
871 break;
872 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000873
Chris Lattner4ae493c2011-02-18 02:08:43 +0000874 IdentifierInfo *II = Tok.getIdentifierInfo();
875 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara67843042011-03-05 18:21:20 +0000876 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000877
Chris Lattner4ae493c2011-02-18 02:08:43 +0000878 if (!Tok.is(tok::comma))
879 break;
880 ConsumeToken();
881 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000882
John McCall0b7e6782011-03-24 11:26:52 +0000883 DeclSpec DS(AttrFactory);
Rafael Espindola4549d7f2013-07-09 12:05:01 +0000884 DeclGroupPtrTy Res =
885 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000886 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000887
Chris Lattner8bb21d32012-04-28 16:12:17 +0000888 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner4ae493c2011-02-18 02:08:43 +0000889 if (R.isUsable())
890 Stmts.push_back(R.release());
891 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000892
Chris Lattner4ae493c2011-02-18 02:08:43 +0000893 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisb918d0f2011-01-17 18:58:44 +0000894 if (Tok.is(tok::annot_pragma_unused)) {
895 HandlePragmaUnused();
896 continue;
897 }
898
David Blaikie4e4d0842012-03-11 07:00:24 +0000899 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet1e862692011-05-06 20:48:22 +0000900 Tok.is(tok::kw___if_not_exists))) {
901 ParseMicrosoftIfExistsStatement(Stmts);
902 continue;
903 }
904
John McCall60d7b3a2010-08-24 06:29:42 +0000905 StmtResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000906 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000907 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattner45a566c2007-08-27 01:01:57 +0000908 } else {
909 // __extension__ can start declarations and it can also be a unary
910 // operator for expressions. Consume multiple __extension__ markers here
911 // until we can determine which is which.
Eli Friedmanadf077f2009-01-27 08:43:38 +0000912 // FIXME: This loses extension expressions in the AST!
Chris Lattner45a566c2007-08-27 01:01:57 +0000913 SourceLocation ExtLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000914 while (Tok.is(tok::kw___extension__))
Chris Lattner45a566c2007-08-27 01:01:57 +0000915 ConsumeToken();
Chris Lattner39146d62008-10-20 06:51:33 +0000916
John McCall0b7e6782011-03-24 11:26:52 +0000917 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +0000918 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Sean Huntbbd37c62009-11-21 08:43:09 +0000919
Chris Lattner45a566c2007-08-27 01:01:57 +0000920 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis5404a152008-10-05 00:06:24 +0000921 if (isDeclarationStatement()) {
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000922 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner97144fc2009-04-02 04:16:50 +0000923 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedmanbc6c8482009-05-16 23:40:44 +0000924 ExtensionRAIIObject O(Diags);
925
Chris Lattner97144fc2009-04-02 04:16:50 +0000926 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +0000927 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
928 Declarator::BlockContext, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000929 attrs);
Chris Lattner97144fc2009-04-02 04:16:50 +0000930 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattner45a566c2007-08-27 01:01:57 +0000931 } else {
Eli Friedmanadf077f2009-01-27 08:43:38 +0000932 // Otherwise this was a unary __extension__ marker.
John McCall60d7b3a2010-08-24 06:29:42 +0000933 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattner043a0b52008-03-13 06:32:11 +0000934
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000935 if (Res.isInvalid()) {
Chris Lattner45a566c2007-08-27 01:01:57 +0000936 SkipUntil(tok::semi);
937 continue;
938 }
Sebastian Redlf512e822009-01-18 18:03:53 +0000939
Sean Huntbbd37c62009-11-21 08:43:09 +0000940 // FIXME: Use attributes?
Chris Lattner39146d62008-10-20 06:51:33 +0000941 // Eat the semicolon at the end of stmt and convert the expr into a
942 // statement.
Douglas Gregor9ba23b42010-09-07 15:23:11 +0000943 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith41956372013-01-14 22:39:08 +0000944 R = Actions.ActOnExprStmt(Res);
Chris Lattner45a566c2007-08-27 01:01:57 +0000945 }
946 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000947
Sebastian Redl0e9eabc2008-12-09 13:15:23 +0000948 if (R.isUsable())
Sebastian Redleffa8d12008-12-10 00:02:53 +0000949 Stmts.push_back(R.release());
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 }
Sebastian Redl61364dd2008-12-11 19:30:53 +0000951
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000952 SourceLocation CloseLoc = Tok.getLocation();
953
Reid Spencer5f016e22007-07-11 17:01:13 +0000954 // We broke out of the while loop because we found a '}' or EOF.
Nico Weberd11f4352012-12-30 23:36:56 +0000955 if (!T.consumeClose())
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000956 // Recover by creating a compound statement with what we parsed so far,
957 // instead of dropping everything and returning StmtError();
Nico Weberd11f4352012-12-30 23:36:56 +0000958 CloseLoc = T.getCloseLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +0000959
Argyrios Kyrtzidis5d5ed592012-03-24 02:26:51 +0000960 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000961 Stmts, isStmtExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000962}
963
Chris Lattner15ff1112008-12-12 06:31:07 +0000964/// ParseParenExprOrCondition:
965/// [C ] '(' expression ')'
Chris Lattnerff871fb2008-12-12 06:35:28 +0000966/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattner15ff1112008-12-12 06:31:07 +0000967///
968/// This function parses and performs error recovery on the specified condition
969/// or expression (depending on whether we're in C++ or C mode). This function
970/// goes out of its way to recover well. It returns true if there was a parser
971/// error (the right paren couldn't be found), which indicates that the caller
972/// should try to recover harder. It returns false if the condition is
973/// successfully parsed. Note that a successful parse can still have semantic
974/// errors in the condition.
John McCall60d7b3a2010-08-24 06:29:42 +0000975bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCalld226f652010-08-21 09:40:31 +0000976 Decl *&DeclResult,
Douglas Gregor586596f2010-05-06 17:25:47 +0000977 SourceLocation Loc,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000978 bool ConvertToBoolean) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000979 BalancedDelimiterTracker T(*this, tok::l_paren);
980 T.consumeOpen();
981
David Blaikie4e4d0842012-03-11 07:00:24 +0000982 if (getLangOpts().CPlusPlus)
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000983 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000984 else {
985 ExprResult = ParseExpression();
John McCalld226f652010-08-21 09:40:31 +0000986 DeclResult = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000987
Douglas Gregor586596f2010-05-06 17:25:47 +0000988 // If required, convert to a boolean value.
989 if (!ExprResult.isInvalid() && ConvertToBoolean)
990 ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000991 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner15ff1112008-12-12 06:31:07 +0000994 // If the parser was confused by the condition and we don't have a ')', try to
995 // recover by skipping ahead to a semi and bailing out. If condexp is
996 // semantically invalid but we have well formed code, keep going.
John McCalld226f652010-08-21 09:40:31 +0000997 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattner15ff1112008-12-12 06:31:07 +0000998 SkipUntil(tok::semi);
999 // Skipping may have stopped if it found the containing ')'. If so, we can
1000 // continue parsing the if statement.
1001 if (Tok.isNot(tok::r_paren))
1002 return true;
1003 }
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Chris Lattner15ff1112008-12-12 06:31:07 +00001005 // Otherwise the condition is valid or the rparen is present.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001006 T.consumeClose();
Chad Rosierb6604462012-07-10 21:35:27 +00001007
Chris Lattnerbddc7e52012-04-28 16:24:20 +00001008 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1009 // that all callers are looking for a statement after the condition, so ")"
1010 // isn't valid.
1011 while (Tok.is(tok::r_paren)) {
1012 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1013 << FixItHint::CreateRemoval(Tok.getLocation());
1014 ConsumeParen();
1015 }
Chad Rosierb6604462012-07-10 21:35:27 +00001016
Chris Lattner15ff1112008-12-12 06:31:07 +00001017 return false;
1018}
1019
1020
Reid Spencer5f016e22007-07-11 17:01:13 +00001021/// ParseIfStatement
1022/// if-statement: [C99 6.8.4.1]
1023/// 'if' '(' expression ')' statement
1024/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001025/// [C++] 'if' '(' condition ')' statement
1026/// [C++] 'if' '(' condition ')' statement 'else' statement
Reid Spencer5f016e22007-07-11 17:01:13 +00001027///
Richard Smith534986f2012-04-14 00:33:13 +00001028StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001029 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1031
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001032 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001033 Diag(Tok, diag::err_expected_lparen_after) << "if";
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 SkipUntil(tok::semi);
Sebastian Redl61364dd2008-12-11 19:30:53 +00001035 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001037
David Blaikie4e4d0842012-03-11 07:00:24 +00001038 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001039
Chris Lattner22153252007-08-26 23:08:06 +00001040 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1041 // the case for C90.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001042 //
1043 // C++ 6.4p3:
1044 // A name introduced by a declaration in a condition is in scope from its
1045 // point of declaration until the end of the substatements controlled by the
1046 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001047 // C++ 3.3.2p4:
1048 // Names declared in the for-init-statement, and in the condition of if,
1049 // while, for, and switch statements are local to the if, while, for, or
1050 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001051 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001052 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner22153252007-08-26 23:08:06 +00001053
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001055 ExprResult CondExp;
John McCalld226f652010-08-21 09:40:31 +00001056 Decl *CondVar = 0;
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001057 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001058 return StmtError();
Chris Lattner18914bc2008-12-12 06:19:11 +00001059
David Blaikiedef07622012-05-16 04:20:04 +00001060 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattner0ecea032007-08-22 05:28:50 +00001062 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001063 // there is no compound stmt. C90 does not have this clause. We only do this
1064 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001065 //
1066 // C++ 6.4p1:
1067 // The substatement in a selection-statement (each substatement, in the else
1068 // form of the if statement) implicitly defines a local scope.
1069 //
1070 // For C++ we create a scope for the condition and a new scope for
1071 // substatements because:
1072 // -When the 'then' scope exits, we want the condition declaration to still be
1073 // active for the 'else' scope too.
1074 // -Sema will detect name clashes by considering declarations of a
1075 // 'ControlScope' as part of its direct subscope.
1076 // -If we wanted the condition and substatement to be in the same scope, we
1077 // would have to notify ParseStatement not to create a new scope. It's
1078 // simpler to let it create a new scope.
1079 //
Mike Stump1eb44332009-09-09 15:08:12 +00001080 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001081 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001082
Chris Lattnerb96728d2007-10-29 05:08:52 +00001083 // Read the 'then' stmt.
1084 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber5cb94a72011-12-22 23:26:17 +00001085
1086 SourceLocation InnerStatementTrailingElseLoc;
1087 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001088
Chris Lattnera36ce712007-08-22 05:16:28 +00001089 // Pop the 'if' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001090 InnerScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001091
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 // If it has an else, parse it.
1093 SourceLocation ElseLoc;
Chris Lattnerb96728d2007-10-29 05:08:52 +00001094 SourceLocation ElseStmtLoc;
John McCall60d7b3a2010-08-24 06:29:42 +00001095 StmtResult ElseStmt;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001096
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001097 if (Tok.is(tok::kw_else)) {
Nico Weber5cb94a72011-12-22 23:26:17 +00001098 if (TrailingElseLoc)
1099 *TrailingElseLoc = Tok.getLocation();
1100
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 ElseLoc = ConsumeToken();
Chris Lattner966c78b2010-04-12 06:12:50 +00001102 ElseStmtLoc = Tok.getLocation();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001103
Chris Lattner0ecea032007-08-22 05:28:50 +00001104 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001105 // there is no compound stmt. C90 does not have this clause. We only do
1106 // this if the body isn't a compound statement to avoid push/pop in common
1107 // cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001108 //
1109 // C++ 6.4p1:
1110 // The substatement in a selection-statement (each substatement, in the else
1111 // form of the if statement) implicitly defines a local scope.
1112 //
Sebastian Redl61364dd2008-12-11 19:30:53 +00001113 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001114 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001115
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 ElseStmt = ParseStatement();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001117
Chris Lattnera36ce712007-08-22 05:16:28 +00001118 // Pop the 'else' scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001119 InnerScope.Exit();
Douglas Gregord2d8be62011-07-30 08:36:53 +00001120 } else if (Tok.is(tok::code_completion)) {
1121 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001122 cutOffParsing();
1123 return StmtError();
Nico Weber5cb94a72011-12-22 23:26:17 +00001124 } else if (InnerStatementTrailingElseLoc.isValid()) {
1125 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00001127
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001128 IfScope.Exit();
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Chris Lattnerb96728d2007-10-29 05:08:52 +00001130 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump1eb44332009-09-09 15:08:12 +00001131 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattnerb96728d2007-10-29 05:08:52 +00001132 // part. If both are invalid, return error.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001133 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1134 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1135 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redla55e52c2008-11-25 22:21:31 +00001136 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl61364dd2008-12-11 19:30:53 +00001137 return StmtError();
Chris Lattnerb96728d2007-10-29 05:08:52 +00001138 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001139
Chris Lattnerb96728d2007-10-29 05:08:52 +00001140 // Now if either are invalid, replace with a ';'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001141 if (ThenStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001142 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001143 if (ElseStmt.isInvalid())
Chris Lattnerb96728d2007-10-29 05:08:52 +00001144 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001145
John McCall9ae2f072010-08-23 23:25:46 +00001146 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +00001147 ElseLoc, ElseStmt.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001148}
1149
1150/// ParseSwitchStatement
1151/// switch-statement:
1152/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001153/// [C++] 'switch' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001154StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001155 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1157
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001158 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001159 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001161 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 }
Chris Lattner22153252007-08-26 23:08:06 +00001163
David Blaikie4e4d0842012-03-11 07:00:24 +00001164 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001165
Chris Lattner22153252007-08-26 23:08:06 +00001166 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1167 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001168 //
1169 // C++ 6.4p3:
1170 // A name introduced by a declaration in a condition is in scope from its
1171 // point of declaration until the end of the substatements controlled by the
1172 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001173 // C++ 3.3.2p4:
1174 // Names declared in the for-init-statement, and in the condition of if,
1175 // while, for, and switch statements are local to the if, while, for, or
1176 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001177 //
Richard Trieubb9b80c2011-04-21 21:44:26 +00001178 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattner15ff1112008-12-12 06:31:07 +00001179 if (C99orCXX)
1180 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001181 ParseScope SwitchScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001182
1183 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001184 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001185 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001186 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redl9a920342008-12-11 19:48:14 +00001187 return StmtError();
Eli Friedman2342ef72008-12-17 22:19:57 +00001188
John McCall60d7b3a2010-08-24 06:29:42 +00001189 StmtResult Switch
John McCall9ae2f072010-08-23 23:25:46 +00001190 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001191
Douglas Gregor586596f2010-05-06 17:25:47 +00001192 if (Switch.isInvalid()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001193 // Skip the switch body.
Douglas Gregor586596f2010-05-06 17:25:47 +00001194 // FIXME: This is not optimal recovery, but parsing the body is more
1195 // dangerous due to the presence of case and default statements, which
1196 // will have no place to connect back with the switch.
Douglas Gregor4186ff42010-05-20 23:20:59 +00001197 if (Tok.is(tok::l_brace)) {
1198 ConsumeBrace();
1199 SkipUntil(tok::r_brace, false, false);
1200 } else
Douglas Gregor586596f2010-05-06 17:25:47 +00001201 SkipUntil(tok::semi);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001202 return Switch;
Douglas Gregor586596f2010-05-06 17:25:47 +00001203 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001204
Chris Lattner0ecea032007-08-22 05:28:50 +00001205 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001206 // there is no compound stmt. C90 does not have this clause. We only do this
1207 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001208 //
1209 // C++ 6.4p1:
1210 // The substatement in a selection-statement (each substatement, in the else
1211 // form of the if statement) implicitly defines a local scope.
1212 //
1213 // See comments in ParseIfStatement for why we create a scope for the
1214 // condition and a new scope for substatement in C++.
1215 //
Mike Stump1eb44332009-09-09 15:08:12 +00001216 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001217 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl61364dd2008-12-11 19:30:53 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001220 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001221
Chris Lattner7e52de42010-01-24 01:50:29 +00001222 // Pop the scopes.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001223 InnerScope.Exit();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001224 SwitchScope.Exit();
Sebastian Redl61364dd2008-12-11 19:30:53 +00001225
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001226 if (Body.isInvalid()) {
Chris Lattner7e52de42010-01-24 01:50:29 +00001227 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001228
1229 // Put the synthesized null statement on the same line as the end of switch
1230 // condition.
1231 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1232 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1233 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001234
John McCall9ae2f072010-08-23 23:25:46 +00001235 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001236}
1237
1238/// ParseWhileStatement
1239/// while-statement: [C99 6.8.5.1]
1240/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001241/// [C++] 'while' '(' condition ')' statement
Richard Smith534986f2012-04-14 00:33:13 +00001242StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001243 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 SourceLocation WhileLoc = Tok.getLocation();
1245 ConsumeToken(); // eat the 'while'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001246
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001247 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001248 Diag(Tok, diag::err_expected_lparen_after) << "while";
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001250 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001252
David Blaikie4e4d0842012-03-11 07:00:24 +00001253 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001254
Chris Lattner22153252007-08-26 23:08:06 +00001255 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1256 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001257 //
1258 // C++ 6.4p3:
1259 // A name introduced by a declaration in a condition is in scope from its
1260 // point of declaration until the end of the substatements controlled by the
1261 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001262 // C++ 3.3.2p4:
1263 // Names declared in the for-init-statement, and in the condition of if,
1264 // while, for, and switch statements are local to the if, while, for, or
1265 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001266 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001267 unsigned ScopeFlags;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001268 if (C99orCXX)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001269 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1270 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001271 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001272 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1273 ParseScope WhileScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001274
1275 // Parse the condition.
John McCall60d7b3a2010-08-24 06:29:42 +00001276 ExprResult Cond;
John McCalld226f652010-08-21 09:40:31 +00001277 Decl *CondVar = 0;
Douglas Gregor586596f2010-05-06 17:25:47 +00001278 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattner15ff1112008-12-12 06:31:07 +00001279 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001280
David Blaikiedef07622012-05-16 04:20:04 +00001281 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner0ecea032007-08-22 05:28:50 +00001283 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001284 // there is no compound stmt. C90 does not have this clause. We only do this
1285 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001286 //
1287 // C++ 6.5p2:
1288 // The substatement in an iteration-statement implicitly defines a local scope
1289 // which is entered and exited each time through the loop.
1290 //
1291 // See comments in ParseIfStatement for why we create a scope for the
1292 // condition and a new scope for substatement in C++.
1293 //
Mike Stump1eb44332009-09-09 15:08:12 +00001294 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001295 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001296
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001298 StmtResult Body(ParseStatement(TrailingElseLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001299
Chris Lattner0ecea032007-08-22 05:28:50 +00001300 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001301 InnerScope.Exit();
1302 WhileScope.Exit();
Sebastian Redl9a920342008-12-11 19:48:14 +00001303
John McCalld226f652010-08-21 09:40:31 +00001304 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001305 return StmtError();
1306
John McCall9ae2f072010-08-23 23:25:46 +00001307 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Reid Spencer5f016e22007-07-11 17:01:13 +00001308}
1309
1310/// ParseDoStatement
1311/// do-statement: [C99 6.8.5.2]
1312/// 'do' statement 'while' '(' expression ')' ';'
1313/// Note: this lets the caller parse the end ';'.
Richard Smith534986f2012-04-14 00:33:13 +00001314StmtResult Parser::ParseDoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001315 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001317
Chris Lattner22153252007-08-26 23:08:06 +00001318 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1319 // the case for C90. Start the loop scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001320 unsigned ScopeFlags;
David Blaikie4e4d0842012-03-11 07:00:24 +00001321 if (getLangOpts().C99)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001322 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner22153252007-08-26 23:08:06 +00001323 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001324 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redl9a920342008-12-11 19:48:14 +00001325
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001326 ParseScope DoScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001327
Chris Lattner0ecea032007-08-22 05:28:50 +00001328 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001329 // there is no compound stmt. C90 does not have this clause. We only do this
1330 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis143db712008-09-11 04:46:46 +00001331 //
1332 // C++ 6.5p2:
1333 // The substatement in an iteration-statement implicitly defines a local scope
1334 // which is entered and exited each time through the loop.
1335 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001336 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikie4e4d0842012-03-11 07:00:24 +00001337 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001338 Tok.isNot(tok::l_brace));
Sebastian Redl9a920342008-12-11 19:48:14 +00001339
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 // Read the body statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001341 StmtResult Body(ParseStatement());
Reid Spencer5f016e22007-07-11 17:01:13 +00001342
Chris Lattner0ecea032007-08-22 05:28:50 +00001343 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001344 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001345
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001346 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001347 if (!Body.isInvalid()) {
Chris Lattner19504402008-11-13 18:52:53 +00001348 Diag(Tok, diag::err_expected_while);
Chris Lattner28eb7e92008-11-23 23:17:07 +00001349 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner19504402008-11-13 18:52:53 +00001350 SkipUntil(tok::semi, false, true);
1351 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001352 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 }
1354 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00001355
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001356 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001357 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner19504402008-11-13 18:52:53 +00001358 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001359 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001361
Richard Smith5eed7e02013-10-15 01:34:54 +00001362 // Parse the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001363 BalancedDelimiterTracker T(*this, tok::l_paren);
1364 T.consumeOpen();
Chad Rosierb6604462012-07-10 21:35:27 +00001365
Richard Smith5eed7e02013-10-15 01:34:54 +00001366 // A do-while expression is not a condition, so can't have attributes.
1367 DiagnoseAndSkipCXX11Attributes();
Sean Hunt2edf0a22012-06-23 05:07:58 +00001368
John McCall60d7b3a2010-08-24 06:29:42 +00001369 ExprResult Cond = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001370 T.consumeClose();
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001371 DoScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001372
Sebastian Redl9a920342008-12-11 19:48:14 +00001373 if (Cond.isInvalid() || Body.isInvalid())
1374 return StmtError();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001375
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001376 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1377 Cond.get(), T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001378}
1379
1380/// ParseForStatement
1381/// for-statement: [C99 6.8.5.3]
1382/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1383/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001384/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1385/// [C++] statement
Richard Smithad762fc2011-04-14 22:09:26 +00001386/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001387/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1388/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001389///
1390/// [C++] for-init-statement:
1391/// [C++] expression-statement
1392/// [C++] simple-declaration
1393///
Richard Smithad762fc2011-04-14 22:09:26 +00001394/// [C++0x] for-range-declaration:
1395/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1396/// [C++0x] for-range-initializer:
1397/// [C++0x] expression
1398/// [C++0x] braced-init-list [TODO]
Richard Smith534986f2012-04-14 00:33:13 +00001399StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001400 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001402
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001403 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00001404 Diag(Tok, diag::err_expected_lparen_after) << "for";
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 SkipUntil(tok::semi);
Sebastian Redl9a920342008-12-11 19:48:14 +00001406 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001408
Chad Rosierb6604462012-07-10 21:35:27 +00001409 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1410 getLangOpts().ObjC1;
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001411
Chris Lattner22153252007-08-26 23:08:06 +00001412 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1413 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001414 //
1415 // C++ 6.4p3:
1416 // A name introduced by a declaration in a condition is in scope from its
1417 // point of declaration until the end of the substatements controlled by the
1418 // condition.
Argyrios Kyrtzidis14d08c02008-09-11 23:08:39 +00001419 // C++ 3.3.2p4:
1420 // Names declared in the for-init-statement, and in the condition of if,
1421 // while, for, and switch statements are local to the if, while, for, or
1422 // switch statement (including the controlled statement).
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001423 // C++ 6.5.3p1:
1424 // Names declared in the for-init-statement are in the same declarative-region
1425 // as those declared in the condition.
1426 //
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001427 unsigned ScopeFlags;
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001428 if (C99orCXXorObjC)
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001429 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1430 Scope::DeclScope | Scope::ControlScope;
Chris Lattner22153252007-08-26 23:08:06 +00001431 else
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001432 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1433
1434 ParseScope ForScope(this, ScopeFlags);
Reid Spencer5f016e22007-07-11 17:01:13 +00001435
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001436 BalancedDelimiterTracker T(*this, tok::l_paren);
1437 T.consumeOpen();
1438
John McCall60d7b3a2010-08-24 06:29:42 +00001439 ExprResult Value;
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001440
Richard Smithad762fc2011-04-14 22:09:26 +00001441 bool ForEach = false, ForRange = false;
John McCall60d7b3a2010-08-24 06:29:42 +00001442 StmtResult FirstPart;
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001443 bool SecondPartIsInvalid = false;
Douglas Gregor586596f2010-05-06 17:25:47 +00001444 FullExprArg SecondPart(Actions);
John McCall60d7b3a2010-08-24 06:29:42 +00001445 ExprResult Collection;
Richard Smithad762fc2011-04-14 22:09:26 +00001446 ForRangeInit ForRangeInit;
Douglas Gregor586596f2010-05-06 17:25:47 +00001447 FullExprArg ThirdPart(Actions);
John McCalld226f652010-08-21 09:40:31 +00001448 Decl *SecondVar = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001449
Douglas Gregor791215b2009-09-21 20:51:25 +00001450 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001451 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallf312b1e2010-08-26 23:41:50 +00001452 C99orCXXorObjC? Sema::PCC_ForInit
1453 : Sema::PCC_Expression);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001454 cutOffParsing();
1455 return StmtError();
Douglas Gregor791215b2009-09-21 20:51:25 +00001456 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001457
Sean Hunt2edf0a22012-06-23 05:07:58 +00001458 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001459 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001460
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 // Parse the first part of the for specifier.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001462 if (Tok.is(tok::semi)) { // for (;
Sean Hunt2edf0a22012-06-23 05:07:58 +00001463 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 // no first part, eat the ';'.
1465 ConsumeToken();
Eli Friedman9490ab42011-12-20 01:50:37 +00001466 } else if (isForInitDeclaration()) { // for (int X = 4;
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 // Parse declaration, which eats the ';'.
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001468 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redl9a920342008-12-11 19:48:14 +00001470
Richard Smithad762fc2011-04-14 22:09:26 +00001471 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikie4e4d0842012-03-11 07:00:24 +00001472 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smithad762fc2011-04-14 22:09:26 +00001473 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1474
Chris Lattner97144fc2009-04-02 04:16:50 +00001475 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001476 StmtVector Stmts;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001477 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smithad762fc2011-04-14 22:09:26 +00001478 DeclEnd, attrs, false,
1479 MightBeForRangeStmt ?
1480 &ForRangeInit : 0);
Chris Lattnercd147752009-03-29 17:27:48 +00001481 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Richard Smithad762fc2011-04-14 22:09:26 +00001483 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001484 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001485 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith8f4fb192011-09-04 19:54:14 +00001486
Richard Smithad762fc2011-04-14 22:09:26 +00001487 ForRange = true;
1488 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattnercd147752009-03-29 17:27:48 +00001489 ConsumeToken();
1490 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +00001491 Actions.ActOnForEachDeclStmt(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001492 // ObjC: for (id x in expr)
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001493 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001494
Douglas Gregorfb629412010-08-23 21:17:50 +00001495 if (Tok.is(tok::code_completion)) {
1496 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001497 cutOffParsing();
1498 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001499 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001500 Collection = ParseExpression();
Chris Lattnercd147752009-03-29 17:27:48 +00001501 } else {
1502 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001503 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 } else {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001505 ProhibitAttributes(attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 Value = ParseExpression();
1507
John McCallf6a16482010-12-04 03:47:34 +00001508 ForEach = isTokIdentifier_in();
1509
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 // Turn the expression into a stmt.
John McCallf6a16482010-12-04 03:47:34 +00001511 if (!Value.isInvalid()) {
1512 if (ForEach)
1513 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1514 else
Richard Smith41956372013-01-14 22:39:08 +00001515 FirstPart = Actions.ActOnExprStmt(Value);
John McCallf6a16482010-12-04 03:47:34 +00001516 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001517
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001518 if (Tok.is(tok::semi)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 ConsumeToken();
John McCallf6a16482010-12-04 03:47:34 +00001520 } else if (ForEach) {
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001521 ConsumeToken(); // consume 'in'
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001522
Douglas Gregorfb629412010-08-23 21:17:50 +00001523 if (Tok.is(tok::code_completion)) {
1524 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001525 cutOffParsing();
1526 return StmtError();
Douglas Gregorfb629412010-08-23 21:17:50 +00001527 }
Douglas Gregor586596f2010-05-06 17:25:47 +00001528 Collection = ParseExpression();
Richard Smith80ad52f2013-01-02 11:42:31 +00001529 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smitha44854a2011-12-20 22:56:20 +00001530 // User tried to write the reasonable, but ill-formed, for-range-statement
1531 // for (expr : expr) { ... }
1532 Diag(Tok, diag::err_for_range_expected_decl)
1533 << FirstPart.get()->getSourceRange();
1534 SkipUntil(tok::r_paren, false, true);
1535 SecondPartIsInvalid = true;
Chris Lattner682bf922009-03-29 16:50:03 +00001536 } else {
Douglas Gregorb72c7782011-02-17 03:38:46 +00001537 if (!Value.isInvalid()) {
1538 Diag(Tok, diag::err_expected_semi_for);
1539 } else {
1540 // Skip until semicolon or rparen, don't consume it.
1541 SkipUntil(tok::r_paren, true, true);
1542 if (Tok.is(tok::semi))
1543 ConsumeToken();
1544 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 }
1546 }
Richard Smithad762fc2011-04-14 22:09:26 +00001547 if (!ForEach && !ForRange) {
John McCall9ae2f072010-08-23 23:25:46 +00001548 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001549 // Parse the second part of the for specifier.
1550 if (Tok.is(tok::semi)) { // for (...;;
1551 // no second part.
Douglas Gregorb72c7782011-02-17 03:38:46 +00001552 } else if (Tok.is(tok::r_paren)) {
1553 // missing both semicolons.
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001554 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00001555 ExprResult Second;
David Blaikie4e4d0842012-03-11 07:00:24 +00001556 if (getLangOpts().CPlusPlus)
Douglas Gregor586596f2010-05-06 17:25:47 +00001557 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1558 else {
1559 Second = ParseExpression();
1560 if (!Second.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001561 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001562 Second.get());
Douglas Gregor586596f2010-05-06 17:25:47 +00001563 }
Douglas Gregoreecf38f2010-05-06 21:39:56 +00001564 SecondPartIsInvalid = Second.isInvalid();
David Blaikiedef07622012-05-16 04:20:04 +00001565 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001566 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001567
Douglas Gregorb72c7782011-02-17 03:38:46 +00001568 if (Tok.isNot(tok::semi)) {
1569 if (!SecondPartIsInvalid || SecondVar)
1570 Diag(Tok, diag::err_expected_semi_for);
1571 else
1572 // Skip until semicolon or rparen, don't consume it.
1573 SkipUntil(tok::r_paren, true, true);
1574 }
1575
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001576 if (Tok.is(tok::semi)) {
1577 ConsumeToken();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001578 }
Sebastian Redl9a920342008-12-11 19:48:14 +00001579
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001580 // Parse the third part of the for specifier.
Douglas Gregor586596f2010-05-06 17:25:47 +00001581 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCall60d7b3a2010-08-24 06:29:42 +00001582 ExprResult Third = ParseExpression();
Richard Smith41956372013-01-14 22:39:08 +00001583 // FIXME: The C++11 standard doesn't actually say that this is a
1584 // discarded-value expression, but it clearly should be.
1585 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregor586596f2010-05-06 17:25:47 +00001586 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001589 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001590
Richard Smithad762fc2011-04-14 22:09:26 +00001591 // We need to perform most of the semantic analysis for a C++0x for-range
1592 // statememt before parsing the body, in order to be able to deduce the type
1593 // of an auto-typed loop variable.
1594 StmtResult ForRangeStmt;
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001595 StmtResult ForEachStmt;
Chad Rosierb6604462012-07-10 21:35:27 +00001596
John McCall990567c2011-07-27 01:07:15 +00001597 if (ForRange) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001598 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smithad762fc2011-04-14 22:09:26 +00001599 ForRangeInit.ColonLoc,
1600 ForRangeInit.RangeExpr.get(),
Richard Smith8b533d92012-09-20 21:52:32 +00001601 T.getCloseLocation(),
1602 Sema::BFRK_Build);
Richard Smithad762fc2011-04-14 22:09:26 +00001603
John McCall990567c2011-07-27 01:07:15 +00001604
1605 // Similarly, we need to do the semantic analysis for a for-range
1606 // statement immediately in order to close over temporaries correctly.
1607 } else if (ForEach) {
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001608 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001609 FirstPart.take(),
Chad Rosierb6604462012-07-10 21:35:27 +00001610 Collection.take(),
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001611 T.getCloseLocation());
John McCall990567c2011-07-27 01:07:15 +00001612 }
1613
Chris Lattner0ecea032007-08-22 05:28:50 +00001614 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner38484402007-08-22 05:33:11 +00001615 // there is no compound stmt. C90 does not have this clause. We only do this
1616 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis488d37e2008-09-11 03:06:46 +00001617 //
1618 // C++ 6.5p2:
1619 // The substatement in an iteration-statement implicitly defines a local scope
1620 // which is entered and exited each time through the loop.
1621 //
1622 // See comments in ParseIfStatement for why we create a scope for
1623 // for-init-statement/condition and a new scope for substatement in C++.
1624 //
Mike Stump1eb44332009-09-09 15:08:12 +00001625 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner4d00f2a2009-04-22 00:54:41 +00001626 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001627
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 // Read the body statement.
Nico Weber5cb94a72011-12-22 23:26:17 +00001629 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001630
Chris Lattner0ecea032007-08-22 05:28:50 +00001631 // Pop the body scope if needed.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001632 InnerScope.Exit();
Chris Lattner0ecea032007-08-22 05:28:50 +00001633
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 // Leave the for-scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +00001635 ForScope.Exit();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001636
1637 if (Body.isInvalid())
Sebastian Redl9a920342008-12-11 19:48:14 +00001638 return StmtError();
Sebastian Redleffa8d12008-12-10 00:02:53 +00001639
Richard Smithad762fc2011-04-14 22:09:26 +00001640 if (ForEach)
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001641 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1642 Body.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Richard Smithad762fc2011-04-14 22:09:26 +00001644 if (ForRange)
1645 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1646
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001647 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1648 SecondPart, SecondVar, ThirdPart,
1649 T.getCloseLocation(), Body.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001650}
1651
1652/// ParseGotoStatement
1653/// jump-statement:
1654/// 'goto' identifier ';'
1655/// [GNU] 'goto' '*' expression ';'
1656///
1657/// Note: this lets the caller parse the end ';'.
1658///
Richard Smith534986f2012-04-14 00:33:13 +00001659StmtResult Parser::ParseGotoStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001660 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001662
John McCall60d7b3a2010-08-24 06:29:42 +00001663 StmtResult Res;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001664 if (Tok.is(tok::identifier)) {
Chris Lattner337e5502011-02-18 01:27:55 +00001665 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1666 Tok.getLocation());
1667 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 ConsumeToken();
Eli Friedmanf01fdff2009-04-28 00:51:18 +00001669 } else if (Tok.is(tok::star)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 // GNU indirect goto extension.
1671 Diag(Tok, diag::ext_gnu_indirect_goto);
1672 SourceLocation StarLoc = ConsumeToken();
John McCall60d7b3a2010-08-24 06:29:42 +00001673 ExprResult R(ParseExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001674 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001676 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 }
John McCall9ae2f072010-08-23 23:25:46 +00001678 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattner95cfb852007-07-22 04:13:33 +00001679 } else {
1680 Diag(Tok, diag::err_expected_ident);
Sebastian Redl9a920342008-12-11 19:48:14 +00001681 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001683
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001684 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +00001685}
1686
1687/// ParseContinueStatement
1688/// jump-statement:
1689/// 'continue' ';'
1690///
1691/// Note: this lets the caller parse the end ';'.
1692///
Richard Smith534986f2012-04-14 00:33:13 +00001693StmtResult Parser::ParseContinueStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001695 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001696}
1697
1698/// ParseBreakStatement
1699/// jump-statement:
1700/// 'break' ';'
1701///
1702/// Note: this lets the caller parse the end ';'.
1703///
Richard Smith534986f2012-04-14 00:33:13 +00001704StmtResult Parser::ParseBreakStatement() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001706 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Reid Spencer5f016e22007-07-11 17:01:13 +00001707}
1708
1709/// ParseReturnStatement
1710/// jump-statement:
1711/// 'return' expression[opt] ';'
Richard Smith534986f2012-04-14 00:33:13 +00001712StmtResult Parser::ParseReturnStatement() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001713 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redl9a920342008-12-11 19:48:14 +00001715
John McCall60d7b3a2010-08-24 06:29:42 +00001716 ExprResult R;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001717 if (Tok.isNot(tok::semi)) {
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001718 if (Tok.is(tok::code_completion)) {
Douglas Gregor23c94db2010-07-02 17:43:08 +00001719 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001720 cutOffParsing();
Douglas Gregor5ac3bdb2010-05-30 01:49:25 +00001721 return StmtError();
1722 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001723
David Blaikie4e4d0842012-03-11 07:00:24 +00001724 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001725 R = ParseInitializer();
Richard Smith7fe62082011-10-15 05:09:34 +00001726 if (R.isUsable())
Richard Smith80ad52f2013-01-02 11:42:31 +00001727 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith7fe62082011-10-15 05:09:34 +00001728 diag::warn_cxx98_compat_generalized_initializer_lists :
1729 diag::ext_generalized_initializer_lists)
Douglas Gregor6f4596c2011-03-11 23:10:44 +00001730 << R.get()->getSourceRange();
1731 } else
1732 R = ParseExpression();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001733 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 SkipUntil(tok::semi, false, true);
Sebastian Redl9a920342008-12-11 19:48:14 +00001735 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 }
1737 }
John McCall9ae2f072010-08-23 23:25:46 +00001738 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001739}
1740
John McCallaeeacf72013-05-03 00:10:13 +00001741namespace {
1742 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1743 Parser &TheParser;
1744 SourceLocation AsmLoc;
1745 StringRef AsmString;
1746
1747 /// The tokens we streamed into AsmString and handed off to MC.
1748 ArrayRef<Token> AsmToks;
1749
1750 /// The offset of each token in AsmToks within AsmString.
1751 ArrayRef<unsigned> AsmTokOffsets;
1752
1753 public:
1754 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1755 StringRef AsmString,
1756 ArrayRef<Token> Toks,
1757 ArrayRef<unsigned> Offsets)
1758 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1759 AsmToks(Toks), AsmTokOffsets(Offsets) {
1760 assert(AsmToks.size() == AsmTokOffsets.size());
1761 }
1762
1763 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1764 InlineAsmIdentifierInfo &Info,
1765 bool IsUnevaluatedContext) {
1766 // Collect the desired tokens.
1767 SmallVector<Token, 16> LineToks;
1768 const Token *FirstOrigToken = 0;
1769 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1770
1771 unsigned NumConsumedToks;
1772 ExprResult Result =
1773 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1774 IsUnevaluatedContext);
1775
1776 // If we consumed the entire line, tell MC that.
1777 // Also do this if we consumed nothing as a way of reporting failure.
1778 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1779 // By not modifying LineBuf, we're implicitly consuming it all.
1780
1781 // Otherwise, consume up to the original tokens.
1782 } else {
1783 assert(FirstOrigToken && "not using original tokens?");
1784
1785 // Since we're using original tokens, apply that offset.
1786 assert(FirstOrigToken[NumConsumedToks].getLocation()
1787 == LineToks[NumConsumedToks].getLocation());
1788 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1789 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1790
1791 // The total length we've consumed is the relative offset
1792 // of the last token we consumed plus its length.
1793 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1794 + AsmToks[LastIndex].getLength()
1795 - AsmTokOffsets[FirstIndex]);
1796 LineBuf = LineBuf.substr(0, TotalOffset);
1797 }
1798
1799 // Initialize the "decl" with the lookup result.
1800 Info.OpDecl = static_cast<void*>(Result.take());
1801 return Info.OpDecl;
1802 }
1803
1804 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1805 unsigned &Offset) {
1806 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1807 Offset, AsmLoc);
1808 }
1809
1810 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1811 void *Context) {
1812 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1813 }
1814
1815 private:
1816 /// Collect the appropriate tokens for the given string.
1817 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1818 const Token *&FirstOrigToken) const {
1819 // For now, assert that the string we're working with is a substring
1820 // of what we gave to MC. This lets us use the original tokens.
1821 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1822 !std::less<const char*>()(AsmString.end(), Str.end()));
1823
1824 // Try to find a token whose offset matches the first token.
1825 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1826 const unsigned *FirstTokOffset
1827 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1828 FirstCharOffset);
1829
1830 // For now, assert that the start of the string exactly
1831 // corresponds to the start of a token.
1832 assert(*FirstTokOffset == FirstCharOffset);
1833
1834 // Use all the original tokens for this line. (We assume the
1835 // end of the line corresponds cleanly to a token break.)
1836 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1837 FirstOrigToken = &AsmToks[FirstTokIndex];
1838 unsigned LastCharOffset = Str.end() - AsmString.begin();
1839 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1840 if (AsmTokOffsets[i] >= LastCharOffset) break;
1841 TempToks.push_back(AsmToks[i]);
1842 }
1843 }
1844
1845 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1846 // Compute an offset into the inline asm buffer.
1847 // FIXME: This isn't right if .macro is involved (but hopefully, no
1848 // real-world code does that).
1849 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1850 const llvm::MemoryBuffer *LBuf =
1851 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1852 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1853
1854 // Figure out which token that offset points into.
1855 const unsigned *TokOffsetPtr =
1856 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1857 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1858 unsigned TokOffset = *TokOffsetPtr;
1859
1860 // If we come up with an answer which seems sane, use it; otherwise,
1861 // just point at the __asm keyword.
1862 // FIXME: Assert the answer is sane once we handle .macro correctly.
1863 SourceLocation Loc = AsmLoc;
1864 if (TokIndex < AsmToks.size()) {
1865 const Token &Tok = AsmToks[TokIndex];
1866 Loc = Tok.getLocation();
1867 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1868 }
1869 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1870 << D.getMessage();
1871 }
1872 };
1873}
1874
1875/// Parse an identifier in an MS-style inline assembly block.
1876///
1877/// \param CastInfo - a void* so that we don't have to teach Parser.h
1878/// about the actual type.
1879ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1880 unsigned &NumLineToksConsumed,
1881 void *CastInfo,
1882 bool IsUnevaluatedContext) {
1883 llvm::InlineAsmIdentifierInfo &Info =
1884 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1885
1886 // Push a fake token on the end so that we don't overrun the token
1887 // stream. We use ';' because it expression-parsing should never
1888 // overrun it.
1889 const tok::TokenKind EndOfStream = tok::semi;
1890 Token EndOfStreamTok;
1891 EndOfStreamTok.startToken();
1892 EndOfStreamTok.setKind(EndOfStream);
1893 LineToks.push_back(EndOfStreamTok);
1894
1895 // Also copy the current token over.
1896 LineToks.push_back(Tok);
1897
1898 PP.EnterTokenStream(LineToks.begin(),
1899 LineToks.size(),
1900 /*disable macros*/ true,
1901 /*owns tokens*/ false);
1902
1903 // Clear the current token and advance to the first token in LineToks.
1904 ConsumeAnyToken();
1905
1906 // Parse an optional scope-specifier if we're in C++.
1907 CXXScopeSpec SS;
1908 if (getLangOpts().CPlusPlus) {
1909 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1910 }
1911
1912 // Require an identifier here.
1913 SourceLocation TemplateKWLoc;
1914 UnqualifiedId Id;
1915 bool Invalid = ParseUnqualifiedId(SS,
1916 /*EnteringContext=*/false,
1917 /*AllowDestructorName=*/false,
1918 /*AllowConstructorName=*/false,
1919 /*ObjectType=*/ ParsedType(),
1920 TemplateKWLoc,
1921 Id);
1922
1923 // If we've run into the poison token we inserted before, or there
1924 // was a parsing error, then claim the entire line.
1925 if (Invalid || Tok.is(EndOfStream)) {
1926 NumLineToksConsumed = LineToks.size() - 2;
1927
1928 // Otherwise, claim up to the start of the next token.
1929 } else {
1930 // Figure out how many tokens we are into LineToks.
1931 unsigned LineIndex = 0;
1932 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1933 LineIndex++;
1934 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1935 }
1936
1937 NumLineToksConsumed = LineIndex;
1938 }
1939
1940 // Finally, restore the old parsing state by consuming all the
1941 // tokens we staged before, implicitly killing off the
1942 // token-lexer we pushed.
1943 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1944 ConsumeAnyToken();
1945 }
1946 ConsumeToken(EndOfStream);
1947
1948 // Leave LineToks in its original state.
1949 LineToks.pop_back();
1950 LineToks.pop_back();
1951
1952 // Perform the lookup.
1953 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1954 IsUnevaluatedContext);
1955}
1956
1957/// Turn a sequence of our tokens back into a string that we can hand
1958/// to the MC asm parser.
1959static bool buildMSAsmString(Preprocessor &PP,
1960 SourceLocation AsmLoc,
1961 ArrayRef<Token> AsmToks,
1962 SmallVectorImpl<unsigned> &TokOffsets,
1963 SmallString<512> &Asm) {
1964 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1965
1966 // Is this the start of a new assembly statement?
1967 bool isNewStatement = true;
1968
1969 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1970 const Token &Tok = AsmToks[i];
1971
1972 // Start each new statement with a newline and a tab.
1973 if (!isNewStatement &&
1974 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1975 Asm += "\n\t";
1976 isNewStatement = true;
1977 }
1978
1979 // Preserve the existence of leading whitespace except at the
1980 // start of a statement.
1981 if (!isNewStatement && Tok.hasLeadingSpace())
1982 Asm += ' ';
1983
1984 // Remember the offset of this token.
1985 TokOffsets.push_back(Asm.size());
1986
1987 // Don't actually write '__asm' into the assembly stream.
1988 if (Tok.is(tok::kw_asm)) {
1989 // Complain about __asm at the end of the stream.
1990 if (i + 1 == e) {
1991 PP.Diag(AsmLoc, diag::err_asm_empty);
1992 return true;
1993 }
1994
1995 continue;
1996 }
1997
1998 // Append the spelling of the token.
1999 SmallString<32> SpellingBuffer;
2000 bool SpellingInvalid = false;
2001 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
2002 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
2003
2004 // We are no longer at the start of a statement.
2005 isNewStatement = false;
2006 }
2007
2008 // Ensure that the buffer is null-terminated.
2009 Asm.push_back('\0');
2010 Asm.pop_back();
2011
2012 assert(TokOffsets.size() == AsmToks.size());
2013 return false;
2014}
2015
Eli Friedman3fedbe12011-09-30 01:13:51 +00002016/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
2017/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier8cd64b42012-06-11 20:47:18 +00002018///
2019/// [MS] ms-asm-statement:
2020/// ms-asm-block
2021/// ms-asm-block ms-asm-statement
2022///
2023/// [MS] ms-asm-block:
2024/// '__asm' ms-asm-line '\n'
2025/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
2026///
2027/// [MS] ms-asm-instruction-block
2028/// ms-asm-line
2029/// ms-asm-line '\n' ms-asm-instruction-block
2030///
Eli Friedman3fedbe12011-09-30 01:13:51 +00002031StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
2032 SourceManager &SrcMgr = PP.getSourceManager();
2033 SourceLocation EndLoc = AsmLoc;
Chad Rosier8cd64b42012-06-11 20:47:18 +00002034 SmallVector<Token, 4> AsmToks;
Chad Rosier21ef7112012-08-14 19:22:06 +00002035
2036 bool InBraces = false;
2037 unsigned short savedBraceCount = 0;
2038 bool InAsmComment = false;
2039 FileID FID;
2040 unsigned LineNo = 0;
2041 unsigned NumTokensRead = 0;
2042 SourceLocation LBraceLoc;
2043
2044 if (Tok.is(tok::l_brace)) {
2045 // Braced inline asm: consume the opening brace.
2046 InBraces = true;
2047 savedBraceCount = BraceCount;
2048 EndLoc = LBraceLoc = ConsumeBrace();
2049 ++NumTokensRead;
2050 } else {
2051 // Single-line inline asm; compute which line it is on.
2052 std::pair<FileID, unsigned> ExpAsmLoc =
2053 SrcMgr.getDecomposedExpansionLoc(EndLoc);
2054 FID = ExpAsmLoc.first;
2055 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2056 }
2057
2058 SourceLocation TokLoc = Tok.getLocation();
Eli Friedman3fedbe12011-09-30 01:13:51 +00002059 do {
Chad Rosier21ef7112012-08-14 19:22:06 +00002060 // If we hit EOF, we're done, period.
2061 if (Tok.is(tok::eof))
Eli Friedman3fedbe12011-09-30 01:13:51 +00002062 break;
Chad Rosier21ef7112012-08-14 19:22:06 +00002063
Chad Rosier21ef7112012-08-14 19:22:06 +00002064 if (!InAsmComment && Tok.is(tok::semi)) {
2065 // A semicolon in an asm is the start of a comment.
2066 InAsmComment = true;
2067 if (InBraces) {
2068 // Compute which line the comment is on.
2069 std::pair<FileID, unsigned> ExpSemiLoc =
2070 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2071 FID = ExpSemiLoc.first;
2072 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2073 }
2074 } else if (!InBraces || InAsmComment) {
2075 // If end-of-line is significant, check whether this token is on a
2076 // new line.
2077 std::pair<FileID, unsigned> ExpLoc =
2078 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2079 if (ExpLoc.first != FID ||
2080 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2081 // If this is a single-line __asm, we're done.
2082 if (!InBraces)
2083 break;
2084 // We're no longer in a comment.
2085 InAsmComment = false;
2086 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2087 // Single-line asm always ends when a closing brace is seen.
2088 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2089 // does MSVC do here?
2090 break;
2091 }
2092 }
2093 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2094 BraceCount == (savedBraceCount + 1)) {
2095 // Consume the closing brace, and finish
2096 EndLoc = ConsumeBrace();
2097 break;
2098 }
2099
2100 // Consume the next token; make sure we don't modify the brace count etc.
2101 // if we are in a comment.
2102 EndLoc = TokLoc;
2103 if (InAsmComment)
2104 PP.Lex(Tok);
2105 else {
2106 AsmToks.push_back(Tok);
2107 ConsumeAnyToken();
2108 }
2109 TokLoc = Tok.getLocation();
2110 ++NumTokensRead;
Eli Friedman3fedbe12011-09-30 01:13:51 +00002111 } while (1);
Chad Rosier8cd64b42012-06-11 20:47:18 +00002112
Chad Rosier21ef7112012-08-14 19:22:06 +00002113 if (InBraces && BraceCount != savedBraceCount) {
2114 // __asm without closing brace (this can happen at EOF).
2115 Diag(Tok, diag::err_expected_rbrace);
2116 Diag(LBraceLoc, diag::note_matching) << "{";
2117 return StmtError();
2118 } else if (NumTokensRead == 0) {
2119 // Empty __asm.
2120 Diag(Tok, diag::err_expected_lbrace);
2121 return StmtError();
2122 }
2123
John McCallaeeacf72013-05-03 00:10:13 +00002124 // Okay, prepare to use MC to parse the assembly.
2125 SmallVector<StringRef, 4> ConstraintRefs;
2126 SmallVector<Expr*, 4> Exprs;
2127 SmallVector<StringRef, 4> ClobberRefs;
2128
2129 // We need an actual supported target.
2130 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2131 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
Alp Tokerc94b5ae2013-10-30 15:07:10 +00002132 const std::string &TT = TheTriple.getTriple();
2133 const llvm::Target *TheTarget = 0;
John McCallaeeacf72013-05-03 00:10:13 +00002134 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2135 ArchTy != llvm::Triple::x86_64);
Alp Tokerc94b5ae2013-10-30 15:07:10 +00002136 if (UnsupportedArch) {
John McCallaeeacf72013-05-03 00:10:13 +00002137 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
Alp Tokerc94b5ae2013-10-30 15:07:10 +00002138 } else {
2139 std::string Error;
2140 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2141 if (!TheTarget)
2142 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
2143 }
Alp Toker25973152013-10-30 14:29:28 +00002144
John McCallaeeacf72013-05-03 00:10:13 +00002145 // If we don't support assembly, or the assembly is empty, we don't
2146 // need to instantiate the AsmParser, etc.
Alp Tokerc94b5ae2013-10-30 15:07:10 +00002147 if (!TheTarget || AsmToks.empty()) {
John McCallaeeacf72013-05-03 00:10:13 +00002148 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2149 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2150 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2151 }
2152
2153 // Expand the tokens into a string buffer.
2154 SmallString<512> AsmString;
2155 SmallVector<unsigned, 8> TokOffsets;
2156 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2157 return StmtError();
2158
John McCallaeeacf72013-05-03 00:10:13 +00002159 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
Rafael Espindola1fcf31e2013-05-13 01:24:18 +00002160 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly12981a72013-09-12 10:59:24 +00002161 // Get the instruction descriptor.
2162 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
John McCallaeeacf72013-05-03 00:10:13 +00002163 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2164 OwningPtr<llvm::MCSubtargetInfo>
2165 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2166
2167 llvm::SourceMgr TempSrcMgr;
Bill Wendling4b7bae32013-06-18 07:22:05 +00002168 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallaeeacf72013-05-03 00:10:13 +00002169 llvm::MemoryBuffer *Buffer =
2170 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2171
2172 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2173 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2174
2175 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2176 OwningPtr<llvm::MCAsmParser>
2177 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2178 OwningPtr<llvm::MCTargetAsmParser>
Joey Gouly12981a72013-09-12 10:59:24 +00002179 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser, *MII));
John McCallaeeacf72013-05-03 00:10:13 +00002180
John McCallaeeacf72013-05-03 00:10:13 +00002181 llvm::MCInstPrinter *IP =
2182 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2183
2184 // Change to the Intel dialect.
2185 Parser->setAssemblerDialect(1);
2186 Parser->setTargetParser(*TargetParser.get());
2187 Parser->setParsingInlineAsm(true);
2188 TargetParser->setParsingInlineAsm(true);
2189
2190 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2191 AsmToks, TokOffsets);
2192 TargetParser->setSemaCallback(&Callback);
2193 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2194 &Callback);
2195
2196 unsigned NumOutputs;
2197 unsigned NumInputs;
2198 std::string AsmStringIR;
2199 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2200 SmallVector<std::string, 4> Constraints;
2201 SmallVector<std::string, 4> Clobbers;
2202 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2203 NumOutputs, NumInputs, OpExprs, Constraints,
2204 Clobbers, MII, IP, Callback))
2205 return StmtError();
2206
2207 // Build the vector of clobber StringRefs.
2208 unsigned NumClobbers = Clobbers.size();
2209 ClobberRefs.resize(NumClobbers);
2210 for (unsigned i = 0; i != NumClobbers; ++i)
2211 ClobberRefs[i] = StringRef(Clobbers[i]);
2212
2213 // Recast the void pointers and build the vector of constraint StringRefs.
2214 unsigned NumExprs = NumOutputs + NumInputs;
2215 ConstraintRefs.resize(NumExprs);
2216 Exprs.resize(NumExprs);
2217 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2218 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2219 if (!OpExpr)
2220 return StmtError();
2221
2222 // Need address of variable.
2223 if (OpExprs[i].second)
2224 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2225 .take();
2226
2227 ConstraintRefs[i] = StringRef(Constraints[i]);
2228 Exprs[i] = OpExpr;
2229 }
2230
Chad Rosier8f726de2012-08-06 20:03:45 +00002231 // FIXME: We should be passing source locations for better diagnostics.
John McCallaeeacf72013-05-03 00:10:13 +00002232 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2233 NumOutputs, NumInputs,
2234 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00002235}
2236
Reid Spencer5f016e22007-07-11 17:01:13 +00002237/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff5f8aa692008-02-11 23:15:56 +00002238/// asm-statement:
2239/// gnu-asm-statement
2240/// ms-asm-statement
2241///
2242/// [GNU] gnu-asm-statement:
Reid Spencer5f016e22007-07-11 17:01:13 +00002243/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2244///
2245/// [GNU] asm-argument:
2246/// asm-string-literal
2247/// asm-string-literal ':' asm-operands[opt]
2248/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2249/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2250/// ':' asm-clobbers
2251///
2252/// [GNU] asm-clobbers:
2253/// asm-string-literal
2254/// asm-clobbers ',' asm-string-literal
2255///
John McCall60d7b3a2010-08-24 06:29:42 +00002256StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002257 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattnerfe795952007-10-29 04:04:16 +00002258 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redl9a920342008-12-11 19:48:14 +00002259
Chad Rosier15490fd2012-12-05 21:08:21 +00002260 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosierb6604462012-07-10 21:35:27 +00002261 !isTypeQualifier()) {
Steve Naroffd62701b2008-02-07 03:50:06 +00002262 msAsm = true;
Eli Friedman3fedbe12011-09-30 01:13:51 +00002263 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffd62701b2008-02-07 03:50:06 +00002264 }
John McCall0b7e6782011-03-24 11:26:52 +00002265 DeclSpec DS(AttrFactory);
Reid Spencer5f016e22007-07-11 17:01:13 +00002266 SourceLocation Loc = Tok.getLocation();
Sean Huntbbd37c62009-11-21 08:43:09 +00002267 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redl9a920342008-12-11 19:48:14 +00002268
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 // GNU asms accept, but warn, about type-qualifiers other than volatile.
2270 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner1ab3b962008-11-18 07:48:38 +00002271 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner1ab3b962008-11-18 07:48:38 +00002273 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith4cf4a5e2013-03-28 01:55:44 +00002274 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2275 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2276 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redl9a920342008-12-11 19:48:14 +00002277
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 // Remember if this was a volatile asm.
Anders Carlsson39c47b52007-11-23 23:12:25 +00002279 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002280 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00002281 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Reid Spencer5f016e22007-07-11 17:01:13 +00002282 SkipUntil(tok::r_paren);
Sebastian Redl9a920342008-12-11 19:48:14 +00002283 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002285 BalancedDelimiterTracker T(*this, tok::l_paren);
2286 T.consumeOpen();
Sebastian Redl9a920342008-12-11 19:48:14 +00002287
John McCall60d7b3a2010-08-24 06:29:42 +00002288 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenek320fa4b2011-12-02 01:30:14 +00002289 if (AsmString.isInvalid()) {
Richard Smith99831e42012-03-06 03:21:47 +00002290 // Consume up to and including the closing paren.
2291 T.skipToEnd();
Sebastian Redl9a920342008-12-11 19:48:14 +00002292 return StmtError();
Ted Kremenek320fa4b2011-12-02 01:30:14 +00002293 }
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002294
Chris Lattner5f9e2722011-07-23 10:55:15 +00002295 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002296 ExprVector Constraints;
2297 ExprVector Exprs;
2298 ExprVector Clobbers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002299
Anders Carlssondfab34a2008-02-05 23:03:50 +00002300 if (Tok.is(tok::r_paren)) {
Chris Lattner64cb4752009-12-20 23:00:41 +00002301 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002302 T.consumeClose();
Chad Rosierdf5faf52012-08-25 00:11:56 +00002303 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2304 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2305 Constraints, Exprs, AsmString.take(),
2306 Clobbers, T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002308
Chris Lattner64cb4752009-12-20 23:00:41 +00002309 // Parse Outputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002310 bool AteExtraColon = false;
2311 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2312 // In C++ mode, parse "::" like ": :".
2313 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattner64cb4752009-12-20 23:00:41 +00002314 ConsumeToken();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002315
Chris Lattner64056462009-12-20 23:08:04 +00002316 if (!AteExtraColon &&
2317 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00002318 return StmtError();
2319 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002320
Chris Lattner64cb4752009-12-20 23:00:41 +00002321 unsigned NumOutputs = Names.size();
2322
2323 // Parse Inputs, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002324 if (AteExtraColon ||
2325 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2326 // In C++ mode, parse "::" like ": :".
2327 if (AteExtraColon)
2328 AteExtraColon = false;
2329 else {
2330 AteExtraColon = Tok.is(tok::coloncolon);
2331 ConsumeToken();
2332 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002333
Chris Lattner64056462009-12-20 23:08:04 +00002334 if (!AteExtraColon &&
2335 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattner64cb4752009-12-20 23:00:41 +00002336 return StmtError();
2337 }
2338
2339 assert(Names.size() == Constraints.size() &&
2340 Constraints.size() == Exprs.size() &&
2341 "Input operand size mismatch!");
2342
2343 unsigned NumInputs = Names.size() - NumOutputs;
2344
2345 // Parse the clobbers, if present.
Chris Lattner64056462009-12-20 23:08:04 +00002346 if (AteExtraColon || Tok.is(tok::colon)) {
2347 if (!AteExtraColon)
2348 ConsumeToken();
Chris Lattner64cb4752009-12-20 23:00:41 +00002349
Chandler Carruth102e1b62010-07-22 07:11:21 +00002350 // Parse the asm-string list for clobbers if present.
2351 if (Tok.isNot(tok::r_paren)) {
2352 while (1) {
John McCall60d7b3a2010-08-24 06:29:42 +00002353 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattner64cb4752009-12-20 23:00:41 +00002354
Chandler Carruth102e1b62010-07-22 07:11:21 +00002355 if (Clobber.isInvalid())
2356 break;
Chris Lattner64cb4752009-12-20 23:00:41 +00002357
Chandler Carruth102e1b62010-07-22 07:11:21 +00002358 Clobbers.push_back(Clobber.release());
Chris Lattner64cb4752009-12-20 23:00:41 +00002359
Chandler Carruth102e1b62010-07-22 07:11:21 +00002360 if (Tok.isNot(tok::comma)) break;
2361 ConsumeToken();
2362 }
Chris Lattner64cb4752009-12-20 23:00:41 +00002363 }
2364 }
2365
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002366 T.consumeClose();
Chad Rosierdf5faf52012-08-25 00:11:56 +00002367 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2368 NumInputs, Names.data(), Constraints, Exprs,
2369 AsmString.take(), Clobbers,
2370 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002371}
2372
2373/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattner64cb4752009-12-20 23:00:41 +00002374/// asm-statement, assuming the leading ':' token was eaten.
Reid Spencer5f016e22007-07-11 17:01:13 +00002375///
2376/// [GNU] asm-operands:
2377/// asm-operand
2378/// asm-operands ',' asm-operand
2379///
2380/// [GNU] asm-operand:
2381/// asm-string-literal '(' expression ')'
2382/// '[' identifier ']' asm-string-literal '(' expression ')'
2383///
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00002384//
2385// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002386bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002387 SmallVectorImpl<Expr *> &Constraints,
2388 SmallVectorImpl<Expr *> &Exprs) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002389 // 'asm-operands' isn't present?
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002390 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002392
2393 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002394 // Read the [id] if present.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002395 if (Tok.is(tok::l_square)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002396 BalancedDelimiterTracker T(*this, tok::l_square);
2397 T.consumeOpen();
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002399 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002400 Diag(Tok, diag::err_expected_ident);
2401 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002402 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002403 }
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Anders Carlssonb235fc22007-11-22 01:36:19 +00002405 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner69efba72007-10-29 04:06:22 +00002406 ConsumeToken();
Anders Carlssonb235fc22007-11-22 01:36:19 +00002407
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002408 Names.push_back(II);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002409 T.consumeClose();
Anders Carlssonb235fc22007-11-22 01:36:19 +00002410 } else
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002411 Names.push_back(0);
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002412
John McCall60d7b3a2010-08-24 06:29:42 +00002413 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002414 if (Constraint.isInvalid()) {
Anders Carlssonb235fc22007-11-22 01:36:19 +00002415 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002416 return true;
Anders Carlssonb235fc22007-11-22 01:36:19 +00002417 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002418 Constraints.push_back(Constraint.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00002419
Chris Lattner4e1d99a2007-10-09 17:41:39 +00002420 if (Tok.isNot(tok::l_paren)) {
Chris Lattner1ab3b962008-11-18 07:48:38 +00002421 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002423 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002424 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002425
Reid Spencer5f016e22007-07-11 17:01:13 +00002426 // Read the parenthesized expression.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002427 BalancedDelimiterTracker T(*this, tok::l_paren);
2428 T.consumeOpen();
John McCall60d7b3a2010-08-24 06:29:42 +00002429 ExprResult Res(ParseExpression());
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002430 T.consumeClose();
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002431 if (Res.isInvalid()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002432 SkipUntil(tok::r_paren);
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002433 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002434 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00002435 Exprs.push_back(Res.release());
Reid Spencer5f016e22007-07-11 17:01:13 +00002436 // Eat the comma and continue parsing if it exists.
Anders Carlsson8bd36fc2008-02-09 19:57:29 +00002437 if (Tok.isNot(tok::comma)) return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002438 ConsumeToken();
2439 }
2440}
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002441
Douglas Gregorc9977d02011-03-16 17:05:57 +00002442Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner40e9bc82009-03-05 00:49:17 +00002443 assert(Tok.is(tok::l_brace));
2444 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002445
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00002446 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1a5bd5d2012-11-19 21:13:18 +00002447 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002448 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00002449 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002450 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002451
John McCallf312b1e2010-08-26 23:41:50 +00002452 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2453 "parsing function body");
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002455 // Do not enter a scope for the brace, as the arguments are in the same scope
2456 // (the function body) as the body itself. Instead, just read the statement
2457 // list and put it into a CompoundStmt for safe keeping.
John McCall60d7b3a2010-08-24 06:29:42 +00002458 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl61364dd2008-12-11 19:30:53 +00002459
Fariborz Jahanianf9ed3152007-11-08 19:01:26 +00002460 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002461 if (FnBody.isInvalid()) {
2462 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00002463 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002464 }
Sebastian Redl61364dd2008-12-11 19:30:53 +00002465
Douglas Gregorc9977d02011-03-16 17:05:57 +00002466 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002467 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeoncd5af4b2007-12-01 08:06:07 +00002468}
Sebastian Redla0fd8652008-12-21 16:41:36 +00002469
Sebastian Redld3a413d2009-04-26 20:35:05 +00002470/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2471///
2472/// function-try-block:
2473/// 'try' ctor-initializer[opt] compound-statement handler-seq
2474///
Douglas Gregorc9977d02011-03-16 17:05:57 +00002475Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redld3a413d2009-04-26 20:35:05 +00002476 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2477 SourceLocation TryLoc = ConsumeToken();
2478
John McCallf312b1e2010-08-26 23:41:50 +00002479 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2480 "parsing function try block");
Sebastian Redld3a413d2009-04-26 20:35:05 +00002481
2482 // Constructor initializer list?
2483 if (Tok.is(tok::colon))
2484 ParseConstructorInitializer(Decl);
Douglas Gregor2eef4272011-09-07 20:36:12 +00002485 else
2486 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002487
Richard Smith1a5bd5d2012-11-19 21:13:18 +00002488 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2489 trySkippingFunctionBody()) {
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002490 BodyScope.Exit();
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00002491 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregorc9977d02011-03-16 17:05:57 +00002492 }
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002493
Sebastian Redlde1b60a2009-04-26 21:08:36 +00002494 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikiec4027c82012-11-10 01:04:23 +00002495 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redld3a413d2009-04-26 20:35:05 +00002496 // If we failed to parse the try-catch, we just give the function an empty
2497 // compound statement as the body.
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002498 if (FnBody.isInvalid()) {
2499 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00002500 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002501 }
Sebastian Redld3a413d2009-04-26 20:35:05 +00002502
Douglas Gregorc9977d02011-03-16 17:05:57 +00002503 BodyScope.Exit();
John McCall9ae2f072010-08-23 23:25:46 +00002504 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redld3a413d2009-04-26 20:35:05 +00002505}
2506
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002507bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002508 assert(Tok.is(tok::l_brace));
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002509 assert(SkipFunctionBodies &&
2510 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002511
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00002512 if (!PP.isCodeCompletionEnabled()) {
2513 ConsumeBrace();
2514 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false);
2515 return true;
2516 }
2517
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002518 // We're in code-completion mode. Skip parsing for all function bodies unless
2519 // the body contains the code-completion point.
2520 TentativeParsingAction PA(*this);
2521 ConsumeBrace();
2522 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Argyrios Kyrtzidis81939a72012-10-31 17:29:28 +00002523 /*StopAtCodeCompletion=*/true)) {
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00002524 PA.Commit();
2525 return true;
2526 }
2527
2528 PA.Revert();
2529 return false;
2530}
2531
Sebastian Redla0fd8652008-12-21 16:41:36 +00002532/// ParseCXXTryBlock - Parse a C++ try-block.
2533///
2534/// try-block:
2535/// 'try' compound-statement handler-seq
2536///
Richard Smith534986f2012-04-14 00:33:13 +00002537StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002538 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2539
2540 SourceLocation TryLoc = ConsumeToken();
Sebastian Redld3a413d2009-04-26 20:35:05 +00002541 return ParseCXXTryBlockCommon(TryLoc);
2542}
2543
2544/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2545/// function-try-block.
2546///
2547/// try-block:
2548/// 'try' compound-statement handler-seq
2549///
2550/// function-try-block:
2551/// 'try' ctor-initializer[opt] compound-statement handler-seq
2552///
2553/// handler-seq:
2554/// handler handler-seq[opt]
2555///
John Wiegley28bbe4b2011-04-28 01:08:34 +00002556/// [Borland] try-block:
2557/// 'try' compound-statement seh-except-block
2558/// 'try' compound-statment seh-finally-block
2559///
David Blaikiec4027c82012-11-10 01:04:23 +00002560StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002561 if (Tok.isNot(tok::l_brace))
2562 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Sean Huntbbd37c62009-11-21 08:43:09 +00002563 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002564
2565 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikiee5afdcf2012-11-13 18:51:45 +00002566 Scope::DeclScope | Scope::TryScope |
2567 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002568 if (TryBlock.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002569 return TryBlock;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002570
John Wiegley28bbe4b2011-04-28 01:08:34 +00002571 // Borland allows SEH-handlers with 'try'
Chad Rosierb6604462012-07-10 21:35:27 +00002572
Richard Smith534986f2012-04-14 00:33:13 +00002573 if ((Tok.is(tok::identifier) &&
2574 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2575 Tok.is(tok::kw___finally)) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002576 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2577 StmtResult Handler;
Douglas Gregorb57791e2011-10-21 03:57:52 +00002578 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley28bbe4b2011-04-28 01:08:34 +00002579 SourceLocation Loc = ConsumeToken();
2580 Handler = ParseSEHExceptBlock(Loc);
2581 }
2582 else {
2583 SourceLocation Loc = ConsumeToken();
2584 Handler = ParseSEHFinallyBlock(Loc);
2585 }
2586 if(Handler.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002587 return Handler;
John McCall7f040a92010-12-24 02:08:15 +00002588
John Wiegley28bbe4b2011-04-28 01:08:34 +00002589 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2590 TryLoc,
2591 TryBlock.take(),
2592 Handler.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002593 }
John Wiegley28bbe4b2011-04-28 01:08:34 +00002594 else {
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002595 StmtVector Handlers;
Richard Smith5eed7e02013-10-15 01:34:54 +00002596
2597 // C++11 attributes can't appear here, despite this context seeming
2598 // statement-like.
2599 DiagnoseAndSkipCXX11Attributes();
Sebastian Redla0fd8652008-12-21 16:41:36 +00002600
John Wiegley28bbe4b2011-04-28 01:08:34 +00002601 if (Tok.isNot(tok::kw_catch))
2602 return StmtError(Diag(Tok, diag::err_expected_catch));
2603 while (Tok.is(tok::kw_catch)) {
David Blaikiec4027c82012-11-10 01:04:23 +00002604 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley28bbe4b2011-04-28 01:08:34 +00002605 if (!Handler.isInvalid())
2606 Handlers.push_back(Handler.release());
2607 }
2608 // Don't bother creating the full statement if we don't have any usable
2609 // handlers.
2610 if (Handlers.empty())
2611 return StmtError();
2612
Robert Wilhelm21adb0c2013-08-22 09:20:03 +00002613 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley28bbe4b2011-04-28 01:08:34 +00002614 }
Sebastian Redla0fd8652008-12-21 16:41:36 +00002615}
2616
2617/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2618///
Richard Smith4cd81c52013-01-29 09:02:09 +00002619/// handler:
2620/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redla0fd8652008-12-21 16:41:36 +00002621///
Richard Smith4cd81c52013-01-29 09:02:09 +00002622/// exception-declaration:
2623/// attribute-specifier-seq[opt] type-specifier-seq declarator
2624/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2625/// '...'
Sebastian Redla0fd8652008-12-21 16:41:36 +00002626///
David Blaikiec4027c82012-11-10 01:04:23 +00002627StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redla0fd8652008-12-21 16:41:36 +00002628 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2629
2630 SourceLocation CatchLoc = ConsumeToken();
2631
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002632 BalancedDelimiterTracker T(*this, tok::l_paren);
2633 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redla0fd8652008-12-21 16:41:36 +00002634 return StmtError();
2635
2636 // C++ 3.3.2p3:
2637 // The name in a catch exception-declaration is local to the handler and
2638 // shall not be redeclared in the outermost block of the handler.
David Blaikiec4027c82012-11-10 01:04:23 +00002639 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikiee5afdcf2012-11-13 18:51:45 +00002640 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redla0fd8652008-12-21 16:41:36 +00002641
2642 // exception-declaration is equivalent to '...' or a parameter-declaration
2643 // without default arguments.
John McCalld226f652010-08-21 09:40:31 +00002644 Decl *ExceptionDecl = 0;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002645 if (Tok.isNot(tok::ellipsis)) {
Richard Smith4cd81c52013-01-29 09:02:09 +00002646 ParsedAttributesWithRange Attributes(AttrFactory);
2647 MaybeParseCXX11Attributes(Attributes);
2648
John McCall0b7e6782011-03-24 11:26:52 +00002649 DeclSpec DS(AttrFactory);
Richard Smith4cd81c52013-01-29 09:02:09 +00002650 DS.takeAttributesFrom(Attributes);
2651
Sebastian Redl4b07b292008-12-22 19:15:10 +00002652 if (ParseCXXTypeSpecifierSeq(DS))
2653 return StmtError();
Richard Smith4cd81c52013-01-29 09:02:09 +00002654
Sebastian Redla0fd8652008-12-21 16:41:36 +00002655 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2656 ParseDeclarator(ExDecl);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002657 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redla0fd8652008-12-21 16:41:36 +00002658 } else
2659 ConsumeToken();
2660
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002661 T.consumeClose();
2662 if (T.getCloseLocation().isInvalid())
Sebastian Redla0fd8652008-12-21 16:41:36 +00002663 return StmtError();
2664
2665 if (Tok.isNot(tok::l_brace))
2666 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2667
Sean Huntbbd37c62009-11-21 08:43:09 +00002668 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smith534986f2012-04-14 00:33:13 +00002669 StmtResult Block(ParseCompoundStatement());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002670 if (Block.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002671 return Block;
Sebastian Redla0fd8652008-12-21 16:41:36 +00002672
John McCall9ae2f072010-08-23 23:25:46 +00002673 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redla0fd8652008-12-21 16:41:36 +00002674}
Francois Pichet1e862692011-05-06 20:48:22 +00002675
2676void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor3896fc52011-10-24 22:31:10 +00002677 IfExistsCondition Result;
Francois Pichetf9860382011-05-07 17:30:27 +00002678 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet1e862692011-05-06 20:48:22 +00002679 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002680
Douglas Gregor3896fc52011-10-24 22:31:10 +00002681 // Handle dependent statements by parsing the braces as a compound statement.
2682 // This is not the same behavior as Visual C++, which don't treat this as a
2683 // compound statement, but for Clang's type checking we can't have anything
2684 // inside these braces escaping to the surrounding code.
2685 if (Result.Behavior == IEB_Dependent) {
2686 if (!Tok.is(tok::l_brace)) {
2687 Diag(Tok, diag::err_expected_lbrace);
Richard Smith534986f2012-04-14 00:33:13 +00002688 return;
Douglas Gregor3896fc52011-10-24 22:31:10 +00002689 }
Richard Smith534986f2012-04-14 00:33:13 +00002690
2691 StmtResult Compound = ParseCompoundStatement();
Douglas Gregorba0513d2011-10-25 01:33:02 +00002692 if (Compound.isInvalid())
2693 return;
Richard Smith534986f2012-04-14 00:33:13 +00002694
Douglas Gregorba0513d2011-10-25 01:33:02 +00002695 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2696 Result.IsIfExists,
Richard Smith534986f2012-04-14 00:33:13 +00002697 Result.SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002698 Result.Name,
2699 Compound.get());
2700 if (DepResult.isUsable())
2701 Stmts.push_back(DepResult.get());
Douglas Gregor3896fc52011-10-24 22:31:10 +00002702 return;
2703 }
Richard Smith534986f2012-04-14 00:33:13 +00002704
Douglas Gregor3896fc52011-10-24 22:31:10 +00002705 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2706 if (Braces.consumeOpen()) {
Francois Pichet1e862692011-05-06 20:48:22 +00002707 Diag(Tok, diag::err_expected_lbrace);
2708 return;
2709 }
Francois Pichet1e862692011-05-06 20:48:22 +00002710
Douglas Gregor3896fc52011-10-24 22:31:10 +00002711 switch (Result.Behavior) {
2712 case IEB_Parse:
2713 // Parse the statements below.
2714 break;
Chad Rosierb6604462012-07-10 21:35:27 +00002715
Douglas Gregor3896fc52011-10-24 22:31:10 +00002716 case IEB_Dependent:
2717 llvm_unreachable("Dependent case handled above");
Chad Rosierb6604462012-07-10 21:35:27 +00002718
Douglas Gregor3896fc52011-10-24 22:31:10 +00002719 case IEB_Skip:
2720 Braces.skipToEnd();
Francois Pichet1e862692011-05-06 20:48:22 +00002721 return;
2722 }
2723
2724 // Condition is true, parse the statements.
2725 while (Tok.isNot(tok::r_brace)) {
2726 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2727 if (R.isUsable())
2728 Stmts.push_back(R.release());
2729 }
Douglas Gregor3896fc52011-10-24 22:31:10 +00002730 Braces.consumeClose();
Francois Pichet1e862692011-05-06 20:48:22 +00002731}