blob: 63fd1a51e49411e738ea65e01337a4813eea85f7 [file] [log] [blame]
Chris Lattner7ad0fbe2006-11-05 07:46:30 +00001//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
Chris Lattner0ccd51e2006-08-09 05:47:47 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner0ccd51e2006-08-09 05:47:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Statement and Block portions of the Parser
11// interface.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Parse/Parser.h"
Chris Lattner8a9a97a2009-12-10 00:21:05 +000016#include "RAIIObjectsForParser.h"
John McCallf413f5e2013-05-03 00:10:13 +000017#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/PrettyStackTrace.h"
20#include "clang/Basic/SourceManager.h"
John McCallf413f5e2013-05-03 00:10:13 +000021#include "clang/Basic/TargetInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
John McCallfaf5fb42010-08-26 23:41:50 +000023#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/Scope.h"
Richard Smith4f605af2012-08-18 00:55:03 +000025#include "clang/Sema/TypoCorrection.h"
John McCallf413f5e2013-05-03 00:10:13 +000026#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCObjectFileInfo.h"
29#include "llvm/MC/MCParser/MCAsmParser.h"
30#include "llvm/MC/MCRegisterInfo.h"
31#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSubtargetInfo.h"
33#include "llvm/MC/MCTargetAsmParser.h"
34#include "llvm/Support/SourceMgr.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
Chad Rosier32503022012-06-11 20:47:18 +000037#include "llvm/ADT/SmallString.h"
Chris Lattner0ccd51e2006-08-09 05:47:47 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// C99 6.8: Statements and Blocks.
42//===----------------------------------------------------------------------===//
43
44/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
45/// StatementOrDeclaration:
46/// statement
47/// declaration
48///
49/// statement:
50/// labeled-statement
51/// compound-statement
52/// expression-statement
53/// selection-statement
54/// iteration-statement
55/// jump-statement
Argyrios Kyrtzidisdee82912008-09-07 18:58:01 +000056/// [C++] declaration-statement
Sebastian Redlb219c902008-12-21 16:41:36 +000057/// [C++] try-block
John Wiegley1c0675e2011-04-28 01:08:34 +000058/// [MS] seh-try-block
Fariborz Jahanian90814572007-10-04 20:19:06 +000059/// [OBC] objc-throw-statement
60/// [OBC] objc-try-catch-statement
Fariborz Jahanianf89ca382008-01-29 18:21:32 +000061/// [OBC] objc-synchronized-statement
Chris Lattner0116c472006-08-15 06:03:28 +000062/// [GNU] asm-statement
Chris Lattner0ccd51e2006-08-09 05:47:47 +000063/// [OMP] openmp-construct [TODO]
64///
65/// labeled-statement:
66/// identifier ':' statement
67/// 'case' constant-expression ':' statement
68/// 'default' ':' statement
69///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000070/// selection-statement:
71/// if-statement
72/// switch-statement
73///
74/// iteration-statement:
75/// while-statement
76/// do-statement
77/// for-statement
78///
Chris Lattner9075bd72006-08-10 04:59:57 +000079/// expression-statement:
80/// expression[opt] ';'
81///
Chris Lattner0ccd51e2006-08-09 05:47:47 +000082/// jump-statement:
83/// 'goto' identifier ';'
84/// 'continue' ';'
85/// 'break' ';'
86/// 'return' expression[opt] ';'
Chris Lattner503fadc2006-08-10 05:45:44 +000087/// [GNU] 'goto' '*' expression ';'
Chris Lattner0ccd51e2006-08-09 05:47:47 +000088///
Fariborz Jahanian90814572007-10-04 20:19:06 +000089/// [OBC] objc-throw-statement:
90/// [OBC] '@' 'throw' expression ';'
Mike Stump11289f42009-09-09 15:08:12 +000091/// [OBC] '@' 'throw' ';'
92///
John McCalldadc5752010-08-24 06:29:42 +000093StmtResult
Nico Weber3cef1082011-12-22 23:26:17 +000094Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
95 SourceLocation *TrailingElseLoc) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000096
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +000097 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +000098
Richard Smithc202b282012-04-14 00:33:13 +000099 ParsedAttributesWithRange Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000100 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
Richard Smithc202b282012-04-14 00:33:13 +0000101
102 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
103 OnlyStatement, TrailingElseLoc, Attrs);
104
105 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
106 "attributes on empty statement");
107
108 if (Attrs.empty() || Res.isInvalid())
109 return Res;
110
111 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
112}
113
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000114namespace {
115class StatementFilterCCC : public CorrectionCandidateCallback {
116public:
117 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
118 WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) ||
119 nextTok.is(tok::identifier) || nextTok.is(tok::star) ||
120 nextTok.is(tok::amp) || nextTok.is(tok::l_square);
121 WantExpressionKeywords = nextTok.is(tok::l_paren) ||
122 nextTok.is(tok::identifier) ||
123 nextTok.is(tok::arrow) || nextTok.is(tok::period);
124 WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) ||
125 nextTok.is(tok::identifier) ||
126 nextTok.is(tok::l_brace);
127 WantCXXNamedCasts = false;
128 }
129
130 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
131 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
132 return isa<ObjCIvarDecl>(FD);
133 return CorrectionCandidateCallback::ValidateCandidate(candidate);
134 }
135
136private:
137 Token NextToken;
138};
139}
140
Richard Smithc202b282012-04-14 00:33:13 +0000141StmtResult
142Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
143 bool OnlyStatement, SourceLocation *TrailingElseLoc,
144 ParsedAttributesWithRange &Attrs) {
145 const char *SemiError = 0;
146 StmtResult Res;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000147
Chris Lattner503fadc2006-08-10 05:45:44 +0000148 // Cases in this switch statement should fall through if the parser expects
149 // the token to end in a semicolon (in which case SemiError should be set),
150 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000151Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000152 tok::TokenKind Kind = Tok.getKind();
153 SourceLocation AtLoc;
154 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000155 case tok::at: // May be a @try or @throw statement
156 {
Richard Smithc202b282012-04-14 00:33:13 +0000157 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000158 AtLoc = ConsumeToken(); // consume @
Sebastian Redlbab9a4b2008-12-11 20:12:42 +0000159 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000160 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000161
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000162 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000163 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000164 cutOffParsing();
165 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000166
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000167 case tok::identifier: {
168 Token Next = NextToken();
169 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000170 // identifier ':' statement
Richard Smithc202b282012-04-14 00:33:13 +0000171 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000172 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000173
Richard Smith4f605af2012-08-18 00:55:03 +0000174 // Look up the identifier, and typo-correct it to a keyword if it's not
175 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000176 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000177 // Try to limit which sets of keywords should be included in typo
178 // correction based on what the next token is.
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000179 StatementFilterCCC Validator(Next);
180 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
Richard Smith4f605af2012-08-18 00:55:03 +0000181 == ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000182 // Handle errors here by skipping up to the next semicolon or '}', and
183 // eat the semicolon if that's what stopped us.
184 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
185 if (Tok.is(tok::semi))
186 ConsumeToken();
187 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000188 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000189
Richard Smith4f605af2012-08-18 00:55:03 +0000190 // If the identifier was typo-corrected, try again.
191 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000192 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000193 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000194
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000195 // Fall through
196 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000197
Chris Lattner803802d2009-03-24 17:04:48 +0000198 default: {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000199 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000200 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek5eec2b02010-11-10 05:59:39 +0000201 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000202 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000203 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000204 }
205
206 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000207 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000208 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000209 }
Mike Stump11289f42009-09-09 15:08:12 +0000210
Richard Smithc202b282012-04-14 00:33:13 +0000211 return ParseExprStatement();
Chris Lattner803802d2009-03-24 17:04:48 +0000212 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000213
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000214 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000215 return ParseCaseStatement();
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000216 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000217 return ParseDefaultStatement();
Sebastian Redl042ad952008-12-11 19:30:53 +0000218
Chris Lattner9075bd72006-08-10 04:59:57 +0000219 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000220 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000221 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000222 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
223 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000224 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000225
Chris Lattner9075bd72006-08-10 04:59:57 +0000226 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000227 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000228 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000229 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000230
Chris Lattner9075bd72006-08-10 04:59:57 +0000231 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000232 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000233 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000234 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000235 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000236 break;
237 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000238 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000239
240 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000241 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000242 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000243 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000244 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000245 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000246 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000247 break;
248 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000249 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000250 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000251 break;
252 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000253 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000254 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000255 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000256
Sebastian Redlb219c902008-12-21 16:41:36 +0000257 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000258 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000259 bool msAsm = false;
260 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000261 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000262 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000263 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000264 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000265 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000266
Sebastian Redlb219c902008-12-21 16:41:36 +0000267 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000268 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000269
270 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000271 ProhibitAttributes(Attrs); // TODO: is it correct?
272 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000273
274 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000275 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000276 HandlePragmaVisibility();
277 return StmtEmpty();
278
279 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000280 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000281 HandlePragmaPack();
282 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000283
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000284 case tok::annot_pragma_msstruct:
285 ProhibitAttributes(Attrs);
286 HandlePragmaMSStruct();
287 return StmtEmpty();
288
Eli Friedmanae8ee252012-10-08 23:52:38 +0000289 case tok::annot_pragma_align:
290 ProhibitAttributes(Attrs);
291 HandlePragmaAlign();
292 return StmtEmpty();
293
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000294 case tok::annot_pragma_weak:
295 ProhibitAttributes(Attrs);
296 HandlePragmaWeak();
297 return StmtEmpty();
298
299 case tok::annot_pragma_weakalias:
300 ProhibitAttributes(Attrs);
301 HandlePragmaWeakAlias();
302 return StmtEmpty();
303
304 case tok::annot_pragma_redefine_extname:
305 ProhibitAttributes(Attrs);
306 HandlePragmaRedefineExtname();
307 return StmtEmpty();
308
Eli Friedman68be1642012-10-04 02:36:51 +0000309 case tok::annot_pragma_fp_contract:
Lang Hamesa930e712012-10-21 01:10:01 +0000310 Diag(Tok, diag::err_pragma_fp_contract_scope);
311 ConsumeToken();
312 return StmtError();
313
Eli Friedman68be1642012-10-04 02:36:51 +0000314 case tok::annot_pragma_opencl_extension:
315 ProhibitAttributes(Attrs);
316 HandlePragmaOpenCLExtension();
317 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000318
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000319 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000320 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000321 return HandlePragmaCaptured();
322
Alexey Bataeva769e072013-03-22 06:34:35 +0000323 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000324 ProhibitAttributes(Attrs);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000325 return ParseOpenMPDeclarativeOrExecutableDirective();
326
Sebastian Redlb219c902008-12-21 16:41:36 +0000327 }
328
Chris Lattner503fadc2006-08-10 05:45:44 +0000329 // If we reached this code, the statement must end in a semicolon.
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000330 if (Tok.is(tok::semi)) {
Chris Lattner503fadc2006-08-10 05:45:44 +0000331 ConsumeToken();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000332 } else if (!Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000333 // If the result was valid, then we do want to diagnose this. Use
334 // ExpectAndConsume to emit the diagnostic, even though we know it won't
335 // succeed.
336 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000337 // Skip until we see a } or ;, but don't eat it.
338 SkipUntil(tok::r_brace, true, true);
Chris Lattner503fadc2006-08-10 05:45:44 +0000339 }
Mike Stump11289f42009-09-09 15:08:12 +0000340
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000341 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000342}
343
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000344/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000345StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000346 // If a case keyword is missing, this is where it should be inserted.
347 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000348
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000349 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000350 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000351 if (Expr.isInvalid()) {
352 // If the expression is invalid, skip ahead to the next semicolon or '}'.
353 // Not doing this opens us up to the possibility of infinite loops if
354 // ParseExpression does not consume any tokens.
355 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
356 if (Tok.is(tok::semi))
357 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000358 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000359 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000360
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000361 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
362 Actions.CheckCaseExpression(Expr.get())) {
363 // If a constant expression is followed by a colon inside a switch block,
364 // suggest a missing case keyword.
365 Diag(OldToken, diag::err_expected_case_before_expression)
366 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000367
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000368 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000369 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000370 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000371
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000372 // Otherwise, eat the semicolon.
373 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000374 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000375}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000376
Richard Smithc202b282012-04-14 00:33:13 +0000377StmtResult Parser::ParseSEHTryBlock() {
John Wiegley1c0675e2011-04-28 01:08:34 +0000378 assert(Tok.is(tok::kw___try) && "Expected '__try'");
379 SourceLocation Loc = ConsumeToken();
380 return ParseSEHTryBlockCommon(Loc);
381}
382
383/// ParseSEHTryBlockCommon
384///
385/// seh-try-block:
386/// '__try' compound-statement seh-handler
387///
388/// seh-handler:
389/// seh-except-block
390/// seh-finally-block
391///
392StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
393 if(Tok.isNot(tok::l_brace))
394 return StmtError(Diag(Tok,diag::err_expected_lbrace));
395
Joao Matos566359c2012-09-04 17:49:35 +0000396 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000397 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000398 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000399
400 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000401 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000402 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000403 SourceLocation Loc = ConsumeToken();
404 Handler = ParseSEHExceptBlock(Loc);
405 } else if (Tok.is(tok::kw___finally)) {
406 SourceLocation Loc = ConsumeToken();
407 Handler = ParseSEHFinallyBlock(Loc);
408 } else {
409 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
410 }
411
412 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000413 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000414
415 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
416 TryLoc,
417 TryBlock.take(),
418 Handler.take());
419}
420
421/// ParseSEHExceptBlock - Handle __except
422///
423/// seh-except-block:
424/// '__except' '(' seh-filter-expression ')' compound-statement
425///
426StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
427 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
428 raii2(Ident___exception_code, false),
429 raii3(Ident_GetExceptionCode, false);
430
431 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
432 return StmtError();
433
434 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
435
David Blaikiebbafb8a2012-03-11 07:00:24 +0000436 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000437 Ident__exception_info->setIsPoisoned(false);
438 Ident___exception_info->setIsPoisoned(false);
439 Ident_GetExceptionInfo->setIsPoisoned(false);
440 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000441 ExprResult FilterExpr(ParseExpression());
Francois Pichetbfaf4772011-04-28 03:14:31 +0000442
David Blaikiebbafb8a2012-03-11 07:00:24 +0000443 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000444 Ident__exception_info->setIsPoisoned(true);
445 Ident___exception_info->setIsPoisoned(true);
446 Ident_GetExceptionInfo->setIsPoisoned(true);
447 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000448
449 if(FilterExpr.isInvalid())
450 return StmtError();
451
452 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
453 return StmtError();
454
Richard Smithc202b282012-04-14 00:33:13 +0000455 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000456
457 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000458 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000459
460 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
461}
462
463/// ParseSEHFinallyBlock - Handle __finally
464///
465/// seh-finally-block:
466/// '__finally' compound-statement
467///
468StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
469 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
470 raii2(Ident___abnormal_termination, false),
471 raii3(Ident_AbnormalTermination, false);
472
Richard Smithc202b282012-04-14 00:33:13 +0000473 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000474 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000475 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000476
477 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000478}
479
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000480/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000481///
482/// labeled-statement:
483/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000484/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000485///
Richard Smithc202b282012-04-14 00:33:13 +0000486StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000487 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
488 "Not an identifier!");
489
490 Token IdentTok = Tok; // Save the whole token.
491 ConsumeToken(); // eat the identifier.
492
493 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000494
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000495 // identifier ':' statement
496 SourceLocation ColonLoc = ConsumeToken();
497
Richard Smithc202b282012-04-14 00:33:13 +0000498 // Read label attributes, if present. attrs will contain both C++11 and GNU
499 // attributes (if present) after this point.
John McCall53fa7142010-12-24 02:08:15 +0000500 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000501
John McCalldadc5752010-08-24 06:29:42 +0000502 StmtResult SubStmt(ParseStatement());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000503
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000504 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000505 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000506 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000507
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000508 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
509 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000510 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000511 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000512 attrs.clear();
513 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000514
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000515 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
516 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000517}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000518
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000519/// ParseCaseStatement
520/// labeled-statement:
521/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000522/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000523///
Richard Smithc202b282012-04-14 00:33:13 +0000524StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000525 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000526
Chris Lattner34a22092009-03-04 04:23:07 +0000527 // It is very very common for code to contain many case statements recursively
528 // nested, as in (but usually without indentation):
529 // case 1:
530 // case 2:
531 // case 3:
532 // case 4:
533 // case 5: etc.
534 //
535 // Parsing this naively works, but is both inefficient and can cause us to run
536 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000537 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000538 // but all the grossness is constrained to ParseCaseStatement (and some
539 // wierdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000540
Chris Lattner34a22092009-03-04 04:23:07 +0000541 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
542 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000543 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000544
Chris Lattner34a22092009-03-04 04:23:07 +0000545 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
546 // gets updated each time a new case is parsed, and whose body is unset so
547 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieu3481fcd2011-09-09 02:16:15 +0000548 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattner34a22092009-03-04 04:23:07 +0000550 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000551 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000552 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000553 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
554 ConsumeToken(); // eat the 'case'.
Mike Stump11289f42009-09-09 15:08:12 +0000555
Douglas Gregord328d572009-09-21 18:10:23 +0000556 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000557 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000558 cutOffParsing();
559 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000560 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000561
Chris Lattner125c0ee2009-12-10 00:38:54 +0000562 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
563 /// Disable this form of error recovery while we're parsing the case
564 /// expression.
565 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000566
Richard Trieu2c850c02011-04-21 21:44:26 +0000567 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
568 MissingCase = false;
Chris Lattner34a22092009-03-04 04:23:07 +0000569 if (LHS.isInvalid()) {
Chris Lattner476c3ad2006-08-13 22:09:58 +0000570 SkipUntil(tok::colon);
Sebastian Redl042ad952008-12-11 19:30:53 +0000571 return StmtError();
Chris Lattner476c3ad2006-08-13 22:09:58 +0000572 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000573
Chris Lattner34a22092009-03-04 04:23:07 +0000574 // GNU case range extension.
575 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000576 ExprResult RHS;
Chris Lattner34a22092009-03-04 04:23:07 +0000577 if (Tok.is(tok::ellipsis)) {
578 Diag(Tok, diag::ext_gnu_case_range);
579 DotDotDotLoc = ConsumeToken();
Sebastian Redl042ad952008-12-11 19:30:53 +0000580
Chris Lattner34a22092009-03-04 04:23:07 +0000581 RHS = ParseConstantExpression();
582 if (RHS.isInvalid()) {
583 SkipUntil(tok::colon);
584 return StmtError();
585 }
586 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000587
Chris Lattner125c0ee2009-12-10 00:38:54 +0000588 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000589
John McCall0140bfe2011-01-22 09:28:32 +0000590 if (Tok.is(tok::colon)) {
591 ColonLoc = ConsumeToken();
592
593 // Treat "case blah;" as a typo for "case blah:".
594 } else if (Tok.is(tok::semi)) {
595 ColonLoc = ConsumeToken();
596 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
597 << FixItHint::CreateReplacement(ColonLoc, ":");
598 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000599 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
600 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
601 << FixItHint::CreateInsertion(ExpectedLoc, ":");
602 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000603 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000604
John McCalldadc5752010-08-24 06:29:42 +0000605 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000606 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
607 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000608
Chris Lattner34a22092009-03-04 04:23:07 +0000609 // If we had a sema error parsing this case, then just ignore it and
610 // continue parsing the sub-stmt.
611 if (Case.isInvalid()) {
612 if (TopLevelCase.isInvalid()) // No parsed case stmts.
613 return ParseStatement();
614 // Otherwise, just don't add it as a nested case.
615 } else {
616 // If this is the first case statement we parsed, it becomes TopLevelCase.
617 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000618 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000619 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000620 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000621 else
John McCallb268a282010-08-23 23:25:46 +0000622 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000623 DeepestParsedCaseStmt = NextDeepest;
624 }
Mike Stump11289f42009-09-09 15:08:12 +0000625
Chris Lattner34a22092009-03-04 04:23:07 +0000626 // Handle all case statements.
627 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattner34a22092009-03-04 04:23:07 +0000629 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattner34a22092009-03-04 04:23:07 +0000631 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000632 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000633
Chris Lattner34a22092009-03-04 04:23:07 +0000634 if (Tok.isNot(tok::r_brace)) {
635 SubStmt = ParseStatement();
636 } else {
637 // Nicely diagnose the common error "switch (X) { case 4: }", which is
638 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000639 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000640 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
641 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner34a22092009-03-04 04:23:07 +0000642 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000643 }
Mike Stump11289f42009-09-09 15:08:12 +0000644
Chris Lattner34a22092009-03-04 04:23:07 +0000645 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000646 if (SubStmt.isInvalid())
Chris Lattner34a22092009-03-04 04:23:07 +0000647 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattner34a22092009-03-04 04:23:07 +0000649 // Install the body into the most deeply-nested case.
John McCallb268a282010-08-23 23:25:46 +0000650 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl042ad952008-12-11 19:30:53 +0000651
Chris Lattner34a22092009-03-04 04:23:07 +0000652 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000653 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000654}
655
656/// ParseDefaultStatement
657/// labeled-statement:
658/// 'default' ':' statement
659/// Note that this does not parse the 'statement' at the end.
660///
Richard Smithc202b282012-04-14 00:33:13 +0000661StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000662 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000663 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000664
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000665 SourceLocation ColonLoc;
John McCall0140bfe2011-01-22 09:28:32 +0000666 if (Tok.is(tok::colon)) {
667 ColonLoc = ConsumeToken();
668
669 // Treat "default;" as a typo for "default:".
670 } else if (Tok.is(tok::semi)) {
671 ColonLoc = ConsumeToken();
672 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
673 << FixItHint::CreateReplacement(ColonLoc, ":");
674 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000675 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
676 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
677 << FixItHint::CreateInsertion(ExpectedLoc, ":");
678 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000679 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000680
Richard Smith1002d102012-02-17 01:35:32 +0000681 StmtResult SubStmt;
682
683 if (Tok.isNot(tok::r_brace)) {
684 SubStmt = ParseStatement();
685 } else {
686 // Diagnose the common error "switch (X) {... default: }", which is
687 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000688 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000689 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
690 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
691 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000692 }
693
Richard Smith1002d102012-02-17 01:35:32 +0000694 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000695 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000696 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000697
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000698 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000699 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000700}
701
Richard Smithc202b282012-04-14 00:33:13 +0000702StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
703 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000704}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000705
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000706/// ParseCompoundStatement - Parse a "{}" block.
707///
708/// compound-statement: [C99 6.8.2]
709/// { block-item-list[opt] }
710/// [GNU] { label-declarations block-item-list } [TODO]
711///
712/// block-item-list:
713/// block-item
714/// block-item-list block-item
715///
716/// block-item:
717/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000718/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000719/// statement
720/// [OMP] openmp-directive [TODO]
721///
722/// [GNU] label-declarations:
723/// [GNU] label-declaration
724/// [GNU] label-declarations label-declaration
725///
726/// [GNU] label-declaration:
727/// [GNU] '__label__' identifier-list ';'
728///
729/// [OMP] openmp-directive: [TODO]
730/// [OMP] barrier-directive
731/// [OMP] flush-directive
Chris Lattner30f910e2006-10-16 05:52:41 +0000732///
Richard Smithc202b282012-04-14 00:33:13 +0000733StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000734 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000735 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000736
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000737 // Enter a scope to hold everything within the compound stmt. Compound
738 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000739 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000740
741 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000742 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000743}
744
Lang Hames2954cea2012-11-03 22:29:05 +0000745/// Parse any pragmas at the start of the compound expression. We handle these
746/// separately since some pragmas (FP_CONTRACT) must appear before any C
747/// statement in the compound, but may be intermingled with other pragmas.
748void Parser::ParseCompoundStatementLeadingPragmas() {
749 bool checkForPragmas = true;
750 while (checkForPragmas) {
751 switch (Tok.getKind()) {
752 case tok::annot_pragma_vis:
753 HandlePragmaVisibility();
754 break;
755 case tok::annot_pragma_pack:
756 HandlePragmaPack();
757 break;
758 case tok::annot_pragma_msstruct:
759 HandlePragmaMSStruct();
760 break;
761 case tok::annot_pragma_align:
762 HandlePragmaAlign();
763 break;
764 case tok::annot_pragma_weak:
765 HandlePragmaWeak();
766 break;
767 case tok::annot_pragma_weakalias:
768 HandlePragmaWeakAlias();
769 break;
770 case tok::annot_pragma_redefine_extname:
771 HandlePragmaRedefineExtname();
772 break;
773 case tok::annot_pragma_opencl_extension:
774 HandlePragmaOpenCLExtension();
775 break;
776 case tok::annot_pragma_fp_contract:
777 HandlePragmaFPContract();
778 break;
779 default:
780 checkForPragmas = false;
781 break;
782 }
783 }
784
785}
786
Chris Lattnerf2978802007-01-21 06:52:16 +0000787/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000788/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000789/// consume the '}' at the end of the block. It does not manipulate the scope
790/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000791StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000792 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000793 Tok.getLocation(),
794 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000795
796 // Record the state of the FP_CONTRACT pragma, restore on leaving the
797 // compound statement.
798 Sema::FPContractStateRAII SaveFPContractState(Actions);
799
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000800 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000801 BalancedDelimiterTracker T(*this, tok::l_brace);
802 if (T.consumeOpen())
803 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000804
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000805 Sema::CompoundScopeRAII CompoundScope(Actions);
806
Lang Hames2954cea2012-11-03 22:29:05 +0000807 // Parse any pragmas at the beginning of the compound statement.
808 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000809
Lang Hames2954cea2012-11-03 22:29:05 +0000810 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000811
Chris Lattner43e7f312011-02-18 02:08:43 +0000812 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
813 // only allowed at the start of a compound stmt regardless of the language.
814 while (Tok.is(tok::kw___label__)) {
815 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000816
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000817 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000818 while (1) {
819 if (Tok.isNot(tok::identifier)) {
820 Diag(Tok, diag::err_expected_ident);
821 break;
822 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000823
Chris Lattner43e7f312011-02-18 02:08:43 +0000824 IdentifierInfo *II = Tok.getIdentifierInfo();
825 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000826 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000827
Chris Lattner43e7f312011-02-18 02:08:43 +0000828 if (!Tok.is(tok::comma))
829 break;
830 ConsumeToken();
831 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000832
John McCall084e83d2011-03-24 11:26:52 +0000833 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000834 DeclGroupPtrTy Res =
835 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000836 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000837
Chris Lattner02f1b612012-04-28 16:12:17 +0000838 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000839 if (R.isUsable())
840 Stmts.push_back(R.release());
841 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000842
Chris Lattner43e7f312011-02-18 02:08:43 +0000843 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000844 if (Tok.is(tok::annot_pragma_unused)) {
845 HandlePragmaUnused();
846 continue;
847 }
848
David Blaikiebbafb8a2012-03-11 07:00:24 +0000849 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet4a7de3e2011-05-06 20:48:22 +0000850 Tok.is(tok::kw___if_not_exists))) {
851 ParseMicrosoftIfExistsStatement(Stmts);
852 continue;
853 }
854
John McCalldadc5752010-08-24 06:29:42 +0000855 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000856 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000857 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000858 } else {
859 // __extension__ can start declarations and it can also be a unary
860 // operator for expressions. Consume multiple __extension__ markers here
861 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000862 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000863 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000864 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000865 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000866
John McCall084e83d2011-03-24 11:26:52 +0000867 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000868 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000869
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000870 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +0000871 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +0000872 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +0000873 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +0000874 ExtensionRAIIObject O(Diags);
875
Chris Lattner49836b42009-04-02 04:16:50 +0000876 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000877 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
878 Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000879 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000880 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000881 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000882 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +0000883 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +0000884
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000885 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000886 SkipUntil(tok::semi);
887 continue;
888 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +0000889
Alexis Hunt96d5c762009-11-21 08:43:09 +0000890 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +0000891 // Eat the semicolon at the end of stmt and convert the expr into a
892 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000893 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000894 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000895 }
896 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000897
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000898 if (R.isUsable())
Sebastian Redld9f7b1c2008-12-10 00:02:53 +0000899 Stmts.push_back(R.release());
Chris Lattner30f910e2006-10-16 05:52:41 +0000900 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000901
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000902 SourceLocation CloseLoc = Tok.getLocation();
903
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000904 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +0000905 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000906 // Recover by creating a compound statement with what we parsed so far,
907 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +0000908 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +0000909
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000910 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000911 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000912}
Chris Lattnerc951dae2006-08-10 04:23:57 +0000913
Chris Lattnerc0081db2008-12-12 06:31:07 +0000914/// ParseParenExprOrCondition:
915/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +0000916/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +0000917///
918/// This function parses and performs error recovery on the specified condition
919/// or expression (depending on whether we're in C++ or C mode). This function
920/// goes out of its way to recover well. It returns true if there was a parser
921/// error (the right paren couldn't be found), which indicates that the caller
922/// should try to recover harder. It returns false if the condition is
923/// successfully parsed. Note that a successful parse can still have semantic
924/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +0000925bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +0000926 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +0000927 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000928 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000929 BalancedDelimiterTracker T(*this, tok::l_paren);
930 T.consumeOpen();
931
David Blaikiebbafb8a2012-03-11 07:00:24 +0000932 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +0000933 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000934 else {
935 ExprResult = ParseExpression();
John McCall48871652010-08-21 09:40:31 +0000936 DeclResult = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000937
Douglas Gregore60e41a2010-05-06 17:25:47 +0000938 // If required, convert to a boolean value.
939 if (!ExprResult.isInvalid() && ConvertToBoolean)
940 ExprResult
John McCallb268a282010-08-23 23:25:46 +0000941 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
Chris Lattnerc0081db2008-12-12 06:31:07 +0000944 // If the parser was confused by the condition and we don't have a ')', try to
945 // recover by skipping ahead to a semi and bailing out. If condexp is
946 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +0000947 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +0000948 SkipUntil(tok::semi);
949 // Skipping may have stopped if it found the containing ')'. If so, we can
950 // continue parsing the if statement.
951 if (Tok.isNot(tok::r_paren))
952 return true;
953 }
Mike Stump11289f42009-09-09 15:08:12 +0000954
Chris Lattnerc0081db2008-12-12 06:31:07 +0000955 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000956 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +0000957
Chris Lattner70d44982012-04-28 16:24:20 +0000958 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
959 // that all callers are looking for a statement after the condition, so ")"
960 // isn't valid.
961 while (Tok.is(tok::r_paren)) {
962 Diag(Tok, diag::err_extraneous_rparen_in_condition)
963 << FixItHint::CreateRemoval(Tok.getLocation());
964 ConsumeParen();
965 }
Chad Rosier67055f52012-07-10 21:35:27 +0000966
Chris Lattnerc0081db2008-12-12 06:31:07 +0000967 return false;
968}
969
970
Chris Lattnerc951dae2006-08-10 04:23:57 +0000971/// ParseIfStatement
972/// if-statement: [C99 6.8.4.1]
973/// 'if' '(' expression ')' statement
974/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +0000975/// [C++] 'if' '(' condition ')' statement
976/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +0000977///
Richard Smithc202b282012-04-14 00:33:13 +0000978StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000979 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000980 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +0000981
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000982 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +0000983 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +0000984 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +0000985 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +0000986 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +0000987
David Blaikiebbafb8a2012-03-11 07:00:24 +0000988 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000989
Chris Lattner2dd1b722007-08-26 23:08:06 +0000990 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
991 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000992 //
993 // C++ 6.4p3:
994 // A name introduced by a declaration in a condition is in scope from its
995 // point of declaration until the end of the substatements controlled by the
996 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +0000997 // C++ 3.3.2p4:
998 // Names declared in the for-init-statement, and in the condition of if,
999 // while, for, and switch statements are local to the if, while, for, or
1000 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001001 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001002 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001003
Chris Lattnerc951dae2006-08-10 04:23:57 +00001004 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001005 ExprResult CondExp;
John McCall48871652010-08-21 09:40:31 +00001006 Decl *CondVar = 0;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001007 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001008 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001009
David Blaikiea5696df2012-05-16 04:20:04 +00001010 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattner8fb26252007-08-22 05:28:50 +00001012 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001013 // there is no compound stmt. C90 does not have this clause. We only do this
1014 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001015 //
1016 // C++ 6.4p1:
1017 // The substatement in a selection-statement (each substatement, in the else
1018 // form of the if statement) implicitly defines a local scope.
1019 //
1020 // For C++ we create a scope for the condition and a new scope for
1021 // substatements because:
1022 // -When the 'then' scope exits, we want the condition declaration to still be
1023 // active for the 'else' scope too.
1024 // -Sema will detect name clashes by considering declarations of a
1025 // 'ControlScope' as part of its direct subscope.
1026 // -If we wanted the condition and substatement to be in the same scope, we
1027 // would have to notify ParseStatement not to create a new scope. It's
1028 // simpler to let it create a new scope.
1029 //
Mike Stump11289f42009-09-09 15:08:12 +00001030 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001031 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001032
Chris Lattner5c5808a2007-10-29 05:08:52 +00001033 // Read the 'then' stmt.
1034 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001035
1036 SourceLocation InnerStatementTrailingElseLoc;
1037 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001038
Chris Lattner37e54f42007-08-22 05:16:28 +00001039 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001040 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001041
Chris Lattnerc951dae2006-08-10 04:23:57 +00001042 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001043 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001044 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001045 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001046
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001047 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001048 if (TrailingElseLoc)
1049 *TrailingElseLoc = Tok.getLocation();
1050
Chris Lattneraf635312006-10-16 06:06:51 +00001051 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001052 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001053
Chris Lattner8fb26252007-08-22 05:28:50 +00001054 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001055 // there is no compound stmt. C90 does not have this clause. We only do
1056 // this if the body isn't a compound statement to avoid push/pop in common
1057 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001058 //
1059 // C++ 6.4p1:
1060 // The substatement in a selection-statement (each substatement, in the else
1061 // form of the if statement) implicitly defines a local scope.
1062 //
Sebastian Redl042ad952008-12-11 19:30:53 +00001063 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001064 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001065
Chris Lattner30f910e2006-10-16 05:52:41 +00001066 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001067
Chris Lattner37e54f42007-08-22 05:16:28 +00001068 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001069 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001070 } else if (Tok.is(tok::code_completion)) {
1071 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001072 cutOffParsing();
1073 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001074 } else if (InnerStatementTrailingElseLoc.isValid()) {
1075 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001076 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001077
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001078 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001079
Chris Lattner5c5808a2007-10-29 05:08:52 +00001080 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001081 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001082 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001083 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1084 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1085 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001086 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001087 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001088 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001089
Chris Lattner5c5808a2007-10-29 05:08:52 +00001090 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001091 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001092 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001093 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001094 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001095
John McCallb268a282010-08-23 23:25:46 +00001096 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001097 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001098}
1099
Chris Lattner9075bd72006-08-10 04:59:57 +00001100/// ParseSwitchStatement
1101/// switch-statement:
1102/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001103/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001104StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001105 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001106 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001107
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001108 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001109 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001110 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001111 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001112 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001113
David Blaikiebbafb8a2012-03-11 07:00:24 +00001114 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001115
Chris Lattner2dd1b722007-08-26 23:08:06 +00001116 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1117 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001118 //
1119 // C++ 6.4p3:
1120 // A name introduced by a declaration in a condition is in scope from its
1121 // point of declaration until the end of the substatements controlled by the
1122 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001123 // C++ 3.3.2p4:
1124 // Names declared in the for-init-statement, and in the condition of if,
1125 // while, for, and switch statements are local to the if, while, for, or
1126 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001127 //
Richard Trieu2c850c02011-04-21 21:44:26 +00001128 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001129 if (C99orCXX)
1130 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001131 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001132
Chris Lattner9075bd72006-08-10 04:59:57 +00001133 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001134 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001135 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001136 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001137 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001138
John McCalldadc5752010-08-24 06:29:42 +00001139 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001140 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001141
Douglas Gregore60e41a2010-05-06 17:25:47 +00001142 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001143 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001144 // FIXME: This is not optimal recovery, but parsing the body is more
1145 // dangerous due to the presence of case and default statements, which
1146 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001147 if (Tok.is(tok::l_brace)) {
1148 ConsumeBrace();
1149 SkipUntil(tok::r_brace, false, false);
1150 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001151 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001152 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001153 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001154
Chris Lattner8fb26252007-08-22 05:28:50 +00001155 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001156 // there is no compound stmt. C90 does not have this clause. We only do this
1157 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001158 //
1159 // C++ 6.4p1:
1160 // The substatement in a selection-statement (each substatement, in the else
1161 // form of the if statement) implicitly defines a local scope.
1162 //
1163 // See comments in ParseIfStatement for why we create a scope for the
1164 // condition and a new scope for substatement in C++.
1165 //
Mike Stump11289f42009-09-09 15:08:12 +00001166 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001167 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001168
Chris Lattner9075bd72006-08-10 04:59:57 +00001169 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001170 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001171
Chris Lattner8fd2d012010-01-24 01:50:29 +00001172 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001173 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001174 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001175
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001176 if (Body.isInvalid()) {
Chris Lattner8fd2d012010-01-24 01:50:29 +00001177 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001178
1179 // Put the synthesized null statement on the same line as the end of switch
1180 // condition.
1181 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1182 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1183 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001184
John McCallb268a282010-08-23 23:25:46 +00001185 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001186}
1187
1188/// ParseWhileStatement
1189/// while-statement: [C99 6.8.5.1]
1190/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001191/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001192StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001193 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001194 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001195 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001196
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001197 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001198 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001199 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001200 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001201 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001202
David Blaikiebbafb8a2012-03-11 07:00:24 +00001203 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001204
Chris Lattner2dd1b722007-08-26 23:08:06 +00001205 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1206 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001207 //
1208 // C++ 6.4p3:
1209 // A name introduced by a declaration in a condition is in scope from its
1210 // point of declaration until the end of the substatements controlled by the
1211 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001212 // C++ 3.3.2p4:
1213 // Names declared in the for-init-statement, and in the condition of if,
1214 // while, for, and switch statements are local to the if, while, for, or
1215 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001216 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001217 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001218 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001219 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1220 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001221 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001222 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1223 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001224
Chris Lattner9075bd72006-08-10 04:59:57 +00001225 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001226 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001227 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001228 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001229 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001230
David Blaikiea5696df2012-05-16 04:20:04 +00001231 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001232
Chris Lattner8fb26252007-08-22 05:28:50 +00001233 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001234 // there is no compound stmt. C90 does not have this clause. We only do this
1235 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001236 //
1237 // C++ 6.5p2:
1238 // The substatement in an iteration-statement implicitly defines a local scope
1239 // which is entered and exited each time through the loop.
1240 //
1241 // See comments in ParseIfStatement for why we create a scope for the
1242 // condition and a new scope for substatement in C++.
1243 //
Mike Stump11289f42009-09-09 15:08:12 +00001244 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001245 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001246
Chris Lattner9075bd72006-08-10 04:59:57 +00001247 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001248 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001249
Chris Lattner8fb26252007-08-22 05:28:50 +00001250 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001251 InnerScope.Exit();
1252 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001253
John McCall48871652010-08-21 09:40:31 +00001254 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001255 return StmtError();
1256
John McCallb268a282010-08-23 23:25:46 +00001257 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001258}
1259
1260/// ParseDoStatement
1261/// do-statement: [C99 6.8.5.2]
1262/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001263/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001264StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001265 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001266 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001267
Chris Lattner2dd1b722007-08-26 23:08:06 +00001268 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1269 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001270 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001271 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001272 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001273 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001274 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001275
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001276 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001277
Chris Lattner8fb26252007-08-22 05:28:50 +00001278 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001279 // there is no compound stmt. C90 does not have this clause. We only do this
1280 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001281 //
1282 // C++ 6.5p2:
1283 // The substatement in an iteration-statement implicitly defines a local scope
1284 // which is entered and exited each time through the loop.
1285 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001286 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001287 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001288 Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001289
Chris Lattner9075bd72006-08-10 04:59:57 +00001290 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001291 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001292
Chris Lattner8fb26252007-08-22 05:28:50 +00001293 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001294 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001295
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001296 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001297 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001298 Diag(Tok, diag::err_expected_while);
Chris Lattner03c40412008-11-23 23:17:07 +00001299 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner0046de12008-11-13 18:52:53 +00001300 SkipUntil(tok::semi, false, true);
1301 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001302 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001303 }
Chris Lattneraf635312006-10-16 06:06:51 +00001304 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001305
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001306 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001307 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner0046de12008-11-13 18:52:53 +00001308 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001309 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001310 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001311
Chris Lattner10da53c2008-12-12 06:35:28 +00001312 // Parse the parenthesized condition.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001313 BalancedDelimiterTracker T(*this, tok::l_paren);
1314 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001315
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001316 // FIXME: Do not just parse the attribute contents and throw them away
1317 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001318 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001319 ProhibitAttributes(attrs);
1320
John McCalldadc5752010-08-24 06:29:42 +00001321 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001322 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001323 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001324
Sebastian Redlb62406f2008-12-11 19:48:14 +00001325 if (Cond.isInvalid() || Body.isInvalid())
1326 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001327
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001328 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1329 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001330}
1331
1332/// ParseForStatement
1333/// for-statement: [C99 6.8.5.3]
1334/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1335/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001336/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1337/// [C++] statement
Richard Smith02e85f32011-04-14 22:09:26 +00001338/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001339/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1340/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001341///
1342/// [C++] for-init-statement:
1343/// [C++] expression-statement
1344/// [C++] simple-declaration
1345///
Richard Smith02e85f32011-04-14 22:09:26 +00001346/// [C++0x] for-range-declaration:
1347/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1348/// [C++0x] for-range-initializer:
1349/// [C++0x] expression
1350/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001351StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001352 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001353 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001354
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001355 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001356 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001357 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001358 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001359 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001360
Chad Rosier67055f52012-07-10 21:35:27 +00001361 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1362 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001363
Chris Lattner2dd1b722007-08-26 23:08:06 +00001364 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1365 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001366 //
1367 // C++ 6.4p3:
1368 // A name introduced by a declaration in a condition is in scope from its
1369 // point of declaration until the end of the substatements controlled by the
1370 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001371 // C++ 3.3.2p4:
1372 // Names declared in the for-init-statement, and in the condition of if,
1373 // while, for, and switch statements are local to the if, while, for, or
1374 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001375 // C++ 6.5.3p1:
1376 // Names declared in the for-init-statement are in the same declarative-region
1377 // as those declared in the condition.
1378 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001379 unsigned ScopeFlags;
Chris Lattner934074c2009-04-22 00:54:41 +00001380 if (C99orCXXorObjC)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001381 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1382 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001383 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001384 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1385
1386 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001387
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001388 BalancedDelimiterTracker T(*this, tok::l_paren);
1389 T.consumeOpen();
1390
John McCalldadc5752010-08-24 06:29:42 +00001391 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001392
Richard Smith02e85f32011-04-14 22:09:26 +00001393 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001394 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001395 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001396 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001397 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001398 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001399 FullExprArg ThirdPart(Actions);
John McCall48871652010-08-21 09:40:31 +00001400 Decl *SecondVar = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001401
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001402 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001403 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001404 C99orCXXorObjC? Sema::PCC_ForInit
1405 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001406 cutOffParsing();
1407 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001408 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001409
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001410 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001411 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001412
Chris Lattner9075bd72006-08-10 04:59:57 +00001413 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001414 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001415 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001416 // no first part, eat the ';'.
1417 ConsumeToken();
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001418 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001419 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001420 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001421 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001422
Richard Smith02e85f32011-04-14 22:09:26 +00001423 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001424 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001425 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1426
Chris Lattner49836b42009-04-02 04:16:50 +00001427 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +00001428 StmtVector Stmts;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001429 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smith02e85f32011-04-14 22:09:26 +00001430 DeclEnd, attrs, false,
1431 MightBeForRangeStmt ?
1432 &ForRangeInit : 0);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001433 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001434
Richard Smith02e85f32011-04-14 22:09:26 +00001435 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001436 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001437 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001438
Richard Smith02e85f32011-04-14 22:09:26 +00001439 ForRange = true;
1440 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001441 ConsumeToken();
1442 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001443 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001444 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001445 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001446
Douglas Gregor68762e72010-08-23 21:17:50 +00001447 if (Tok.is(tok::code_completion)) {
1448 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001449 cutOffParsing();
1450 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001451 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001452 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001453 } else {
1454 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001455 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001456 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001457 ProhibitAttributes(attrs);
Chris Lattner89c50c62006-08-11 06:41:18 +00001458 Value = ParseExpression();
Chris Lattner71e23ce2006-11-04 20:18:38 +00001459
John McCall34376a62010-12-04 03:47:34 +00001460 ForEach = isTokIdentifier_in();
1461
Chris Lattnercd68f642007-06-27 01:06:29 +00001462 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001463 if (!Value.isInvalid()) {
1464 if (ForEach)
1465 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1466 else
Richard Smith945f8d32013-01-14 22:39:08 +00001467 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001468 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001469
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001470 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001471 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001472 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001473 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001474
Douglas Gregor68762e72010-08-23 21:17:50 +00001475 if (Tok.is(tok::code_completion)) {
1476 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001477 cutOffParsing();
1478 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001479 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001480 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001481 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001482 // User tried to write the reasonable, but ill-formed, for-range-statement
1483 // for (expr : expr) { ... }
1484 Diag(Tok, diag::err_for_range_expected_decl)
1485 << FirstPart.get()->getSourceRange();
1486 SkipUntil(tok::r_paren, false, true);
1487 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001488 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001489 if (!Value.isInvalid()) {
1490 Diag(Tok, diag::err_expected_semi_for);
1491 } else {
1492 // Skip until semicolon or rparen, don't consume it.
1493 SkipUntil(tok::r_paren, true, true);
1494 if (Tok.is(tok::semi))
1495 ConsumeToken();
1496 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001497 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001498 }
Richard Smith02e85f32011-04-14 22:09:26 +00001499 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001500 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001501 // Parse the second part of the for specifier.
1502 if (Tok.is(tok::semi)) { // for (...;;
1503 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001504 } else if (Tok.is(tok::r_paren)) {
1505 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001506 } else {
John McCalldadc5752010-08-24 06:29:42 +00001507 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001508 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001509 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1510 else {
1511 Second = ParseExpression();
1512 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001513 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001514 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001515 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001516 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001517 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001518 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001519
Douglas Gregor230a7e62011-02-17 03:38:46 +00001520 if (Tok.isNot(tok::semi)) {
1521 if (!SecondPartIsInvalid || SecondVar)
1522 Diag(Tok, diag::err_expected_semi_for);
1523 else
1524 // Skip until semicolon or rparen, don't consume it.
1525 SkipUntil(tok::r_paren, true, true);
1526 }
1527
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001528 if (Tok.is(tok::semi)) {
1529 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001530 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001531
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001532 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001533 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001534 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001535 // FIXME: The C++11 standard doesn't actually say that this is a
1536 // discarded-value expression, but it clearly should be.
1537 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001538 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001539 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001540 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001541 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001542
Richard Smith02e85f32011-04-14 22:09:26 +00001543 // We need to perform most of the semantic analysis for a C++0x for-range
1544 // statememt before parsing the body, in order to be able to deduce the type
1545 // of an auto-typed loop variable.
1546 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001547 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001548
John McCall53848232011-07-27 01:07:15 +00001549 if (ForRange) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001550 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smith02e85f32011-04-14 22:09:26 +00001551 ForRangeInit.ColonLoc,
1552 ForRangeInit.RangeExpr.get(),
Richard Smitha05b3b52012-09-20 21:52:32 +00001553 T.getCloseLocation(),
1554 Sema::BFRK_Build);
Richard Smith02e85f32011-04-14 22:09:26 +00001555
John McCall53848232011-07-27 01:07:15 +00001556
1557 // Similarly, we need to do the semantic analysis for a for-range
1558 // statement immediately in order to close over temporaries correctly.
1559 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001560 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001561 FirstPart.take(),
Chad Rosier67055f52012-07-10 21:35:27 +00001562 Collection.take(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001563 T.getCloseLocation());
John McCall53848232011-07-27 01:07:15 +00001564 }
1565
Chris Lattner8fb26252007-08-22 05:28:50 +00001566 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001567 // there is no compound stmt. C90 does not have this clause. We only do this
1568 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001569 //
1570 // C++ 6.5p2:
1571 // The substatement in an iteration-statement implicitly defines a local scope
1572 // which is entered and exited each time through the loop.
1573 //
1574 // See comments in ParseIfStatement for why we create a scope for
1575 // for-init-statement/condition and a new scope for substatement in C++.
1576 //
Mike Stump11289f42009-09-09 15:08:12 +00001577 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner934074c2009-04-22 00:54:41 +00001578 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001579
Chris Lattner9075bd72006-08-10 04:59:57 +00001580 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001581 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001582
Chris Lattner8fb26252007-08-22 05:28:50 +00001583 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001584 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001585
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001586 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001587 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001588
1589 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001590 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001591
Richard Smith02e85f32011-04-14 22:09:26 +00001592 if (ForEach)
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001593 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1594 Body.take());
Mike Stump11289f42009-09-09 15:08:12 +00001595
Richard Smith02e85f32011-04-14 22:09:26 +00001596 if (ForRange)
1597 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1598
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001599 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1600 SecondPart, SecondVar, ThirdPart,
1601 T.getCloseLocation(), Body.take());
Chris Lattner9075bd72006-08-10 04:59:57 +00001602}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001603
Chris Lattner503fadc2006-08-10 05:45:44 +00001604/// ParseGotoStatement
1605/// jump-statement:
1606/// 'goto' identifier ';'
1607/// [GNU] 'goto' '*' expression ';'
1608///
1609/// Note: this lets the caller parse the end ';'.
1610///
Richard Smithc202b282012-04-14 00:33:13 +00001611StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001612 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001613 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001614
John McCalldadc5752010-08-24 06:29:42 +00001615 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001616 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001617 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1618 Tok.getLocation());
1619 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001620 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001621 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001622 // GNU indirect goto extension.
1623 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001624 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001625 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001626 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Chris Lattnera0927ce2006-08-12 16:59:03 +00001627 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001628 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001629 }
John McCallb268a282010-08-23 23:25:46 +00001630 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001631 } else {
1632 Diag(Tok, diag::err_expected_ident);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001633 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001634 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001635
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001636 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001637}
1638
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001639/// ParseContinueStatement
1640/// jump-statement:
1641/// 'continue' ';'
1642///
1643/// Note: this lets the caller parse the end ';'.
1644///
Richard Smithc202b282012-04-14 00:33:13 +00001645StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001646 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001647 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001648}
1649
1650/// ParseBreakStatement
1651/// jump-statement:
1652/// 'break' ';'
1653///
1654/// Note: this lets the caller parse the end ';'.
1655///
Richard Smithc202b282012-04-14 00:33:13 +00001656StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001657 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001658 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001659}
1660
Chris Lattner503fadc2006-08-10 05:45:44 +00001661/// ParseReturnStatement
1662/// jump-statement:
1663/// 'return' expression[opt] ';'
Richard Smithc202b282012-04-14 00:33:13 +00001664StmtResult Parser::ParseReturnStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001665 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001666 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001667
John McCalldadc5752010-08-24 06:29:42 +00001668 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001669 if (Tok.isNot(tok::semi)) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001670 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001671 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001672 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001673 return StmtError();
1674 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001675
David Blaikiebbafb8a2012-03-11 07:00:24 +00001676 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001677 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001678 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001679 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001680 diag::warn_cxx98_compat_generalized_initializer_lists :
1681 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001682 << R.get()->getSourceRange();
1683 } else
1684 R = ParseExpression();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001685 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Chris Lattnera0927ce2006-08-12 16:59:03 +00001686 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001687 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001688 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001689 }
John McCallb268a282010-08-23 23:25:46 +00001690 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Chris Lattner503fadc2006-08-10 05:45:44 +00001691}
Chris Lattner0116c472006-08-15 06:03:28 +00001692
John McCallf413f5e2013-05-03 00:10:13 +00001693namespace {
1694 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1695 Parser &TheParser;
1696 SourceLocation AsmLoc;
1697 StringRef AsmString;
1698
1699 /// The tokens we streamed into AsmString and handed off to MC.
1700 ArrayRef<Token> AsmToks;
1701
1702 /// The offset of each token in AsmToks within AsmString.
1703 ArrayRef<unsigned> AsmTokOffsets;
1704
1705 public:
1706 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1707 StringRef AsmString,
1708 ArrayRef<Token> Toks,
1709 ArrayRef<unsigned> Offsets)
1710 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1711 AsmToks(Toks), AsmTokOffsets(Offsets) {
1712 assert(AsmToks.size() == AsmTokOffsets.size());
1713 }
1714
1715 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1716 InlineAsmIdentifierInfo &Info,
1717 bool IsUnevaluatedContext) {
1718 // Collect the desired tokens.
1719 SmallVector<Token, 16> LineToks;
1720 const Token *FirstOrigToken = 0;
1721 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1722
1723 unsigned NumConsumedToks;
1724 ExprResult Result =
1725 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1726 IsUnevaluatedContext);
1727
1728 // If we consumed the entire line, tell MC that.
1729 // Also do this if we consumed nothing as a way of reporting failure.
1730 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1731 // By not modifying LineBuf, we're implicitly consuming it all.
1732
1733 // Otherwise, consume up to the original tokens.
1734 } else {
1735 assert(FirstOrigToken && "not using original tokens?");
1736
1737 // Since we're using original tokens, apply that offset.
1738 assert(FirstOrigToken[NumConsumedToks].getLocation()
1739 == LineToks[NumConsumedToks].getLocation());
1740 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1741 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1742
1743 // The total length we've consumed is the relative offset
1744 // of the last token we consumed plus its length.
1745 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1746 + AsmToks[LastIndex].getLength()
1747 - AsmTokOffsets[FirstIndex]);
1748 LineBuf = LineBuf.substr(0, TotalOffset);
1749 }
1750
1751 // Initialize the "decl" with the lookup result.
1752 Info.OpDecl = static_cast<void*>(Result.take());
1753 return Info.OpDecl;
1754 }
1755
1756 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1757 unsigned &Offset) {
1758 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1759 Offset, AsmLoc);
1760 }
1761
1762 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1763 void *Context) {
1764 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1765 }
1766
1767 private:
1768 /// Collect the appropriate tokens for the given string.
1769 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1770 const Token *&FirstOrigToken) const {
1771 // For now, assert that the string we're working with is a substring
1772 // of what we gave to MC. This lets us use the original tokens.
1773 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1774 !std::less<const char*>()(AsmString.end(), Str.end()));
1775
1776 // Try to find a token whose offset matches the first token.
1777 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1778 const unsigned *FirstTokOffset
1779 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1780 FirstCharOffset);
1781
1782 // For now, assert that the start of the string exactly
1783 // corresponds to the start of a token.
1784 assert(*FirstTokOffset == FirstCharOffset);
1785
1786 // Use all the original tokens for this line. (We assume the
1787 // end of the line corresponds cleanly to a token break.)
1788 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1789 FirstOrigToken = &AsmToks[FirstTokIndex];
1790 unsigned LastCharOffset = Str.end() - AsmString.begin();
1791 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1792 if (AsmTokOffsets[i] >= LastCharOffset) break;
1793 TempToks.push_back(AsmToks[i]);
1794 }
1795 }
1796
1797 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1798 // Compute an offset into the inline asm buffer.
1799 // FIXME: This isn't right if .macro is involved (but hopefully, no
1800 // real-world code does that).
1801 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1802 const llvm::MemoryBuffer *LBuf =
1803 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1804 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1805
1806 // Figure out which token that offset points into.
1807 const unsigned *TokOffsetPtr =
1808 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1809 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1810 unsigned TokOffset = *TokOffsetPtr;
1811
1812 // If we come up with an answer which seems sane, use it; otherwise,
1813 // just point at the __asm keyword.
1814 // FIXME: Assert the answer is sane once we handle .macro correctly.
1815 SourceLocation Loc = AsmLoc;
1816 if (TokIndex < AsmToks.size()) {
1817 const Token &Tok = AsmToks[TokIndex];
1818 Loc = Tok.getLocation();
1819 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1820 }
1821 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1822 << D.getMessage();
1823 }
1824 };
1825}
1826
1827/// Parse an identifier in an MS-style inline assembly block.
1828///
1829/// \param CastInfo - a void* so that we don't have to teach Parser.h
1830/// about the actual type.
1831ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1832 unsigned &NumLineToksConsumed,
1833 void *CastInfo,
1834 bool IsUnevaluatedContext) {
1835 llvm::InlineAsmIdentifierInfo &Info =
1836 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1837
1838 // Push a fake token on the end so that we don't overrun the token
1839 // stream. We use ';' because it expression-parsing should never
1840 // overrun it.
1841 const tok::TokenKind EndOfStream = tok::semi;
1842 Token EndOfStreamTok;
1843 EndOfStreamTok.startToken();
1844 EndOfStreamTok.setKind(EndOfStream);
1845 LineToks.push_back(EndOfStreamTok);
1846
1847 // Also copy the current token over.
1848 LineToks.push_back(Tok);
1849
1850 PP.EnterTokenStream(LineToks.begin(),
1851 LineToks.size(),
1852 /*disable macros*/ true,
1853 /*owns tokens*/ false);
1854
1855 // Clear the current token and advance to the first token in LineToks.
1856 ConsumeAnyToken();
1857
1858 // Parse an optional scope-specifier if we're in C++.
1859 CXXScopeSpec SS;
1860 if (getLangOpts().CPlusPlus) {
1861 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1862 }
1863
1864 // Require an identifier here.
1865 SourceLocation TemplateKWLoc;
1866 UnqualifiedId Id;
1867 bool Invalid = ParseUnqualifiedId(SS,
1868 /*EnteringContext=*/false,
1869 /*AllowDestructorName=*/false,
1870 /*AllowConstructorName=*/false,
1871 /*ObjectType=*/ ParsedType(),
1872 TemplateKWLoc,
1873 Id);
1874
1875 // If we've run into the poison token we inserted before, or there
1876 // was a parsing error, then claim the entire line.
1877 if (Invalid || Tok.is(EndOfStream)) {
1878 NumLineToksConsumed = LineToks.size() - 2;
1879
1880 // Otherwise, claim up to the start of the next token.
1881 } else {
1882 // Figure out how many tokens we are into LineToks.
1883 unsigned LineIndex = 0;
1884 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1885 LineIndex++;
1886 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1887 }
1888
1889 NumLineToksConsumed = LineIndex;
1890 }
1891
1892 // Finally, restore the old parsing state by consuming all the
1893 // tokens we staged before, implicitly killing off the
1894 // token-lexer we pushed.
1895 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1896 ConsumeAnyToken();
1897 }
1898 ConsumeToken(EndOfStream);
1899
1900 // Leave LineToks in its original state.
1901 LineToks.pop_back();
1902 LineToks.pop_back();
1903
1904 // Perform the lookup.
1905 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1906 IsUnevaluatedContext);
1907}
1908
1909/// Turn a sequence of our tokens back into a string that we can hand
1910/// to the MC asm parser.
1911static bool buildMSAsmString(Preprocessor &PP,
1912 SourceLocation AsmLoc,
1913 ArrayRef<Token> AsmToks,
1914 SmallVectorImpl<unsigned> &TokOffsets,
1915 SmallString<512> &Asm) {
1916 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1917
1918 // Is this the start of a new assembly statement?
1919 bool isNewStatement = true;
1920
1921 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1922 const Token &Tok = AsmToks[i];
1923
1924 // Start each new statement with a newline and a tab.
1925 if (!isNewStatement &&
1926 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1927 Asm += "\n\t";
1928 isNewStatement = true;
1929 }
1930
1931 // Preserve the existence of leading whitespace except at the
1932 // start of a statement.
1933 if (!isNewStatement && Tok.hasLeadingSpace())
1934 Asm += ' ';
1935
1936 // Remember the offset of this token.
1937 TokOffsets.push_back(Asm.size());
1938
1939 // Don't actually write '__asm' into the assembly stream.
1940 if (Tok.is(tok::kw_asm)) {
1941 // Complain about __asm at the end of the stream.
1942 if (i + 1 == e) {
1943 PP.Diag(AsmLoc, diag::err_asm_empty);
1944 return true;
1945 }
1946
1947 continue;
1948 }
1949
1950 // Append the spelling of the token.
1951 SmallString<32> SpellingBuffer;
1952 bool SpellingInvalid = false;
1953 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
1954 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
1955
1956 // We are no longer at the start of a statement.
1957 isNewStatement = false;
1958 }
1959
1960 // Ensure that the buffer is null-terminated.
1961 Asm.push_back('\0');
1962 Asm.pop_back();
1963
1964 assert(TokOffsets.size() == AsmToks.size());
1965 return false;
1966}
1967
Eli Friedmana4b02c32011-09-30 01:13:51 +00001968/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1969/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier32503022012-06-11 20:47:18 +00001970///
1971/// [MS] ms-asm-statement:
1972/// ms-asm-block
1973/// ms-asm-block ms-asm-statement
1974///
1975/// [MS] ms-asm-block:
1976/// '__asm' ms-asm-line '\n'
1977/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1978///
1979/// [MS] ms-asm-instruction-block
1980/// ms-asm-line
1981/// ms-asm-line '\n' ms-asm-instruction-block
1982///
Eli Friedmana4b02c32011-09-30 01:13:51 +00001983StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1984 SourceManager &SrcMgr = PP.getSourceManager();
1985 SourceLocation EndLoc = AsmLoc;
Chad Rosier32503022012-06-11 20:47:18 +00001986 SmallVector<Token, 4> AsmToks;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00001987
1988 bool InBraces = false;
1989 unsigned short savedBraceCount = 0;
1990 bool InAsmComment = false;
1991 FileID FID;
1992 unsigned LineNo = 0;
1993 unsigned NumTokensRead = 0;
1994 SourceLocation LBraceLoc;
1995
1996 if (Tok.is(tok::l_brace)) {
1997 // Braced inline asm: consume the opening brace.
1998 InBraces = true;
1999 savedBraceCount = BraceCount;
2000 EndLoc = LBraceLoc = ConsumeBrace();
2001 ++NumTokensRead;
2002 } else {
2003 // Single-line inline asm; compute which line it is on.
2004 std::pair<FileID, unsigned> ExpAsmLoc =
2005 SrcMgr.getDecomposedExpansionLoc(EndLoc);
2006 FID = ExpAsmLoc.first;
2007 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2008 }
2009
2010 SourceLocation TokLoc = Tok.getLocation();
Eli Friedmana4b02c32011-09-30 01:13:51 +00002011 do {
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002012 // If we hit EOF, we're done, period.
2013 if (Tok.is(tok::eof))
Eli Friedmana4b02c32011-09-30 01:13:51 +00002014 break;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002015
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002016 if (!InAsmComment && Tok.is(tok::semi)) {
2017 // A semicolon in an asm is the start of a comment.
2018 InAsmComment = true;
2019 if (InBraces) {
2020 // Compute which line the comment is on.
2021 std::pair<FileID, unsigned> ExpSemiLoc =
2022 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2023 FID = ExpSemiLoc.first;
2024 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2025 }
2026 } else if (!InBraces || InAsmComment) {
2027 // If end-of-line is significant, check whether this token is on a
2028 // new line.
2029 std::pair<FileID, unsigned> ExpLoc =
2030 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2031 if (ExpLoc.first != FID ||
2032 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2033 // If this is a single-line __asm, we're done.
2034 if (!InBraces)
2035 break;
2036 // We're no longer in a comment.
2037 InAsmComment = false;
2038 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2039 // Single-line asm always ends when a closing brace is seen.
2040 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2041 // does MSVC do here?
2042 break;
2043 }
2044 }
2045 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2046 BraceCount == (savedBraceCount + 1)) {
2047 // Consume the closing brace, and finish
2048 EndLoc = ConsumeBrace();
2049 break;
2050 }
2051
2052 // Consume the next token; make sure we don't modify the brace count etc.
2053 // if we are in a comment.
2054 EndLoc = TokLoc;
2055 if (InAsmComment)
2056 PP.Lex(Tok);
2057 else {
2058 AsmToks.push_back(Tok);
2059 ConsumeAnyToken();
2060 }
2061 TokLoc = Tok.getLocation();
2062 ++NumTokensRead;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002063 } while (1);
Chad Rosier32503022012-06-11 20:47:18 +00002064
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002065 if (InBraces && BraceCount != savedBraceCount) {
2066 // __asm without closing brace (this can happen at EOF).
2067 Diag(Tok, diag::err_expected_rbrace);
2068 Diag(LBraceLoc, diag::note_matching) << "{";
2069 return StmtError();
2070 } else if (NumTokensRead == 0) {
2071 // Empty __asm.
2072 Diag(Tok, diag::err_expected_lbrace);
2073 return StmtError();
2074 }
2075
John McCallf413f5e2013-05-03 00:10:13 +00002076 // Okay, prepare to use MC to parse the assembly.
2077 SmallVector<StringRef, 4> ConstraintRefs;
2078 SmallVector<Expr*, 4> Exprs;
2079 SmallVector<StringRef, 4> ClobberRefs;
2080
2081 // We need an actual supported target.
2082 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2083 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
2084 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2085 ArchTy != llvm::Triple::x86_64);
2086 if (UnsupportedArch)
2087 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
2088
2089 // If we don't support assembly, or the assembly is empty, we don't
2090 // need to instantiate the AsmParser, etc.
2091 if (UnsupportedArch || AsmToks.empty()) {
2092 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2093 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2094 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2095 }
2096
2097 // Expand the tokens into a string buffer.
2098 SmallString<512> AsmString;
2099 SmallVector<unsigned, 8> TokOffsets;
2100 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2101 return StmtError();
2102
2103 // Find the target and create the target specific parser.
2104 std::string Error;
2105 const std::string &TT = TheTriple.getTriple();
2106 const llvm::Target *TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2107
John McCallf413f5e2013-05-03 00:10:13 +00002108 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
Rafael Espindola77056232013-05-13 01:24:18 +00002109 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002110 // Get the instruction descriptor.
2111 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
John McCallf413f5e2013-05-03 00:10:13 +00002112 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2113 OwningPtr<llvm::MCSubtargetInfo>
2114 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2115
2116 llvm::SourceMgr TempSrcMgr;
Bill Wendlingda1e3e72013-06-18 07:22:05 +00002117 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallf413f5e2013-05-03 00:10:13 +00002118 llvm::MemoryBuffer *Buffer =
2119 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2120
2121 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2122 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2123
2124 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2125 OwningPtr<llvm::MCAsmParser>
2126 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2127 OwningPtr<llvm::MCTargetAsmParser>
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002128 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser, *MII));
John McCallf413f5e2013-05-03 00:10:13 +00002129
John McCallf413f5e2013-05-03 00:10:13 +00002130 llvm::MCInstPrinter *IP =
2131 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2132
2133 // Change to the Intel dialect.
2134 Parser->setAssemblerDialect(1);
2135 Parser->setTargetParser(*TargetParser.get());
2136 Parser->setParsingInlineAsm(true);
2137 TargetParser->setParsingInlineAsm(true);
2138
2139 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2140 AsmToks, TokOffsets);
2141 TargetParser->setSemaCallback(&Callback);
2142 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2143 &Callback);
2144
2145 unsigned NumOutputs;
2146 unsigned NumInputs;
2147 std::string AsmStringIR;
2148 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2149 SmallVector<std::string, 4> Constraints;
2150 SmallVector<std::string, 4> Clobbers;
2151 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2152 NumOutputs, NumInputs, OpExprs, Constraints,
2153 Clobbers, MII, IP, Callback))
2154 return StmtError();
2155
2156 // Build the vector of clobber StringRefs.
2157 unsigned NumClobbers = Clobbers.size();
2158 ClobberRefs.resize(NumClobbers);
2159 for (unsigned i = 0; i != NumClobbers; ++i)
2160 ClobberRefs[i] = StringRef(Clobbers[i]);
2161
2162 // Recast the void pointers and build the vector of constraint StringRefs.
2163 unsigned NumExprs = NumOutputs + NumInputs;
2164 ConstraintRefs.resize(NumExprs);
2165 Exprs.resize(NumExprs);
2166 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2167 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2168 if (!OpExpr)
2169 return StmtError();
2170
2171 // Need address of variable.
2172 if (OpExprs[i].second)
2173 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2174 .take();
2175
2176 ConstraintRefs[i] = StringRef(Constraints[i]);
2177 Exprs[i] = OpExpr;
2178 }
2179
Chad Rosierc6c71332012-08-06 20:03:45 +00002180 // FIXME: We should be passing source locations for better diagnostics.
John McCallf413f5e2013-05-03 00:10:13 +00002181 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2182 NumOutputs, NumInputs,
2183 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002184}
2185
Chris Lattner0116c472006-08-15 06:03:28 +00002186/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff69e8f9e2008-02-11 23:15:56 +00002187/// asm-statement:
2188/// gnu-asm-statement
2189/// ms-asm-statement
2190///
2191/// [GNU] gnu-asm-statement:
Chris Lattner0116c472006-08-15 06:03:28 +00002192/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2193///
2194/// [GNU] asm-argument:
2195/// asm-string-literal
2196/// asm-string-literal ':' asm-operands[opt]
2197/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2198/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2199/// ':' asm-clobbers
2200///
2201/// [GNU] asm-clobbers:
2202/// asm-string-literal
2203/// asm-clobbers ',' asm-string-literal
2204///
John McCalldadc5752010-08-24 06:29:42 +00002205StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002206 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattner73c56c02007-10-29 04:04:16 +00002207 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002208
Chad Rosierc8e56e82012-12-05 21:08:21 +00002209 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosier67055f52012-07-10 21:35:27 +00002210 !isTypeQualifier()) {
Steve Naroffb2c80c72008-02-07 03:50:06 +00002211 msAsm = true;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002212 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002213 }
John McCall084e83d2011-03-24 11:26:52 +00002214 DeclSpec DS(AttrFactory);
Chris Lattner0116c472006-08-15 06:03:28 +00002215 SourceLocation Loc = Tok.getLocation();
Alexis Hunt96d5c762009-11-21 08:43:09 +00002216 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002217
Chris Lattner0116c472006-08-15 06:03:28 +00002218 // GNU asms accept, but warn, about type-qualifiers other than volatile.
Chris Lattnera925dc62006-11-28 04:33:46 +00002219 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner6d29c102008-11-18 07:48:38 +00002220 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Chris Lattnera925dc62006-11-28 04:33:46 +00002221 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner6d29c102008-11-18 07:48:38 +00002222 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith8e1ac332013-03-28 01:55:44 +00002223 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2224 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2225 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redlb62406f2008-12-11 19:48:14 +00002226
Chris Lattner0116c472006-08-15 06:03:28 +00002227 // Remember if this was a volatile asm.
Anders Carlsson660bdd12007-11-23 23:12:25 +00002228 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002229 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002230 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Chris Lattner0116c472006-08-15 06:03:28 +00002231 SkipUntil(tok::r_paren);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002232 return StmtError();
Chris Lattner0116c472006-08-15 06:03:28 +00002233 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002234 BalancedDelimiterTracker T(*this, tok::l_paren);
2235 T.consumeOpen();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002236
John McCalldadc5752010-08-24 06:29:42 +00002237 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002238 if (AsmString.isInvalid()) {
Richard Smithd67aea22012-03-06 03:21:47 +00002239 // Consume up to and including the closing paren.
2240 T.skipToEnd();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002241 return StmtError();
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002242 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002243
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002244 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002245 ExprVector Constraints;
2246 ExprVector Exprs;
2247 ExprVector Clobbers;
Chris Lattner0116c472006-08-15 06:03:28 +00002248
Anders Carlsson19fe1162008-02-05 23:03:50 +00002249 if (Tok.is(tok::r_paren)) {
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002250 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002251 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002252 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2253 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2254 Constraints, Exprs, AsmString.take(),
2255 Clobbers, T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002256 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002257
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002258 // Parse Outputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002259 bool AteExtraColon = false;
2260 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2261 // In C++ mode, parse "::" like ": :".
2262 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002263 ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002264
Chris Lattner15768502009-12-20 23:08:04 +00002265 if (!AteExtraColon &&
2266 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002267 return StmtError();
2268 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002269
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002270 unsigned NumOutputs = Names.size();
2271
2272 // Parse Inputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002273 if (AteExtraColon ||
2274 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2275 // In C++ mode, parse "::" like ": :".
2276 if (AteExtraColon)
2277 AteExtraColon = false;
2278 else {
2279 AteExtraColon = Tok.is(tok::coloncolon);
2280 ConsumeToken();
2281 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002282
Chris Lattner15768502009-12-20 23:08:04 +00002283 if (!AteExtraColon &&
2284 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002285 return StmtError();
2286 }
2287
2288 assert(Names.size() == Constraints.size() &&
2289 Constraints.size() == Exprs.size() &&
2290 "Input operand size mismatch!");
2291
2292 unsigned NumInputs = Names.size() - NumOutputs;
2293
2294 // Parse the clobbers, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002295 if (AteExtraColon || Tok.is(tok::colon)) {
2296 if (!AteExtraColon)
2297 ConsumeToken();
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002298
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002299 // Parse the asm-string list for clobbers if present.
2300 if (Tok.isNot(tok::r_paren)) {
2301 while (1) {
John McCalldadc5752010-08-24 06:29:42 +00002302 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002303
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002304 if (Clobber.isInvalid())
2305 break;
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002306
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002307 Clobbers.push_back(Clobber.release());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002308
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002309 if (Tok.isNot(tok::comma)) break;
2310 ConsumeToken();
2311 }
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002312 }
2313 }
2314
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002315 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002316 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2317 NumInputs, Names.data(), Constraints, Exprs,
2318 AsmString.take(), Clobbers,
2319 T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002320}
2321
2322/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002323/// asm-statement, assuming the leading ':' token was eaten.
Chris Lattner0116c472006-08-15 06:03:28 +00002324///
2325/// [GNU] asm-operands:
2326/// asm-operand
2327/// asm-operands ',' asm-operand
2328///
2329/// [GNU] asm-operand:
2330/// asm-string-literal '(' expression ')'
2331/// '[' identifier ']' asm-string-literal '(' expression ')'
2332///
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00002333//
2334// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002335bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieu2bd04012011-09-09 02:00:50 +00002336 SmallVectorImpl<Expr *> &Constraints,
2337 SmallVectorImpl<Expr *> &Exprs) {
Chris Lattner0116c472006-08-15 06:03:28 +00002338 // 'asm-operands' isn't present?
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002339 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002340 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002341
2342 while (1) {
Chris Lattner0116c472006-08-15 06:03:28 +00002343 // Read the [id] if present.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002344 if (Tok.is(tok::l_square)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002345 BalancedDelimiterTracker T(*this, tok::l_square);
2346 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00002347
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002348 if (Tok.isNot(tok::identifier)) {
Chris Lattner0116c472006-08-15 06:03:28 +00002349 Diag(Tok, diag::err_expected_ident);
2350 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002351 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002352 }
Mike Stump11289f42009-09-09 15:08:12 +00002353
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002354 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner645ff3f2007-10-29 04:06:22 +00002355 ConsumeToken();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002356
Anders Carlsson9a020f92010-01-30 22:25:16 +00002357 Names.push_back(II);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002358 T.consumeClose();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002359 } else
Anders Carlsson9a020f92010-01-30 22:25:16 +00002360 Names.push_back(0);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002361
John McCalldadc5752010-08-24 06:29:42 +00002362 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002363 if (Constraint.isInvalid()) {
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002364 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002365 return true;
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002366 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002367 Constraints.push_back(Constraint.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002368
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002369 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002370 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Chris Lattner0116c472006-08-15 06:03:28 +00002371 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002372 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002373 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002374
Chris Lattner0116c472006-08-15 06:03:28 +00002375 // Read the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002376 BalancedDelimiterTracker T(*this, tok::l_paren);
2377 T.consumeOpen();
John McCalldadc5752010-08-24 06:29:42 +00002378 ExprResult Res(ParseExpression());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002379 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002380 if (Res.isInvalid()) {
Chris Lattner0116c472006-08-15 06:03:28 +00002381 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002382 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002383 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002384 Exprs.push_back(Res.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002385 // Eat the comma and continue parsing if it exists.
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002386 if (Tok.isNot(tok::comma)) return false;
Chris Lattner0116c472006-08-15 06:03:28 +00002387 ConsumeToken();
2388 }
2389}
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002390
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002391Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002392 assert(Tok.is(tok::l_brace));
2393 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002394
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00002395 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00002396 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002397 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002398 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002399 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002400
John McCallfaf5fb42010-08-26 23:41:50 +00002401 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2402 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002403
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002404 // Do not enter a scope for the brace, as the arguments are in the same scope
2405 // (the function body) as the body itself. Instead, just read the statement
2406 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002407 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002408
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002409 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002410 if (FnBody.isInvalid()) {
2411 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002412 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002413 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002414
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002415 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002416 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002417}
Sebastian Redlb219c902008-12-21 16:41:36 +00002418
Sebastian Redla7b98a72009-04-26 20:35:05 +00002419/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2420///
2421/// function-try-block:
2422/// 'try' ctor-initializer[opt] compound-statement handler-seq
2423///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002424Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002425 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2426 SourceLocation TryLoc = ConsumeToken();
2427
John McCallfaf5fb42010-08-26 23:41:50 +00002428 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2429 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002430
2431 // Constructor initializer list?
2432 if (Tok.is(tok::colon))
2433 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002434 else
2435 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002436
Richard Smith1ab34b32012-11-19 21:13:18 +00002437 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2438 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002439 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002440 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002441 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002442
Sebastian Redld98ecd62009-04-26 21:08:36 +00002443 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002444 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00002445 // If we failed to parse the try-catch, we just give the function an empty
2446 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002447 if (FnBody.isInvalid()) {
2448 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002449 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002450 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002451
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002452 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002453 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002454}
2455
Erik Verbruggen6e922512012-04-12 10:11:59 +00002456bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002457 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00002458 assert(SkipFunctionBodies &&
2459 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002460
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002461 if (!PP.isCodeCompletionEnabled()) {
2462 ConsumeBrace();
2463 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false);
2464 return true;
2465 }
2466
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002467 // We're in code-completion mode. Skip parsing for all function bodies unless
2468 // the body contains the code-completion point.
2469 TentativeParsingAction PA(*this);
2470 ConsumeBrace();
2471 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002472 /*StopAtCodeCompletion=*/true)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002473 PA.Commit();
2474 return true;
2475 }
2476
2477 PA.Revert();
2478 return false;
2479}
2480
Sebastian Redlb219c902008-12-21 16:41:36 +00002481/// ParseCXXTryBlock - Parse a C++ try-block.
2482///
2483/// try-block:
2484/// 'try' compound-statement handler-seq
2485///
Richard Smithc202b282012-04-14 00:33:13 +00002486StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002487 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2488
2489 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002490 return ParseCXXTryBlockCommon(TryLoc);
2491}
2492
2493/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2494/// function-try-block.
2495///
2496/// try-block:
2497/// 'try' compound-statement handler-seq
2498///
2499/// function-try-block:
2500/// 'try' ctor-initializer[opt] compound-statement handler-seq
2501///
2502/// handler-seq:
2503/// handler handler-seq[opt]
2504///
John Wiegley1c0675e2011-04-28 01:08:34 +00002505/// [Borland] try-block:
2506/// 'try' compound-statement seh-except-block
2507/// 'try' compound-statment seh-finally-block
2508///
David Blaikie1c9c9042012-11-10 01:04:23 +00002509StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002510 if (Tok.isNot(tok::l_brace))
2511 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Alexis Hunt96d5c762009-11-21 08:43:09 +00002512 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002513
2514 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikie3403feb2012-11-13 18:51:45 +00002515 Scope::DeclScope | Scope::TryScope |
2516 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002517 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002518 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002519
John Wiegley1c0675e2011-04-28 01:08:34 +00002520 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002521
Richard Smithc202b282012-04-14 00:33:13 +00002522 if ((Tok.is(tok::identifier) &&
2523 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2524 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002525 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2526 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002527 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002528 SourceLocation Loc = ConsumeToken();
2529 Handler = ParseSEHExceptBlock(Loc);
2530 }
2531 else {
2532 SourceLocation Loc = ConsumeToken();
2533 Handler = ParseSEHFinallyBlock(Loc);
2534 }
2535 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002536 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002537
John Wiegley1c0675e2011-04-28 01:08:34 +00002538 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2539 TryLoc,
2540 TryBlock.take(),
2541 Handler.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002542 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002543 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002544 StmtVector Handlers;
Richard Smithc202b282012-04-14 00:33:13 +00002545 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002546 MaybeParseCXX11Attributes(attrs);
John Wiegley1c0675e2011-04-28 01:08:34 +00002547 ProhibitAttributes(attrs);
Sebastian Redlb219c902008-12-21 16:41:36 +00002548
John Wiegley1c0675e2011-04-28 01:08:34 +00002549 if (Tok.isNot(tok::kw_catch))
2550 return StmtError(Diag(Tok, diag::err_expected_catch));
2551 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002552 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002553 if (!Handler.isInvalid())
2554 Handlers.push_back(Handler.release());
2555 }
2556 // Don't bother creating the full statement if we don't have any usable
2557 // handlers.
2558 if (Handlers.empty())
2559 return StmtError();
2560
Robert Wilhelmcafda822013-08-22 09:20:03 +00002561 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002562 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002563}
2564
2565/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2566///
Richard Smith1dba27c2013-01-29 09:02:09 +00002567/// handler:
2568/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002569///
Richard Smith1dba27c2013-01-29 09:02:09 +00002570/// exception-declaration:
2571/// attribute-specifier-seq[opt] type-specifier-seq declarator
2572/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2573/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002574///
David Blaikie1c9c9042012-11-10 01:04:23 +00002575StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002576 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2577
2578 SourceLocation CatchLoc = ConsumeToken();
2579
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002580 BalancedDelimiterTracker T(*this, tok::l_paren);
2581 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redlb219c902008-12-21 16:41:36 +00002582 return StmtError();
2583
2584 // C++ 3.3.2p3:
2585 // The name in a catch exception-declaration is local to the handler and
2586 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002587 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002588 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002589
2590 // exception-declaration is equivalent to '...' or a parameter-declaration
2591 // without default arguments.
John McCall48871652010-08-21 09:40:31 +00002592 Decl *ExceptionDecl = 0;
Sebastian Redlb219c902008-12-21 16:41:36 +00002593 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002594 ParsedAttributesWithRange Attributes(AttrFactory);
2595 MaybeParseCXX11Attributes(Attributes);
2596
John McCall084e83d2011-03-24 11:26:52 +00002597 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002598 DS.takeAttributesFrom(Attributes);
2599
Sebastian Redl54c04d42008-12-22 19:15:10 +00002600 if (ParseCXXTypeSpecifierSeq(DS))
2601 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002602
Sebastian Redlb219c902008-12-21 16:41:36 +00002603 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2604 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002605 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002606 } else
2607 ConsumeToken();
2608
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002609 T.consumeClose();
2610 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002611 return StmtError();
2612
2613 if (Tok.isNot(tok::l_brace))
2614 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2615
Alexis Hunt96d5c762009-11-21 08:43:09 +00002616 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002617 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002618 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002619 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002620
John McCallb268a282010-08-23 23:25:46 +00002621 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002622}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002623
2624void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002625 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002626 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002627 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002628
Douglas Gregor43edb322011-10-24 22:31:10 +00002629 // Handle dependent statements by parsing the braces as a compound statement.
2630 // This is not the same behavior as Visual C++, which don't treat this as a
2631 // compound statement, but for Clang's type checking we can't have anything
2632 // inside these braces escaping to the surrounding code.
2633 if (Result.Behavior == IEB_Dependent) {
2634 if (!Tok.is(tok::l_brace)) {
2635 Diag(Tok, diag::err_expected_lbrace);
Richard Smithc202b282012-04-14 00:33:13 +00002636 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002637 }
Richard Smithc202b282012-04-14 00:33:13 +00002638
2639 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002640 if (Compound.isInvalid())
2641 return;
Richard Smithc202b282012-04-14 00:33:13 +00002642
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002643 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2644 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002645 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002646 Result.Name,
2647 Compound.get());
2648 if (DepResult.isUsable())
2649 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002650 return;
2651 }
Richard Smithc202b282012-04-14 00:33:13 +00002652
Douglas Gregor43edb322011-10-24 22:31:10 +00002653 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2654 if (Braces.consumeOpen()) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002655 Diag(Tok, diag::err_expected_lbrace);
2656 return;
2657 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002658
Douglas Gregor43edb322011-10-24 22:31:10 +00002659 switch (Result.Behavior) {
2660 case IEB_Parse:
2661 // Parse the statements below.
2662 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002663
Douglas Gregor43edb322011-10-24 22:31:10 +00002664 case IEB_Dependent:
2665 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002666
Douglas Gregor43edb322011-10-24 22:31:10 +00002667 case IEB_Skip:
2668 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002669 return;
2670 }
2671
2672 // Condition is true, parse the statements.
2673 while (Tok.isNot(tok::r_brace)) {
2674 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2675 if (R.isUsable())
2676 Stmts.push_back(R.release());
2677 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002678 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002679}