blob: edf0dda7df8c09ce006233187f986f439018f494 [file] [log] [blame]
Chris Lattner7ad0fbe2006-11-05 07:46:30 +00001//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
Chris Lattner0ccd51e2006-08-09 05:47:47 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner0ccd51e2006-08-09 05:47:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Statement and Block portions of the Parser
11// interface.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Parse/Parser.h"
Chris Lattner8a9a97a2009-12-10 00:21:05 +000016#include "RAIIObjectsForParser.h"
John McCallf413f5e2013-05-03 00:10:13 +000017#include "clang/AST/ASTContext.h"
Aaron Ballmanb06b15a2014-06-06 12:40:24 +000018#include "clang/Basic/Attributes.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/PrettyStackTrace.h"
John McCall8b0666c2010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Aaron Ballmanb06b15a2014-06-06 12:40:24 +000022#include "clang/Sema/LoopHint.h"
John McCallfaf5fb42010-08-26 23:41:50 +000023#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/Scope.h"
Richard Smith4f605af2012-08-18 00:55:03 +000025#include "clang/Sema/TypoCorrection.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000026#include "llvm/ADT/SmallString.h"
Chris Lattner0ccd51e2006-08-09 05:47:47 +000027using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// C99 6.8: Statements and Blocks.
31//===----------------------------------------------------------------------===//
32
Richard Smith426a47b2013-10-28 22:04:30 +000033/// \brief Parse a standalone statement (for instance, as the body of an 'if',
34/// 'while', or 'for').
Alexey Bataevc4fad652016-01-13 11:18:54 +000035StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
36 bool AllowOpenMPStandalone) {
Richard Smith426a47b2013-10-28 22:04:30 +000037 StmtResult Res;
38
39 // We may get back a null statement if we found a #pragma. Keep going until
40 // we get an actual statement.
41 do {
42 StmtVector Stmts;
Alexey Bataevc4fad652016-01-13 11:18:54 +000043 Res = ParseStatementOrDeclaration(
44 Stmts, AllowOpenMPStandalone ? ACK_StatementsOpenMPAnyExecutable
45 : ACK_StatementsOpenMPNonStandalone,
46 TrailingElseLoc);
Richard Smith426a47b2013-10-28 22:04:30 +000047 } while (!Res.isInvalid() && !Res.get());
48
49 return Res;
50}
51
Chris Lattner0ccd51e2006-08-09 05:47:47 +000052/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
53/// StatementOrDeclaration:
54/// statement
55/// declaration
56///
57/// statement:
58/// labeled-statement
59/// compound-statement
60/// expression-statement
61/// selection-statement
62/// iteration-statement
63/// jump-statement
Argyrios Kyrtzidisdee82912008-09-07 18:58:01 +000064/// [C++] declaration-statement
Sebastian Redlb219c902008-12-21 16:41:36 +000065/// [C++] try-block
John Wiegley1c0675e2011-04-28 01:08:34 +000066/// [MS] seh-try-block
Fariborz Jahanian90814572007-10-04 20:19:06 +000067/// [OBC] objc-throw-statement
68/// [OBC] objc-try-catch-statement
Fariborz Jahanianf89ca382008-01-29 18:21:32 +000069/// [OBC] objc-synchronized-statement
Chris Lattner0116c472006-08-15 06:03:28 +000070/// [GNU] asm-statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +000071/// [OMP] openmp-construct [TODO]
72///
73/// labeled-statement:
74/// identifier ':' statement
75/// 'case' constant-expression ':' statement
76/// 'default' ':' statement
77///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000078/// selection-statement:
79/// if-statement
80/// switch-statement
81///
82/// iteration-statement:
83/// while-statement
84/// do-statement
85/// for-statement
86///
Chris Lattner9075bd72006-08-10 04:59:57 +000087/// expression-statement:
88/// expression[opt] ';'
89///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000090/// jump-statement:
91/// 'goto' identifier ';'
92/// 'continue' ';'
93/// 'break' ';'
94/// 'return' expression[opt] ';'
Chris Lattner503fadc2006-08-10 05:45:44 +000095/// [GNU] 'goto' '*' expression ';'
Chris Lattner0ccd51e2006-08-09 05:47:47 +000096///
Fariborz Jahanian90814572007-10-04 20:19:06 +000097/// [OBC] objc-throw-statement:
98/// [OBC] '@' 'throw' expression ';'
Mike Stump11289f42009-09-09 15:08:12 +000099/// [OBC] '@' 'throw' ';'
100///
John McCalldadc5752010-08-24 06:29:42 +0000101StmtResult
Alexey Bataevc4fad652016-01-13 11:18:54 +0000102Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
103 AllowedContsructsKind Allowed,
Nico Weber3cef1082011-12-22 23:26:17 +0000104 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000105
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +0000106 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000107
Richard Smithc202b282012-04-14 00:33:13 +0000108 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +0000109 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
Richard Smithc202b282012-04-14 00:33:13 +0000110
Alexey Bataevc4fad652016-01-13 11:18:54 +0000111 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
112 Stmts, Allowed, TrailingElseLoc, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000113
114 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
115 "attributes on empty statement");
116
117 if (Attrs.empty() || Res.isInvalid())
118 return Res;
119
120 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
121}
122
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000123namespace {
124class StatementFilterCCC : public CorrectionCandidateCallback {
125public:
126 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000127 WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
128 tok::identifier, tok::star, tok::amp);
129 WantExpressionKeywords =
130 nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
131 WantRemainingKeywords =
132 nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000133 WantCXXNamedCasts = false;
134 }
135
Craig Topper2b07f022014-03-12 05:09:18 +0000136 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000137 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
Kaelyn Uhrain07e62722013-10-01 22:00:28 +0000138 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain46b6cdc2013-09-27 19:40:16 +0000139 if (NextToken.is(tok::equal))
140 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain30943ce2013-09-27 23:54:23 +0000141 if (NextToken.is(tok::period) &&
142 candidate.getCorrectionDeclAs<NamespaceDecl>())
143 return false;
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000144 return CorrectionCandidateCallback::ValidateCandidate(candidate);
145 }
146
147private:
148 Token NextToken;
149};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000150}
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000151
Richard Smithc202b282012-04-14 00:33:13 +0000152StmtResult
153Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
Alexey Bataevc4fad652016-01-13 11:18:54 +0000154 AllowedContsructsKind Allowed, SourceLocation *TrailingElseLoc,
Richard Smithc202b282012-04-14 00:33:13 +0000155 ParsedAttributesWithRange &Attrs) {
Craig Topper161e4db2014-05-21 06:02:52 +0000156 const char *SemiError = nullptr;
Richard Smithc202b282012-04-14 00:33:13 +0000157 StmtResult Res;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000158
Chris Lattner503fadc2006-08-10 05:45:44 +0000159 // Cases in this switch statement should fall through if the parser expects
160 // the token to end in a semicolon (in which case SemiError should be set),
161 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000162Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000163 tok::TokenKind Kind = Tok.getKind();
164 SourceLocation AtLoc;
165 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000166 case tok::at: // May be a @try or @throw statement
167 {
Richard Smithc202b282012-04-14 00:33:13 +0000168 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000169 AtLoc = ConsumeToken(); // consume @
Sebastian Redlbab9a4b2008-12-11 20:12:42 +0000170 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000171 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000172
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000173 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000174 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000175 cutOffParsing();
176 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000177
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000178 case tok::identifier: {
179 Token Next = NextToken();
180 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000181 // identifier ':' statement
Richard Smithc202b282012-04-14 00:33:13 +0000182 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000183 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000184
Richard Smith4f605af2012-08-18 00:55:03 +0000185 // Look up the identifier, and typo-correct it to a keyword if it's not
186 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000187 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000188 // Try to limit which sets of keywords should be included in typo
189 // correction based on what the next token is.
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000190 if (TryAnnotateName(/*IsAddressOfOperand*/ false,
191 llvm::make_unique<StatementFilterCCC>(Next)) ==
192 ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000193 // Handle errors here by skipping up to the next semicolon or '}', and
194 // eat the semicolon if that's what stopped us.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000195 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000196 if (Tok.is(tok::semi))
197 ConsumeToken();
198 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000199 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000200
Richard Smith4f605af2012-08-18 00:55:03 +0000201 // If the identifier was typo-corrected, try again.
202 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000203 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000204 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000205
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000206 // Fall through
207 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000208
Chris Lattner803802d2009-03-24 17:04:48 +0000209 default: {
Alexey Bataevc4fad652016-01-13 11:18:54 +0000210 if ((getLangOpts().CPlusPlus || Allowed == ACK_Any) &&
211 isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000212 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Rafael Espindola1bd906d2014-10-22 14:27:08 +0000213 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000214 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000215 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000216 }
217
218 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000219 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000220 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000221 }
Mike Stump11289f42009-09-09 15:08:12 +0000222
Richard Smithc202b282012-04-14 00:33:13 +0000223 return ParseExprStatement();
Chris Lattner803802d2009-03-24 17:04:48 +0000224 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000225
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000226 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000227 return ParseCaseStatement();
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000228 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000229 return ParseDefaultStatement();
Sebastian Redl042ad952008-12-11 19:30:53 +0000230
Chris Lattner9075bd72006-08-10 04:59:57 +0000231 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000232 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000233 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000234 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
235 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000236 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000237
Chris Lattner9075bd72006-08-10 04:59:57 +0000238 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000239 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000240 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000241 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000242
Chris Lattner9075bd72006-08-10 04:59:57 +0000243 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000244 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000245 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000246 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000247 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000248 break;
249 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000250 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000251
252 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000253 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000254 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000255 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000256 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000257 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000258 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000259 break;
260 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000261 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000262 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000263 break;
264 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000265 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000266 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000267 break;
Richard Smith0e304ea2015-10-22 04:46:14 +0000268 case tok::kw_co_return: // C++ Coroutines: co_return statement
269 Res = ParseReturnStatement();
270 SemiError = "co_return";
271 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000272
Sebastian Redlb219c902008-12-21 16:41:36 +0000273 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000274 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000275 bool msAsm = false;
276 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000277 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000278 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000279 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000280 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000281 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000282
Reid Kleckner6d8d22a2014-06-25 00:28:35 +0000283 case tok::kw___if_exists:
284 case tok::kw___if_not_exists:
285 ProhibitAttributes(Attrs);
286 ParseMicrosoftIfExistsStatement(Stmts);
287 // An __if_exists block is like a compound statement, but it doesn't create
288 // a new scope.
289 return StmtEmpty();
290
Sebastian Redlb219c902008-12-21 16:41:36 +0000291 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000292 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000293
294 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000295 ProhibitAttributes(Attrs); // TODO: is it correct?
296 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000297
Nico Weberc7d05962014-07-06 22:32:59 +0000298 case tok::kw___leave:
299 Res = ParseSEHLeaveStatement();
300 SemiError = "__leave";
301 break;
302
Eli Friedmanec52f922012-02-23 23:47:16 +0000303 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000304 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000305 HandlePragmaVisibility();
306 return StmtEmpty();
307
308 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000309 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000310 HandlePragmaPack();
311 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000312
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000313 case tok::annot_pragma_msstruct:
314 ProhibitAttributes(Attrs);
315 HandlePragmaMSStruct();
316 return StmtEmpty();
317
Eli Friedmanae8ee252012-10-08 23:52:38 +0000318 case tok::annot_pragma_align:
319 ProhibitAttributes(Attrs);
320 HandlePragmaAlign();
321 return StmtEmpty();
322
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000323 case tok::annot_pragma_weak:
324 ProhibitAttributes(Attrs);
325 HandlePragmaWeak();
326 return StmtEmpty();
327
328 case tok::annot_pragma_weakalias:
329 ProhibitAttributes(Attrs);
330 HandlePragmaWeakAlias();
331 return StmtEmpty();
332
333 case tok::annot_pragma_redefine_extname:
334 ProhibitAttributes(Attrs);
335 HandlePragmaRedefineExtname();
336 return StmtEmpty();
337
Eli Friedman68be1642012-10-04 02:36:51 +0000338 case tok::annot_pragma_fp_contract:
Richard Smithca9b0b62013-11-15 21:10:54 +0000339 ProhibitAttributes(Attrs);
Lang Hamesa930e712012-10-21 01:10:01 +0000340 Diag(Tok, diag::err_pragma_fp_contract_scope);
341 ConsumeToken();
342 return StmtError();
343
Eli Friedman68be1642012-10-04 02:36:51 +0000344 case tok::annot_pragma_opencl_extension:
345 ProhibitAttributes(Attrs);
346 HandlePragmaOpenCLExtension();
347 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000348
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000349 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000350 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000351 return HandlePragmaCaptured();
352
Alexey Bataeva769e072013-03-22 06:34:35 +0000353 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000354 ProhibitAttributes(Attrs);
Alexey Bataevc4fad652016-01-13 11:18:54 +0000355 return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000356
David Majnemer4bb09802014-02-10 19:50:15 +0000357 case tok::annot_pragma_ms_pointers_to_members:
358 ProhibitAttributes(Attrs);
359 HandlePragmaMSPointersToMembers();
360 return StmtEmpty();
361
Warren Huntc3b18962014-04-08 22:30:47 +0000362 case tok::annot_pragma_ms_pragma:
363 ProhibitAttributes(Attrs);
364 HandlePragmaMSPragma();
365 return StmtEmpty();
Aaron Ballmanb06b15a2014-06-06 12:40:24 +0000366
Alexey Bataev3d42f342015-11-20 07:02:57 +0000367 case tok::annot_pragma_ms_vtordisp:
368 ProhibitAttributes(Attrs);
369 HandlePragmaMSVtorDisp();
370 return StmtEmpty();
371
Aaron Ballmanb06b15a2014-06-06 12:40:24 +0000372 case tok::annot_pragma_loop_hint:
373 ProhibitAttributes(Attrs);
Alexey Bataevc4fad652016-01-13 11:18:54 +0000374 return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
Richard Smithba3a4f92016-01-12 21:59:26 +0000375
376 case tok::annot_pragma_dump:
377 HandlePragmaDump();
378 return StmtEmpty();
Sebastian Redlb219c902008-12-21 16:41:36 +0000379 }
380
Chris Lattner503fadc2006-08-10 05:45:44 +0000381 // If we reached this code, the statement must end in a semicolon.
Alp Toker97650562014-01-10 11:19:30 +0000382 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000383 // If the result was valid, then we do want to diagnose this. Use
384 // ExpectAndConsume to emit the diagnostic, even though we know it won't
385 // succeed.
386 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000387 // Skip until we see a } or ;, but don't eat it.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000388 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Chris Lattner503fadc2006-08-10 05:45:44 +0000389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000391 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000392}
393
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000394/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000395StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000396 // If a case keyword is missing, this is where it should be inserted.
397 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000398
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000399 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000400 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000401 if (Expr.isInvalid()) {
402 // If the expression is invalid, skip ahead to the next semicolon or '}'.
403 // Not doing this opens us up to the possibility of infinite loops if
404 // ParseExpression does not consume any tokens.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000405 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000406 if (Tok.is(tok::semi))
407 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000408 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000409 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000410
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000411 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
412 Actions.CheckCaseExpression(Expr.get())) {
413 // If a constant expression is followed by a colon inside a switch block,
414 // suggest a missing case keyword.
415 Diag(OldToken, diag::err_expected_case_before_expression)
416 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000417
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000418 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000419 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000420 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000421
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000422 // Otherwise, eat the semicolon.
423 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000424 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000425}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000426
John Wiegley1c0675e2011-04-28 01:08:34 +0000427/// ParseSEHTryBlockCommon
428///
429/// seh-try-block:
430/// '__try' compound-statement seh-handler
431///
432/// seh-handler:
433/// seh-except-block
434/// seh-finally-block
435///
Nico Weberdd256742015-02-25 01:43:27 +0000436StmtResult Parser::ParseSEHTryBlock() {
437 assert(Tok.is(tok::kw___try) && "Expected '__try'");
438 SourceLocation TryLoc = ConsumeToken();
439
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000440 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +0000441 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
John Wiegley1c0675e2011-04-28 01:08:34 +0000442
Warren Huntf6be4cb2014-07-25 20:52:51 +0000443 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
444 Scope::DeclScope | Scope::SEHTryScope));
John Wiegley1c0675e2011-04-28 01:08:34 +0000445 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000446 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000447
448 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000449 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000450 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000451 SourceLocation Loc = ConsumeToken();
452 Handler = ParseSEHExceptBlock(Loc);
453 } else if (Tok.is(tok::kw___finally)) {
454 SourceLocation Loc = ConsumeToken();
455 Handler = ParseSEHFinallyBlock(Loc);
456 } else {
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000457 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
John Wiegley1c0675e2011-04-28 01:08:34 +0000458 }
459
460 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000461 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000462
463 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
464 TryLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000465 TryBlock.get(),
Warren Huntf6be4cb2014-07-25 20:52:51 +0000466 Handler.get());
John Wiegley1c0675e2011-04-28 01:08:34 +0000467}
468
469/// ParseSEHExceptBlock - Handle __except
470///
471/// seh-except-block:
472/// '__except' '(' seh-filter-expression ')' compound-statement
473///
474StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
475 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
476 raii2(Ident___exception_code, false),
477 raii3(Ident_GetExceptionCode, false);
478
Alp Toker383d2c42014-01-01 03:08:43 +0000479 if (ExpectAndConsume(tok::l_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000480 return StmtError();
481
Reid Kleckner1d59f992015-01-22 01:36:17 +0000482 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
483 Scope::SEHExceptScope);
John Wiegley1c0675e2011-04-28 01:08:34 +0000484
David Blaikiebbafb8a2012-03-11 07:00:24 +0000485 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000486 Ident__exception_info->setIsPoisoned(false);
487 Ident___exception_info->setIsPoisoned(false);
488 Ident_GetExceptionInfo->setIsPoisoned(false);
489 }
Reid Kleckner1d59f992015-01-22 01:36:17 +0000490
491 ExprResult FilterExpr;
492 {
493 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
494 Scope::SEHFilterScope);
Reid Kleckner85368fb2015-04-02 22:09:32 +0000495 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Reid Kleckner1d59f992015-01-22 01:36:17 +0000496 }
Francois Pichetbfaf4772011-04-28 03:14:31 +0000497
David Blaikiebbafb8a2012-03-11 07:00:24 +0000498 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000499 Ident__exception_info->setIsPoisoned(true);
500 Ident___exception_info->setIsPoisoned(true);
501 Ident_GetExceptionInfo->setIsPoisoned(true);
502 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000503
504 if(FilterExpr.isInvalid())
505 return StmtError();
506
Alp Toker383d2c42014-01-01 03:08:43 +0000507 if (ExpectAndConsume(tok::r_paren))
John Wiegley1c0675e2011-04-28 01:08:34 +0000508 return StmtError();
509
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000510 if (Tok.isNot(tok::l_brace))
511 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
512
Richard Smithc202b282012-04-14 00:33:13 +0000513 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000514
515 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000516 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000517
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000518 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
John Wiegley1c0675e2011-04-28 01:08:34 +0000519}
520
521/// ParseSEHFinallyBlock - Handle __finally
522///
523/// seh-finally-block:
524/// '__finally' compound-statement
525///
Nico Weberd64657f2015-03-09 02:47:59 +0000526StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000527 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
528 raii2(Ident___abnormal_termination, false),
529 raii3(Ident_AbnormalTermination, false);
530
Nico Weberfc3fe4f2015-02-25 02:22:06 +0000531 if (Tok.isNot(tok::l_brace))
532 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
533
Nico Weberd64657f2015-03-09 02:47:59 +0000534 ParseScope FinallyScope(this, 0);
535 Actions.ActOnStartSEHFinallyBlock();
536
Richard Smithc202b282012-04-14 00:33:13 +0000537 StmtResult Block(ParseCompoundStatement());
Nico Weberce903292015-03-09 03:17:15 +0000538 if(Block.isInvalid()) {
539 Actions.ActOnAbortSEHFinallyBlock();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000540 return Block;
Nico Weberce903292015-03-09 03:17:15 +0000541 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000542
Nico Weberd64657f2015-03-09 02:47:59 +0000543 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000544}
545
Nico Weberc7d05962014-07-06 22:32:59 +0000546/// Handle __leave
547///
548/// seh-leave-statement:
549/// '__leave' ';'
550///
551StmtResult Parser::ParseSEHLeaveStatement() {
552 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
553 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
554}
555
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000556/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000557///
558/// labeled-statement:
559/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000560/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000561///
Richard Smithc202b282012-04-14 00:33:13 +0000562StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000563 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
564 "Not an identifier!");
565
566 Token IdentTok = Tok; // Save the whole token.
567 ConsumeToken(); // eat the identifier.
568
569 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000570
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000571 // identifier ':' statement
572 SourceLocation ColonLoc = ConsumeToken();
573
Richard Smitha3e01cf2013-11-15 22:45:29 +0000574 // Read label attributes, if present.
575 StmtResult SubStmt;
576 if (Tok.is(tok::kw___attribute)) {
577 ParsedAttributesWithRange TempAttrs(AttrFactory);
578 ParseGNUAttributes(TempAttrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000579
Richard Smitha3e01cf2013-11-15 22:45:29 +0000580 // In C++, GNU attributes only apply to the label if they are followed by a
581 // semicolon, to disambiguate label attributes from attributes on a labeled
582 // declaration.
583 //
584 // This doesn't quite match what GCC does; if the attribute list is empty
585 // and followed by a semicolon, GCC will reject (it appears to parse the
586 // attributes as part of a statement in that case). That looks like a bug.
587 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
588 attrs.takeAllFrom(TempAttrs);
589 else if (isDeclarationStatement()) {
590 StmtVector Stmts;
591 // FIXME: We should do this whether or not we have a declaration
592 // statement, but that doesn't work correctly (because ProhibitAttributes
593 // can't handle GNU attributes), so only call it in the one case where
594 // GNU attributes are allowed.
595 SubStmt = ParseStatementOrDeclarationAfterAttributes(
Alexey Bataevc4fad652016-01-13 11:18:54 +0000596 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
597 TempAttrs);
Richard Smitha3e01cf2013-11-15 22:45:29 +0000598 if (!TempAttrs.empty() && !SubStmt.isInvalid())
599 SubStmt = Actions.ProcessStmtAttributes(
600 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
601 } else {
Alp Toker383d2c42014-01-01 03:08:43 +0000602 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
Richard Smitha3e01cf2013-11-15 22:45:29 +0000603 }
604 }
605
606 // If we've not parsed a statement yet, parse one now.
607 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
608 SubStmt = ParseStatement();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000609
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000610 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000611 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000612 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000613
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000614 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
615 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000616 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000617 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000618 attrs.clear();
619 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000620
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000621 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
622 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000623}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000624
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000625/// ParseCaseStatement
626/// labeled-statement:
627/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000628/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000629///
Richard Smithc202b282012-04-14 00:33:13 +0000630StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000631 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattner34a22092009-03-04 04:23:07 +0000633 // It is very very common for code to contain many case statements recursively
634 // nested, as in (but usually without indentation):
635 // case 1:
636 // case 2:
637 // case 3:
638 // case 4:
639 // case 5: etc.
640 //
641 // Parsing this naively works, but is both inefficient and can cause us to run
642 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000643 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000644 // but all the grossness is constrained to ParseCaseStatement (and some
Richard Smitha3e01cf2013-11-15 22:45:29 +0000645 // weirdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattner34a22092009-03-04 04:23:07 +0000647 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
648 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000649 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000650
Chris Lattner34a22092009-03-04 04:23:07 +0000651 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
652 // gets updated each time a new case is parsed, and whose body is unset so
653 // far. When parsing 'case 4', this is the 'case 3' node.
Craig Topper161e4db2014-05-21 06:02:52 +0000654 Stmt *DeepestParsedCaseStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000655
Chris Lattner34a22092009-03-04 04:23:07 +0000656 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000657 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000658 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000659 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
660 ConsumeToken(); // eat the 'case'.
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000661 ColonLoc = SourceLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000662
Douglas Gregord328d572009-09-21 18:10:23 +0000663 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000664 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000665 cutOffParsing();
666 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000667 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000668
Chris Lattner125c0ee2009-12-10 00:38:54 +0000669 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
670 /// Disable this form of error recovery while we're parsing the case
671 /// expression.
672 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000673
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000674 ExprResult LHS;
675 if (!MissingCase) {
676 LHS = ParseConstantExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000677 if (!getLangOpts().CPlusPlus11) {
678 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
679 return Actions.VerifyIntegerConstantExpression(E);
680 });
681 }
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000682 if (LHS.isInvalid()) {
683 // If constant-expression is parsed unsuccessfully, recover by skipping
684 // current case statement (moving to the colon that ends it).
685 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
686 TryConsumeToken(tok::colon, ColonLoc);
687 continue;
688 }
689 return StmtError();
690 }
691 } else {
692 LHS = Expr;
693 MissingCase = false;
Chris Lattner476c3ad2006-08-13 22:09:58 +0000694 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000695
Chris Lattner34a22092009-03-04 04:23:07 +0000696 // GNU case range extension.
697 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000698 ExprResult RHS;
Alp Tokerec543272013-12-24 09:48:30 +0000699 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
700 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
Chris Lattner34a22092009-03-04 04:23:07 +0000701 RHS = ParseConstantExpression();
702 if (RHS.isInvalid()) {
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000703 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
704 TryConsumeToken(tok::colon, ColonLoc);
705 continue;
706 }
Chris Lattner34a22092009-03-04 04:23:07 +0000707 return StmtError();
708 }
709 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000710
Chris Lattner125c0ee2009-12-10 00:38:54 +0000711 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000712
Alp Tokerec543272013-12-24 09:48:30 +0000713 if (TryConsumeToken(tok::colon, ColonLoc)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000714 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
715 TryConsumeToken(tok::coloncolon, ColonLoc)) {
716 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
Alp Tokerec543272013-12-24 09:48:30 +0000717 Diag(ColonLoc, diag::err_expected_after)
718 << "'case'" << tok::colon
719 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000720 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000721 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000722 Diag(ExpectedLoc, diag::err_expected_after)
723 << "'case'" << tok::colon
724 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000725 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000726 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000727
John McCalldadc5752010-08-24 06:29:42 +0000728 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000729 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
730 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000731
Chris Lattner34a22092009-03-04 04:23:07 +0000732 // If we had a sema error parsing this case, then just ignore it and
733 // continue parsing the sub-stmt.
734 if (Case.isInvalid()) {
735 if (TopLevelCase.isInvalid()) // No parsed case stmts.
Alexey Bataevc4fad652016-01-13 11:18:54 +0000736 return ParseStatement(/*TrailingElseLoc=*/nullptr,
737 /*AllowOpenMPStandalone=*/true);
Chris Lattner34a22092009-03-04 04:23:07 +0000738 // Otherwise, just don't add it as a nested case.
739 } else {
740 // If this is the first case statement we parsed, it becomes TopLevelCase.
741 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000742 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000743 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000744 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000745 else
John McCallb268a282010-08-23 23:25:46 +0000746 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000747 DeepestParsedCaseStmt = NextDeepest;
748 }
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattner34a22092009-03-04 04:23:07 +0000750 // Handle all case statements.
751 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000752
Chris Lattner34a22092009-03-04 04:23:07 +0000753 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000754 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattner34a22092009-03-04 04:23:07 +0000756 if (Tok.isNot(tok::r_brace)) {
Alexey Bataevc4fad652016-01-13 11:18:54 +0000757 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
758 /*AllowOpenMPStandalone=*/true);
Chris Lattner34a22092009-03-04 04:23:07 +0000759 } else {
760 // Nicely diagnose the common error "switch (X) { case 4: }", which is
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000761 // not valid. If ColonLoc doesn't point to a valid text location, there was
762 // another parsing error, so avoid producing extra diagnostics.
763 if (ColonLoc.isValid()) {
764 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
765 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
766 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
767 }
768 SubStmt = StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +0000769 }
Mike Stump11289f42009-09-09 15:08:12 +0000770
Chris Lattner34a22092009-03-04 04:23:07 +0000771 // Install the body into the most deeply-nested case.
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000772 if (DeepestParsedCaseStmt) {
773 // Broken sub-stmt shouldn't prevent forming the case statement properly.
774 if (SubStmt.isInvalid())
775 SubStmt = Actions.ActOnNullStmt(SourceLocation());
776 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
777 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000778
Chris Lattner34a22092009-03-04 04:23:07 +0000779 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000780 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000781}
782
783/// ParseDefaultStatement
784/// labeled-statement:
785/// 'default' ':' statement
786/// Note that this does not parse the 'statement' at the end.
787///
Richard Smithc202b282012-04-14 00:33:13 +0000788StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000789 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000790 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000791
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000792 SourceLocation ColonLoc;
Alp Tokerec543272013-12-24 09:48:30 +0000793 if (TryConsumeToken(tok::colon, ColonLoc)) {
Alp Tokerec543272013-12-24 09:48:30 +0000794 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
Alp Toker97650562014-01-10 11:19:30 +0000795 // Treat "default;" as a typo for "default:".
Alp Tokerec543272013-12-24 09:48:30 +0000796 Diag(ColonLoc, diag::err_expected_after)
797 << "'default'" << tok::colon
798 << FixItHint::CreateReplacement(ColonLoc, ":");
John McCall0140bfe2011-01-22 09:28:32 +0000799 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000800 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Alp Tokerec543272013-12-24 09:48:30 +0000801 Diag(ExpectedLoc, diag::err_expected_after)
802 << "'default'" << tok::colon
803 << FixItHint::CreateInsertion(ExpectedLoc, ":");
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000804 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000805 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000806
Richard Smith1002d102012-02-17 01:35:32 +0000807 StmtResult SubStmt;
808
809 if (Tok.isNot(tok::r_brace)) {
Alexey Bataevc4fad652016-01-13 11:18:54 +0000810 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
811 /*AllowOpenMPStandalone=*/true);
Richard Smith1002d102012-02-17 01:35:32 +0000812 } else {
813 // Diagnose the common error "switch (X) {... default: }", which is
814 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000815 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000816 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
817 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
818 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000819 }
820
Richard Smith1002d102012-02-17 01:35:32 +0000821 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000822 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000823 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000824
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000825 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000826 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000827}
828
Richard Smithc202b282012-04-14 00:33:13 +0000829StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
830 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000831}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000832
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000833/// ParseCompoundStatement - Parse a "{}" block.
834///
835/// compound-statement: [C99 6.8.2]
836/// { block-item-list[opt] }
837/// [GNU] { label-declarations block-item-list } [TODO]
838///
839/// block-item-list:
840/// block-item
841/// block-item-list block-item
842///
843/// block-item:
844/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000845/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000846/// statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000847///
848/// [GNU] label-declarations:
849/// [GNU] label-declaration
850/// [GNU] label-declarations label-declaration
851///
852/// [GNU] label-declaration:
853/// [GNU] '__label__' identifier-list ';'
854///
Richard Smithc202b282012-04-14 00:33:13 +0000855StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000856 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000857 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000858
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000859 // Enter a scope to hold everything within the compound stmt. Compound
860 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000861 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000862
863 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000864 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000865}
866
Lang Hames2954cea2012-11-03 22:29:05 +0000867/// Parse any pragmas at the start of the compound expression. We handle these
868/// separately since some pragmas (FP_CONTRACT) must appear before any C
869/// statement in the compound, but may be intermingled with other pragmas.
870void Parser::ParseCompoundStatementLeadingPragmas() {
871 bool checkForPragmas = true;
872 while (checkForPragmas) {
873 switch (Tok.getKind()) {
874 case tok::annot_pragma_vis:
875 HandlePragmaVisibility();
876 break;
877 case tok::annot_pragma_pack:
878 HandlePragmaPack();
879 break;
880 case tok::annot_pragma_msstruct:
881 HandlePragmaMSStruct();
882 break;
883 case tok::annot_pragma_align:
884 HandlePragmaAlign();
885 break;
886 case tok::annot_pragma_weak:
887 HandlePragmaWeak();
888 break;
889 case tok::annot_pragma_weakalias:
890 HandlePragmaWeakAlias();
891 break;
892 case tok::annot_pragma_redefine_extname:
893 HandlePragmaRedefineExtname();
894 break;
895 case tok::annot_pragma_opencl_extension:
896 HandlePragmaOpenCLExtension();
897 break;
898 case tok::annot_pragma_fp_contract:
899 HandlePragmaFPContract();
900 break;
David Majnemer4bb09802014-02-10 19:50:15 +0000901 case tok::annot_pragma_ms_pointers_to_members:
902 HandlePragmaMSPointersToMembers();
903 break;
Warren Huntc3b18962014-04-08 22:30:47 +0000904 case tok::annot_pragma_ms_pragma:
905 HandlePragmaMSPragma();
906 break;
Alexey Bataev3d42f342015-11-20 07:02:57 +0000907 case tok::annot_pragma_ms_vtordisp:
908 HandlePragmaMSVtorDisp();
909 break;
Richard Smithba3a4f92016-01-12 21:59:26 +0000910 case tok::annot_pragma_dump:
911 HandlePragmaDump();
912 break;
Lang Hames2954cea2012-11-03 22:29:05 +0000913 default:
914 checkForPragmas = false;
915 break;
916 }
917 }
918
919}
920
Chris Lattnerf2978802007-01-21 06:52:16 +0000921/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000922/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000923/// consume the '}' at the end of the block. It does not manipulate the scope
924/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000925StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000926 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000927 Tok.getLocation(),
928 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000929
930 // Record the state of the FP_CONTRACT pragma, restore on leaving the
931 // compound statement.
932 Sema::FPContractStateRAII SaveFPContractState(Actions);
933
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000934 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000935 BalancedDelimiterTracker T(*this, tok::l_brace);
936 if (T.consumeOpen())
937 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000938
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000939 Sema::CompoundScopeRAII CompoundScope(Actions);
940
Lang Hames2954cea2012-11-03 22:29:05 +0000941 // Parse any pragmas at the beginning of the compound statement.
942 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000943
Lang Hames2954cea2012-11-03 22:29:05 +0000944 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000945
Chris Lattner43e7f312011-02-18 02:08:43 +0000946 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
947 // only allowed at the start of a compound stmt regardless of the language.
948 while (Tok.is(tok::kw___label__)) {
949 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000950
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000951 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000952 while (1) {
953 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +0000954 Diag(Tok, diag::err_expected) << tok::identifier;
Chris Lattner43e7f312011-02-18 02:08:43 +0000955 break;
956 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000957
Chris Lattner43e7f312011-02-18 02:08:43 +0000958 IdentifierInfo *II = Tok.getIdentifierInfo();
959 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000960 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000961
Alp Tokerec543272013-12-24 09:48:30 +0000962 if (!TryConsumeToken(tok::comma))
Chris Lattner43e7f312011-02-18 02:08:43 +0000963 break;
Chris Lattner43e7f312011-02-18 02:08:43 +0000964 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000965
John McCall084e83d2011-03-24 11:26:52 +0000966 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000967 DeclGroupPtrTy Res =
968 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000969 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000970
Chris Lattner02f1b612012-04-28 16:12:17 +0000971 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000972 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000973 Stmts.push_back(R.get());
Chris Lattner43e7f312011-02-18 02:08:43 +0000974 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000975
Richard Smith752ada82015-11-17 23:32:01 +0000976 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
977 Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000978 if (Tok.is(tok::annot_pragma_unused)) {
979 HandlePragmaUnused();
980 continue;
981 }
982
John McCalldadc5752010-08-24 06:29:42 +0000983 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000984 if (Tok.isNot(tok::kw___extension__)) {
Alexey Bataevc4fad652016-01-13 11:18:54 +0000985 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000986 } else {
987 // __extension__ can start declarations and it can also be a unary
988 // operator for expressions. Consume multiple __extension__ markers here
989 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000990 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000991 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000992 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000993 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000994
John McCall084e83d2011-03-24 11:26:52 +0000995 ParsedAttributesWithRange attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +0000996 MaybeParseCXX11Attributes(attrs, nullptr,
997 /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000998
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000999 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +00001000 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +00001001 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +00001002 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +00001003 ExtensionRAIIObject O(Diags);
1004
Chris Lattner49836b42009-04-02 04:16:50 +00001005 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001006 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +00001007 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001008 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001009 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +00001010 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +00001011 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +00001012
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001013 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001014 SkipUntil(tok::semi);
1015 continue;
1016 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +00001017
Alexis Hunt96d5c762009-11-21 08:43:09 +00001018 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +00001019 // Eat the semicolon at the end of stmt and convert the expr into a
1020 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +00001021 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +00001022 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +00001023 }
1024 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001025
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001026 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001027 Stmts.push_back(R.get());
Chris Lattner30f910e2006-10-16 05:52:41 +00001028 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001029
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001030 SourceLocation CloseLoc = Tok.getLocation();
1031
Chris Lattner0ccd51e2006-08-09 05:47:47 +00001032 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +00001033 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001034 // Recover by creating a compound statement with what we parsed so far,
1035 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +00001036 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001037
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +00001038 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001039 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +00001040}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001041
Chris Lattnerc0081db2008-12-12 06:31:07 +00001042/// ParseParenExprOrCondition:
1043/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +00001044/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +00001045///
1046/// This function parses and performs error recovery on the specified condition
1047/// or expression (depending on whether we're in C++ or C mode). This function
1048/// goes out of its way to recover well. It returns true if there was a parser
1049/// error (the right paren couldn't be found), which indicates that the caller
1050/// should try to recover harder. It returns false if the condition is
1051/// successfully parsed. Note that a successful parse can still have semantic
1052/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +00001053bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +00001054 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001055 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001056 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001057 BalancedDelimiterTracker T(*this, tok::l_paren);
1058 T.consumeOpen();
1059
David Blaikiebbafb8a2012-03-11 07:00:24 +00001060 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001061 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001062 else {
1063 ExprResult = ParseExpression();
Craig Topper161e4db2014-05-21 06:02:52 +00001064 DeclResult = nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001065
Douglas Gregore60e41a2010-05-06 17:25:47 +00001066 // If required, convert to a boolean value.
1067 if (!ExprResult.isInvalid() && ConvertToBoolean)
1068 ExprResult
John McCallb268a282010-08-23 23:25:46 +00001069 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001070 }
Mike Stump11289f42009-09-09 15:08:12 +00001071
Chris Lattnerc0081db2008-12-12 06:31:07 +00001072 // If the parser was confused by the condition and we don't have a ')', try to
1073 // recover by skipping ahead to a semi and bailing out. If condexp is
1074 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +00001075 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +00001076 SkipUntil(tok::semi);
1077 // Skipping may have stopped if it found the containing ')'. If so, we can
1078 // continue parsing the if statement.
1079 if (Tok.isNot(tok::r_paren))
1080 return true;
1081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
Chris Lattnerc0081db2008-12-12 06:31:07 +00001083 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001084 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +00001085
Chris Lattner70d44982012-04-28 16:24:20 +00001086 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1087 // that all callers are looking for a statement after the condition, so ")"
1088 // isn't valid.
1089 while (Tok.is(tok::r_paren)) {
1090 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1091 << FixItHint::CreateRemoval(Tok.getLocation());
1092 ConsumeParen();
1093 }
Chad Rosier67055f52012-07-10 21:35:27 +00001094
Chris Lattnerc0081db2008-12-12 06:31:07 +00001095 return false;
1096}
1097
1098
Chris Lattnerc951dae2006-08-10 04:23:57 +00001099/// ParseIfStatement
1100/// if-statement: [C99 6.8.4.1]
1101/// 'if' '(' expression ')' statement
1102/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001103/// [C++] 'if' '(' condition ')' statement
1104/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +00001105///
Richard Smithc202b282012-04-14 00:33:13 +00001106StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001107 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001108 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +00001109
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001110 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001111 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +00001112 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +00001113 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +00001114 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001115
David Blaikiebbafb8a2012-03-11 07:00:24 +00001116 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001117
Chris Lattner2dd1b722007-08-26 23:08:06 +00001118 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1119 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001120 //
1121 // C++ 6.4p3:
1122 // A name introduced by a declaration in a condition is in scope from its
1123 // point of declaration until the end of the substatements controlled by the
1124 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001125 // C++ 3.3.2p4:
1126 // Names declared in the for-init-statement, and in the condition of if,
1127 // while, for, and switch statements are local to the if, while, for, or
1128 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001129 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001130 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001131
Chris Lattnerc951dae2006-08-10 04:23:57 +00001132 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001133 ExprResult CondExp;
Craig Topper161e4db2014-05-21 06:02:52 +00001134 Decl *CondVar = nullptr;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001135 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001136 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001137
David Blaikiea5696df2012-05-16 04:20:04 +00001138 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001139
Chris Lattner8fb26252007-08-22 05:28:50 +00001140 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001141 // there is no compound stmt. C90 does not have this clause. We only do this
1142 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001143 //
1144 // C++ 6.4p1:
1145 // The substatement in a selection-statement (each substatement, in the else
1146 // form of the if statement) implicitly defines a local scope.
1147 //
1148 // For C++ we create a scope for the condition and a new scope for
1149 // substatements because:
1150 // -When the 'then' scope exits, we want the condition declaration to still be
1151 // active for the 'else' scope too.
1152 // -Sema will detect name clashes by considering declarations of a
1153 // 'ControlScope' as part of its direct subscope.
1154 // -If we wanted the condition and substatement to be in the same scope, we
1155 // would have to notify ParseStatement not to create a new scope. It's
1156 // simpler to let it create a new scope.
1157 //
David Majnemer2206bf52014-03-05 08:57:59 +00001158 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001159
Chris Lattner5c5808a2007-10-29 05:08:52 +00001160 // Read the 'then' stmt.
1161 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001162
1163 SourceLocation InnerStatementTrailingElseLoc;
1164 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001165
Chris Lattner37e54f42007-08-22 05:16:28 +00001166 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001167 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001168
Chris Lattnerc951dae2006-08-10 04:23:57 +00001169 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001170 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001171 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001172 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001173
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001174 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001175 if (TrailingElseLoc)
1176 *TrailingElseLoc = Tok.getLocation();
1177
Chris Lattneraf635312006-10-16 06:06:51 +00001178 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001179 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001180
Chris Lattner8fb26252007-08-22 05:28:50 +00001181 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001182 // there is no compound stmt. C90 does not have this clause. We only do
1183 // this if the body isn't a compound statement to avoid push/pop in common
1184 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001185 //
1186 // C++ 6.4p1:
1187 // The substatement in a selection-statement (each substatement, in the else
1188 // form of the if statement) implicitly defines a local scope.
1189 //
David Majnemer2206bf52014-03-05 08:57:59 +00001190 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001191
Chris Lattner30f910e2006-10-16 05:52:41 +00001192 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001193
Chris Lattner37e54f42007-08-22 05:16:28 +00001194 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001195 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001196 } else if (Tok.is(tok::code_completion)) {
1197 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001198 cutOffParsing();
1199 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001200 } else if (InnerStatementTrailingElseLoc.isValid()) {
1201 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001202 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001203
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001204 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001205
Chris Lattner5c5808a2007-10-29 05:08:52 +00001206 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001207 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001208 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001209 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
Craig Topper161e4db2014-05-21 06:02:52 +00001210 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1211 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001212 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001213 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001214 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001215
Chris Lattner5c5808a2007-10-29 05:08:52 +00001216 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001217 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001218 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001219 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001220 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001221
John McCallb268a282010-08-23 23:25:46 +00001222 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001223 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001224}
1225
Chris Lattner9075bd72006-08-10 04:59:57 +00001226/// ParseSwitchStatement
1227/// switch-statement:
1228/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001229/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001230StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001231 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001232 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001233
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001234 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001235 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001236 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001237 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001238 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001239
David Blaikiebbafb8a2012-03-11 07:00:24 +00001240 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001241
Chris Lattner2dd1b722007-08-26 23:08:06 +00001242 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1243 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001244 //
1245 // C++ 6.4p3:
1246 // A name introduced by a declaration in a condition is in scope from its
1247 // point of declaration until the end of the substatements controlled by the
1248 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001249 // C++ 3.3.2p4:
1250 // Names declared in the for-init-statement, and in the condition of if,
1251 // while, for, and switch statements are local to the if, while, for, or
1252 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001253 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001254 unsigned ScopeFlags = Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001255 if (C99orCXX)
1256 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001257 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001258
Chris Lattner9075bd72006-08-10 04:59:57 +00001259 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001260 ExprResult Cond;
Craig Topper161e4db2014-05-21 06:02:52 +00001261 Decl *CondVar = nullptr;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001262 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001263 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001264
John McCalldadc5752010-08-24 06:29:42 +00001265 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001266 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001267
Douglas Gregore60e41a2010-05-06 17:25:47 +00001268 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001269 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001270 // FIXME: This is not optimal recovery, but parsing the body is more
1271 // dangerous due to the presence of case and default statements, which
1272 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001273 if (Tok.is(tok::l_brace)) {
1274 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001275 SkipUntil(tok::r_brace);
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001276 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001277 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001278 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001279 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001280
Chris Lattner8fb26252007-08-22 05:28:50 +00001281 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001282 // there is no compound stmt. C90 does not have this clause. We only do this
1283 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001284 //
1285 // C++ 6.4p1:
1286 // The substatement in a selection-statement (each substatement, in the else
1287 // form of the if statement) implicitly defines a local scope.
1288 //
1289 // See comments in ParseIfStatement for why we create a scope for the
1290 // condition and a new scope for substatement in C++.
1291 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001292 getCurScope()->AddFlags(Scope::BreakScope);
David Majnemer2206bf52014-03-05 08:57:59 +00001293 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001294
Hans Wennborg852c3462014-06-17 00:09:05 +00001295 // We have incremented the mangling number for the SwitchScope and the
1296 // InnerScope, which is one too many.
1297 if (C99orCXX)
David Majnemera7f8c462015-03-19 21:54:30 +00001298 getCurScope()->decrementMSManglingNumber();
Hans Wennborg852c3462014-06-17 00:09:05 +00001299
Chris Lattner9075bd72006-08-10 04:59:57 +00001300 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001301 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001302
Chris Lattner8fd2d012010-01-24 01:50:29 +00001303 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001304 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001305 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001306
John McCallb268a282010-08-23 23:25:46 +00001307 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001308}
1309
1310/// ParseWhileStatement
1311/// while-statement: [C99 6.8.5.1]
1312/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001313/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001314StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001315 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001316 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001317 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001318
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001319 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001320 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001321 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001322 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001323 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001324
David Blaikiebbafb8a2012-03-11 07:00:24 +00001325 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001326
Chris Lattner2dd1b722007-08-26 23:08:06 +00001327 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1328 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001329 //
1330 // C++ 6.4p3:
1331 // A name introduced by a declaration in a condition is in scope from its
1332 // point of declaration until the end of the substatements controlled by the
1333 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001334 // C++ 3.3.2p4:
1335 // Names declared in the for-init-statement, and in the condition of if,
1336 // while, for, and switch statements are local to the if, while, for, or
1337 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001338 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001339 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001340 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001341 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1342 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001343 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001344 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1345 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001346
Chris Lattner9075bd72006-08-10 04:59:57 +00001347 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001348 ExprResult Cond;
Craig Topper161e4db2014-05-21 06:02:52 +00001349 Decl *CondVar = nullptr;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001350 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001351 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001352
David Blaikiea5696df2012-05-16 04:20:04 +00001353 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001354
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001355 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001356 // there is no compound stmt. C90 does not have this clause. We only do this
1357 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001358 //
1359 // C++ 6.5p2:
1360 // The substatement in an iteration-statement implicitly defines a local scope
1361 // which is entered and exited each time through the loop.
1362 //
1363 // See comments in ParseIfStatement for why we create a scope for the
1364 // condition and a new scope for substatement in C++.
1365 //
David Majnemer2206bf52014-03-05 08:57:59 +00001366 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001367
Chris Lattner9075bd72006-08-10 04:59:57 +00001368 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001369 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001370
Chris Lattner8fb26252007-08-22 05:28:50 +00001371 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001372 InnerScope.Exit();
1373 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001374
John McCall48871652010-08-21 09:40:31 +00001375 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001376 return StmtError();
1377
John McCallb268a282010-08-23 23:25:46 +00001378 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001379}
1380
1381/// ParseDoStatement
1382/// do-statement: [C99 6.8.5.2]
1383/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001384/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001385StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001386 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001387 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001388
Chris Lattner2dd1b722007-08-26 23:08:06 +00001389 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1390 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001391 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001392 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001393 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001394 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001395 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001396
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001397 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001398
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001399 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001400 // there is no compound stmt. C90 does not have this clause. We only do this
1401 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001402 //
1403 // C++ 6.5p2:
1404 // The substatement in an iteration-statement implicitly defines a local scope
1405 // which is entered and exited each time through the loop.
1406 //
David Majnemer2206bf52014-03-05 08:57:59 +00001407 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1408 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001409
Chris Lattner9075bd72006-08-10 04:59:57 +00001410 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001411 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001412
Chris Lattner8fb26252007-08-22 05:28:50 +00001413 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001414 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001415
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001416 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001417 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001418 Diag(Tok, diag::err_expected_while);
Alp Tokerec543272013-12-24 09:48:30 +00001419 Diag(DoLoc, diag::note_matching) << "'do'";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001420 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner0046de12008-11-13 18:52:53 +00001421 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001422 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001423 }
Chris Lattneraf635312006-10-16 06:06:51 +00001424 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001425
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001426 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001427 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Alexey Bataevee6507d2013-11-18 08:17:37 +00001428 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001429 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001430 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001431
Richard Smithc2c8bb82013-10-15 01:34:54 +00001432 // Parse the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001433 BalancedDelimiterTracker T(*this, tok::l_paren);
1434 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001435
Richard Smithc2c8bb82013-10-15 01:34:54 +00001436 // A do-while expression is not a condition, so can't have attributes.
1437 DiagnoseAndSkipCXX11Attributes();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001438
John McCalldadc5752010-08-24 06:29:42 +00001439 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001440 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001441 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001442
Sebastian Redlb62406f2008-12-11 19:48:14 +00001443 if (Cond.isInvalid() || Body.isInvalid())
1444 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001445
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001446 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1447 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001448}
1449
Richard Smith955bf012014-06-19 11:42:00 +00001450bool Parser::isForRangeIdentifier() {
1451 assert(Tok.is(tok::identifier));
1452
1453 const Token &Next = NextToken();
1454 if (Next.is(tok::colon))
1455 return true;
1456
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001457 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
Richard Smith955bf012014-06-19 11:42:00 +00001458 TentativeParsingAction PA(*this);
1459 ConsumeToken();
1460 SkipCXX11Attributes();
1461 bool Result = Tok.is(tok::colon);
1462 PA.Revert();
1463 return Result;
1464 }
1465
1466 return false;
1467}
1468
Chris Lattner9075bd72006-08-10 04:59:57 +00001469/// ParseForStatement
1470/// for-statement: [C99 6.8.5.3]
1471/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1472/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001473/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1474/// [C++] statement
Richard Smith0e304ea2015-10-22 04:46:14 +00001475/// [C++0x] 'for'
1476/// 'co_await'[opt] [Coroutines]
1477/// '(' for-range-declaration ':' for-range-initializer ')'
1478/// statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001479/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1480/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001481///
1482/// [C++] for-init-statement:
1483/// [C++] expression-statement
1484/// [C++] simple-declaration
1485///
Richard Smith02e85f32011-04-14 22:09:26 +00001486/// [C++0x] for-range-declaration:
1487/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1488/// [C++0x] for-range-initializer:
1489/// [C++0x] expression
1490/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001491StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001492 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001493 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001494
Richard Smith0e304ea2015-10-22 04:46:14 +00001495 SourceLocation CoawaitLoc;
1496 if (Tok.is(tok::kw_co_await))
1497 CoawaitLoc = ConsumeToken();
1498
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001499 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001500 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001501 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001502 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001503 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001504
Chad Rosier67055f52012-07-10 21:35:27 +00001505 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1506 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001507
Chris Lattner2dd1b722007-08-26 23:08:06 +00001508 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1509 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001510 //
1511 // C++ 6.4p3:
1512 // A name introduced by a declaration in a condition is in scope from its
1513 // point of declaration until the end of the substatements controlled by the
1514 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001515 // C++ 3.3.2p4:
1516 // Names declared in the for-init-statement, and in the condition of if,
1517 // while, for, and switch statements are local to the if, while, for, or
1518 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001519 // C++ 6.5.3p1:
1520 // Names declared in the for-init-statement are in the same declarative-region
1521 // as those declared in the condition.
1522 //
Serge Pavlov09f99242014-01-23 15:05:00 +00001523 unsigned ScopeFlags = 0;
Chris Lattner934074c2009-04-22 00:54:41 +00001524 if (C99orCXXorObjC)
Serge Pavlov09f99242014-01-23 15:05:00 +00001525 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001526
1527 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001528
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001529 BalancedDelimiterTracker T(*this, tok::l_paren);
1530 T.consumeOpen();
1531
John McCalldadc5752010-08-24 06:29:42 +00001532 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001533
Richard Smith02e85f32011-04-14 22:09:26 +00001534 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001535 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001536 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001537 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001538 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001539 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001540 FullExprArg ThirdPart(Actions);
Craig Topper161e4db2014-05-21 06:02:52 +00001541 Decl *SecondVar = nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001542
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001543 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001544 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001545 C99orCXXorObjC? Sema::PCC_ForInit
1546 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001547 cutOffParsing();
1548 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001549 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001550
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001551 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001552 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001553
Chris Lattner9075bd72006-08-10 04:59:57 +00001554 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001555 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001556 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001557 // no first part, eat the ';'.
1558 ConsumeToken();
Richard Smith955bf012014-06-19 11:42:00 +00001559 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1560 isForRangeIdentifier()) {
1561 ProhibitAttributes(attrs);
1562 IdentifierInfo *Name = Tok.getIdentifierInfo();
1563 SourceLocation Loc = ConsumeToken();
1564 MaybeParseCXX11Attributes(attrs);
1565
1566 ForRangeInit.ColonLoc = ConsumeToken();
1567 if (Tok.is(tok::l_brace))
1568 ForRangeInit.RangeExpr = ParseBraceInitializer();
1569 else
1570 ForRangeInit.RangeExpr = ParseExpression();
1571
Richard Smith83d3f152014-11-27 01:54:27 +00001572 Diag(Loc, diag::err_for_range_identifier)
Richard Smith955bf012014-06-19 11:42:00 +00001573 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1574 ? FixItHint::CreateInsertion(Loc, "auto &&")
1575 : FixItHint());
1576
1577 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1578 attrs, attrs.Range.getEnd());
1579 ForRange = true;
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001580 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001581 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001582 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001583 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001584
Richard Smith02e85f32011-04-14 22:09:26 +00001585 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001586 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001587 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1588
Chris Lattner49836b42009-04-02 04:16:50 +00001589 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00001590 DeclGroupPtrTy DG = ParseSimpleDeclaration(
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001591 Declarator::ForContext, DeclEnd, attrs, false,
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00001592 MightBeForRangeStmt ? &ForRangeInit : nullptr);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001593 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Richard Smith02e85f32011-04-14 22:09:26 +00001594 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001595 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001596 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001597
Richard Smith02e85f32011-04-14 22:09:26 +00001598 ForRange = true;
1599 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001600 ConsumeToken();
1601 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001602 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001603 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001604 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001605
Douglas Gregor68762e72010-08-23 21:17:50 +00001606 if (Tok.is(tok::code_completion)) {
1607 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001608 cutOffParsing();
1609 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001610 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001611 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001612 } else {
1613 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001614 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001615 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001616 ProhibitAttributes(attrs);
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001617 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
Chris Lattner71e23ce2006-11-04 20:18:38 +00001618
John McCall34376a62010-12-04 03:47:34 +00001619 ForEach = isTokIdentifier_in();
1620
Chris Lattnercd68f642007-06-27 01:06:29 +00001621 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001622 if (!Value.isInvalid()) {
1623 if (ForEach)
1624 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1625 else
Richard Smith945f8d32013-01-14 22:39:08 +00001626 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001627 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001628
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001629 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001630 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001631 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001632 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001633
Douglas Gregor68762e72010-08-23 21:17:50 +00001634 if (Tok.is(tok::code_completion)) {
1635 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001636 cutOffParsing();
1637 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001638 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001639 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001640 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001641 // User tried to write the reasonable, but ill-formed, for-range-statement
1642 // for (expr : expr) { ... }
1643 Diag(Tok, diag::err_for_range_expected_decl)
1644 << FirstPart.get()->getSourceRange();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001645 SkipUntil(tok::r_paren, StopBeforeMatch);
Richard Smith4f848f12011-12-20 22:56:20 +00001646 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001647 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001648 if (!Value.isInvalid()) {
1649 Diag(Tok, diag::err_expected_semi_for);
1650 } else {
1651 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001652 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001653 if (Tok.is(tok::semi))
1654 ConsumeToken();
1655 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001656 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001657 }
Serge Pavlov09f99242014-01-23 15:05:00 +00001658
1659 // Parse the second part of the for specifier.
1660 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
Richard Smith02e85f32011-04-14 22:09:26 +00001661 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001662 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001663 // Parse the second part of the for specifier.
1664 if (Tok.is(tok::semi)) { // for (...;;
1665 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001666 } else if (Tok.is(tok::r_paren)) {
1667 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001668 } else {
John McCalldadc5752010-08-24 06:29:42 +00001669 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001670 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001671 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1672 else {
1673 Second = ParseExpression();
1674 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001675 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001676 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001677 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001678 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001679 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001680 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001681
Douglas Gregor230a7e62011-02-17 03:38:46 +00001682 if (Tok.isNot(tok::semi)) {
1683 if (!SecondPartIsInvalid || SecondVar)
1684 Diag(Tok, diag::err_expected_semi_for);
1685 else
1686 // Skip until semicolon or rparen, don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001687 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor230a7e62011-02-17 03:38:46 +00001688 }
1689
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001690 if (Tok.is(tok::semi)) {
1691 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001692 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001693
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001694 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001695 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001696 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001697 // FIXME: The C++11 standard doesn't actually say that this is a
1698 // discarded-value expression, but it clearly should be.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001699 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001700 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001701 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001702 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001703 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001704
Richard Smith0e304ea2015-10-22 04:46:14 +00001705 // C++ Coroutines [stmt.iter]:
1706 // 'co_await' can only be used for a range-based for statement.
1707 if (CoawaitLoc.isValid() && !ForRange) {
1708 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1709 CoawaitLoc = SourceLocation();
1710 }
1711
Richard Smith02e85f32011-04-14 22:09:26 +00001712 // We need to perform most of the semantic analysis for a C++0x for-range
1713 // statememt before parsing the body, in order to be able to deduce the type
1714 // of an auto-typed loop variable.
1715 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001716 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001717
John McCall53848232011-07-27 01:07:15 +00001718 if (ForRange) {
Richard Smith9f690bd2015-10-27 06:02:45 +00001719 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1720 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1721 ForRangeInit.ColonLoc, ForRangeInit.RangeExpr.get(),
1722 T.getCloseLocation(), Sema::BFRK_Build);
John McCall53848232011-07-27 01:07:15 +00001723
1724 // Similarly, we need to do the semantic analysis for a for-range
1725 // statement immediately in order to close over temporaries correctly.
1726 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001727 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001728 FirstPart.get(),
1729 Collection.get(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001730 T.getCloseLocation());
Alexey Bataev9c821032015-04-30 04:23:23 +00001731 } else {
1732 // In OpenMP loop region loop control variable must be captured and be
1733 // private. Perform analysis of first part (if any).
1734 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1735 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1736 }
John McCall53848232011-07-27 01:07:15 +00001737 }
1738
Justin Bognere4ebb6c2013-12-03 07:36:55 +00001739 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001740 // there is no compound stmt. C90 does not have this clause. We only do this
1741 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001742 //
1743 // C++ 6.5p2:
1744 // The substatement in an iteration-statement implicitly defines a local scope
1745 // which is entered and exited each time through the loop.
1746 //
1747 // See comments in ParseIfStatement for why we create a scope for
1748 // for-init-statement/condition and a new scope for substatement in C++.
1749 //
David Majnemer2206bf52014-03-05 08:57:59 +00001750 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1751 Tok.is(tok::l_brace));
1752
1753 // The body of the for loop has the same local mangling number as the
1754 // for-init-statement.
1755 // It will only be incremented if the body contains other things that would
1756 // normally increment the mangling number (like a compound statement).
1757 if (C99orCXXorObjC)
David Majnemera7f8c462015-03-19 21:54:30 +00001758 getCurScope()->decrementMSManglingNumber();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001759
Chris Lattner9075bd72006-08-10 04:59:57 +00001760 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001761 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001762
Chris Lattner8fb26252007-08-22 05:28:50 +00001763 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001764 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001765
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001766 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001767 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001768
1769 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001770 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001771
Richard Smith02e85f32011-04-14 22:09:26 +00001772 if (ForEach)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001773 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1774 Body.get());
Mike Stump11289f42009-09-09 15:08:12 +00001775
Richard Smith02e85f32011-04-14 22:09:26 +00001776 if (ForRange)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001777 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001778
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001779 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001780 SecondPart, SecondVar, ThirdPart,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001781 T.getCloseLocation(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001782}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001783
Chris Lattner503fadc2006-08-10 05:45:44 +00001784/// ParseGotoStatement
1785/// jump-statement:
1786/// 'goto' identifier ';'
1787/// [GNU] 'goto' '*' expression ';'
1788///
1789/// Note: this lets the caller parse the end ';'.
1790///
Richard Smithc202b282012-04-14 00:33:13 +00001791StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001792 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001793 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001794
John McCalldadc5752010-08-24 06:29:42 +00001795 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001796 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001797 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1798 Tok.getLocation());
1799 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001800 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001801 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001802 // GNU indirect goto extension.
1803 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001804 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001805 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001806 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001807 SkipUntil(tok::semi, StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001808 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001809 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001810 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001811 } else {
Alp Tokerec543272013-12-24 09:48:30 +00001812 Diag(Tok, diag::err_expected) << tok::identifier;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001813 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001814 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001815
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001816 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001817}
1818
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001819/// ParseContinueStatement
1820/// jump-statement:
1821/// 'continue' ';'
1822///
1823/// Note: this lets the caller parse the end ';'.
1824///
Richard Smithc202b282012-04-14 00:33:13 +00001825StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001826 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001827 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001828}
1829
1830/// ParseBreakStatement
1831/// jump-statement:
1832/// 'break' ';'
1833///
1834/// Note: this lets the caller parse the end ';'.
1835///
Richard Smithc202b282012-04-14 00:33:13 +00001836StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001837 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001838 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001839}
1840
Chris Lattner503fadc2006-08-10 05:45:44 +00001841/// ParseReturnStatement
1842/// jump-statement:
1843/// 'return' expression[opt] ';'
Richard Smith0e304ea2015-10-22 04:46:14 +00001844/// 'return' braced-init-list ';'
1845/// 'co_return' expression[opt] ';'
1846/// 'co_return' braced-init-list ';'
Richard Smithc202b282012-04-14 00:33:13 +00001847StmtResult Parser::ParseReturnStatement() {
Richard Smith0e304ea2015-10-22 04:46:14 +00001848 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1849 "Not a return stmt!");
1850 bool IsCoreturn = Tok.is(tok::kw_co_return);
Chris Lattneraf635312006-10-16 06:06:51 +00001851 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001852
John McCalldadc5752010-08-24 06:29:42 +00001853 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001854 if (Tok.isNot(tok::semi)) {
Richard Smith0e304ea2015-10-22 04:46:14 +00001855 // FIXME: Code completion for co_return.
1856 if (Tok.is(tok::code_completion) && !IsCoreturn) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001857 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001858 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001859 return StmtError();
1860 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001861
David Blaikiebbafb8a2012-03-11 07:00:24 +00001862 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001863 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001864 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001865 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001866 diag::warn_cxx98_compat_generalized_initializer_lists :
1867 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001868 << R.get()->getSourceRange();
1869 } else
Nico Weber3ce01c32015-01-04 08:07:54 +00001870 R = ParseExpression();
Serge Pavlovf79bd5c2013-12-04 03:51:59 +00001871 if (R.isInvalid()) {
1872 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001873 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001874 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001875 }
Richard Smithcfd53b42015-10-22 06:13:50 +00001876 if (IsCoreturn)
1877 return Actions.ActOnCoreturnStmt(ReturnLoc, R.get());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001878 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
Chris Lattner503fadc2006-08-10 05:45:44 +00001879}
Chris Lattner0116c472006-08-15 06:03:28 +00001880
Alexey Bataevc4fad652016-01-13 11:18:54 +00001881StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1882 AllowedContsructsKind Allowed,
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001883 SourceLocation *TrailingElseLoc,
1884 ParsedAttributesWithRange &Attrs) {
1885 // Create temporary attribute list.
1886 ParsedAttributesWithRange TempAttrs(AttrFactory);
1887
Mark Heffernanbd26f5e2014-07-21 18:08:34 +00001888 // Get loop hints and consume annotated token.
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001889 while (Tok.is(tok::annot_pragma_loop_hint)) {
Tyler Nowicki0c9b34b2014-07-31 20:15:14 +00001890 LoopHint Hint;
1891 if (!HandlePragmaLoopHint(Hint))
1892 continue;
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001893
Tyler Nowicki0c9b34b2014-07-31 20:15:14 +00001894 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001895 ArgsUnion(Hint.ValueExpr)};
Mark Heffernanbd26f5e2014-07-21 18:08:34 +00001896 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1897 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1898 AttributeList::AS_Pragma);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001899 }
1900
1901 // Get the next statement.
1902 MaybeParseCXX11Attributes(Attrs);
1903
1904 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
Alexey Bataevc4fad652016-01-13 11:18:54 +00001905 Stmts, Allowed, TrailingElseLoc, Attrs);
Aaron Ballmanb06b15a2014-06-06 12:40:24 +00001906
1907 Attrs.takeAllFrom(TempAttrs);
1908 return S;
1909}
1910
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001911Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00001912 assert(Tok.is(tok::l_brace));
1913 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001914
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00001915 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00001916 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00001917 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00001918 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001919 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001920
John McCallfaf5fb42010-08-26 23:41:50 +00001921 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1922 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00001923
Alexey Bataev3d42f342015-11-20 07:02:57 +00001924 // Save and reset current vtordisp stack if we have entered a C++ method body.
1925 bool IsCXXMethod =
1926 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1927 Sema::VtorDispStackRAII SavedVtorDispStack(Actions, IsCXXMethod);
1928
Fariborz Jahanian8e632942007-11-08 19:01:26 +00001929 // Do not enter a scope for the brace, as the arguments are in the same scope
1930 // (the function body) as the body itself. Instead, just read the statement
1931 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00001932 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00001933
Fariborz Jahanian8e632942007-11-08 19:01:26 +00001934 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001935 if (FnBody.isInvalid()) {
1936 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00001937 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001938 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001939
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001940 BodyScope.Exit();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001941 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00001942}
Sebastian Redlb219c902008-12-21 16:41:36 +00001943
Sebastian Redla7b98a72009-04-26 20:35:05 +00001944/// ParseFunctionTryBlock - Parse a C++ function-try-block.
1945///
1946/// function-try-block:
1947/// 'try' ctor-initializer[opt] compound-statement handler-seq
1948///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001949Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00001950 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1951 SourceLocation TryLoc = ConsumeToken();
1952
John McCallfaf5fb42010-08-26 23:41:50 +00001953 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1954 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00001955
1956 // Constructor initializer list?
1957 if (Tok.is(tok::colon))
1958 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00001959 else
1960 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001961
Richard Smith1ab34b32012-11-19 21:13:18 +00001962 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
1963 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00001964 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00001965 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001966 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001967
Alexey Bataev3d42f342015-11-20 07:02:57 +00001968 // Save and reset current vtordisp stack if we have entered a C++ method body.
1969 bool IsCXXMethod =
1970 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1971 Sema::VtorDispStackRAII SavedVtorDispStack(Actions, IsCXXMethod);
1972
Sebastian Redld98ecd62009-04-26 21:08:36 +00001973 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00001974 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00001975 // If we failed to parse the try-catch, we just give the function an empty
1976 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001977 if (FnBody.isInvalid()) {
1978 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00001979 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001980 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00001981
Douglas Gregora0ff0c32011-03-16 17:05:57 +00001982 BodyScope.Exit();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001983 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
Sebastian Redla7b98a72009-04-26 20:35:05 +00001984}
1985
Erik Verbruggen6e922512012-04-12 10:11:59 +00001986bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001987 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00001988 assert(SkipFunctionBodies &&
1989 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001990
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00001991 if (!PP.isCodeCompletionEnabled()) {
1992 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001993 SkipUntil(tok::r_brace);
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00001994 return true;
1995 }
1996
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00001997 // We're in code-completion mode. Skip parsing for all function bodies unless
1998 // the body contains the code-completion point.
1999 TentativeParsingAction PA(*this);
2000 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002001 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002002 PA.Commit();
2003 return true;
2004 }
2005
2006 PA.Revert();
2007 return false;
2008}
2009
Sebastian Redlb219c902008-12-21 16:41:36 +00002010/// ParseCXXTryBlock - Parse a C++ try-block.
2011///
2012/// try-block:
2013/// 'try' compound-statement handler-seq
2014///
Richard Smithc202b282012-04-14 00:33:13 +00002015StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002016 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2017
2018 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002019 return ParseCXXTryBlockCommon(TryLoc);
2020}
2021
2022/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2023/// function-try-block.
2024///
2025/// try-block:
2026/// 'try' compound-statement handler-seq
2027///
2028/// function-try-block:
2029/// 'try' ctor-initializer[opt] compound-statement handler-seq
2030///
2031/// handler-seq:
2032/// handler handler-seq[opt]
2033///
John Wiegley1c0675e2011-04-28 01:08:34 +00002034/// [Borland] try-block:
2035/// 'try' compound-statement seh-except-block
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002036/// 'try' compound-statement seh-finally-block
John Wiegley1c0675e2011-04-28 01:08:34 +00002037///
David Blaikie1c9c9042012-11-10 01:04:23 +00002038StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002039 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002040 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Richard Smithc202b282012-04-14 00:33:13 +00002041
Warren Huntf6be4cb2014-07-25 20:52:51 +00002042 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2043 Scope::DeclScope | Scope::TryScope |
2044 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002045 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002046 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002047
John Wiegley1c0675e2011-04-28 01:08:34 +00002048 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002049
Richard Smithc202b282012-04-14 00:33:13 +00002050 if ((Tok.is(tok::identifier) &&
2051 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2052 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002053 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2054 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002055 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002056 SourceLocation Loc = ConsumeToken();
2057 Handler = ParseSEHExceptBlock(Loc);
2058 }
2059 else {
2060 SourceLocation Loc = ConsumeToken();
2061 Handler = ParseSEHFinallyBlock(Loc);
2062 }
2063 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002064 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002065
John Wiegley1c0675e2011-04-28 01:08:34 +00002066 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2067 TryLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002068 TryBlock.get(),
Warren Huntf6be4cb2014-07-25 20:52:51 +00002069 Handler.get());
Sebastian Redlb219c902008-12-21 16:41:36 +00002070 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002071 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002072 StmtVector Handlers;
Richard Smithc2c8bb82013-10-15 01:34:54 +00002073
2074 // C++11 attributes can't appear here, despite this context seeming
2075 // statement-like.
2076 DiagnoseAndSkipCXX11Attributes();
Sebastian Redlb219c902008-12-21 16:41:36 +00002077
John Wiegley1c0675e2011-04-28 01:08:34 +00002078 if (Tok.isNot(tok::kw_catch))
2079 return StmtError(Diag(Tok, diag::err_expected_catch));
2080 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002081 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002082 if (!Handler.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002083 Handlers.push_back(Handler.get());
John Wiegley1c0675e2011-04-28 01:08:34 +00002084 }
2085 // Don't bother creating the full statement if we don't have any usable
2086 // handlers.
2087 if (Handlers.empty())
2088 return StmtError();
2089
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002090 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002091 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002092}
2093
2094/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2095///
Richard Smith1dba27c2013-01-29 09:02:09 +00002096/// handler:
2097/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002098///
Richard Smith1dba27c2013-01-29 09:02:09 +00002099/// exception-declaration:
2100/// attribute-specifier-seq[opt] type-specifier-seq declarator
2101/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2102/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002103///
David Blaikie1c9c9042012-11-10 01:04:23 +00002104StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002105 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2106
2107 SourceLocation CatchLoc = ConsumeToken();
2108
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002109 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002110 if (T.expectAndConsume())
Sebastian Redlb219c902008-12-21 16:41:36 +00002111 return StmtError();
2112
2113 // C++ 3.3.2p3:
2114 // The name in a catch exception-declaration is local to the handler and
2115 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002116 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002117 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002118
2119 // exception-declaration is equivalent to '...' or a parameter-declaration
2120 // without default arguments.
Craig Topper161e4db2014-05-21 06:02:52 +00002121 Decl *ExceptionDecl = nullptr;
Sebastian Redlb219c902008-12-21 16:41:36 +00002122 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002123 ParsedAttributesWithRange Attributes(AttrFactory);
2124 MaybeParseCXX11Attributes(Attributes);
2125
John McCall084e83d2011-03-24 11:26:52 +00002126 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002127 DS.takeAttributesFrom(Attributes);
2128
Sebastian Redl54c04d42008-12-22 19:15:10 +00002129 if (ParseCXXTypeSpecifierSeq(DS))
2130 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002131
Sebastian Redlb219c902008-12-21 16:41:36 +00002132 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2133 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002134 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002135 } else
2136 ConsumeToken();
2137
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002138 T.consumeClose();
2139 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002140 return StmtError();
2141
2142 if (Tok.isNot(tok::l_brace))
Alp Tokerec543272013-12-24 09:48:30 +00002143 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
Sebastian Redlb219c902008-12-21 16:41:36 +00002144
Alexis Hunt96d5c762009-11-21 08:43:09 +00002145 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002146 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002147 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002148 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002149
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002150 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
Sebastian Redlb219c902008-12-21 16:41:36 +00002151}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002152
2153void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002154 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002155 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002156 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002157
Douglas Gregor43edb322011-10-24 22:31:10 +00002158 // Handle dependent statements by parsing the braces as a compound statement.
2159 // This is not the same behavior as Visual C++, which don't treat this as a
2160 // compound statement, but for Clang's type checking we can't have anything
2161 // inside these braces escaping to the surrounding code.
2162 if (Result.Behavior == IEB_Dependent) {
2163 if (!Tok.is(tok::l_brace)) {
Alp Tokerec543272013-12-24 09:48:30 +00002164 Diag(Tok, diag::err_expected) << tok::l_brace;
Richard Smithc202b282012-04-14 00:33:13 +00002165 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002166 }
Richard Smithc202b282012-04-14 00:33:13 +00002167
2168 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002169 if (Compound.isInvalid())
2170 return;
Richard Smithc202b282012-04-14 00:33:13 +00002171
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002172 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2173 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002174 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002175 Result.Name,
2176 Compound.get());
2177 if (DepResult.isUsable())
2178 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002179 return;
2180 }
Richard Smithc202b282012-04-14 00:33:13 +00002181
Douglas Gregor43edb322011-10-24 22:31:10 +00002182 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2183 if (Braces.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00002184 Diag(Tok, diag::err_expected) << tok::l_brace;
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002185 return;
2186 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002187
Douglas Gregor43edb322011-10-24 22:31:10 +00002188 switch (Result.Behavior) {
2189 case IEB_Parse:
2190 // Parse the statements below.
2191 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002192
Douglas Gregor43edb322011-10-24 22:31:10 +00002193 case IEB_Dependent:
2194 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002195
Douglas Gregor43edb322011-10-24 22:31:10 +00002196 case IEB_Skip:
2197 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002198 return;
2199 }
2200
2201 // Condition is true, parse the statements.
2202 while (Tok.isNot(tok::r_brace)) {
Alexey Bataevc4fad652016-01-13 11:18:54 +00002203 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002204 if (R.isUsable())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002205 Stmts.push_back(R.get());
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002206 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002207 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002208}