blob: ef1ab89b8c956637399ceb9f5aec0037e7298804 [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>())
Kaelyn Uhrain07e62722013-10-01 22:00:28 +0000132 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
Kaelyn Uhrain46b6cdc2013-09-27 19:40:16 +0000133 if (NextToken.is(tok::equal))
134 return candidate.getCorrectionDeclAs<VarDecl>();
Kaelyn Uhrain30943ce2013-09-27 23:54:23 +0000135 if (NextToken.is(tok::period) &&
136 candidate.getCorrectionDeclAs<NamespaceDecl>())
137 return false;
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000138 return CorrectionCandidateCallback::ValidateCandidate(candidate);
139 }
140
141private:
142 Token NextToken;
143};
144}
145
Richard Smithc202b282012-04-14 00:33:13 +0000146StmtResult
147Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
148 bool OnlyStatement, SourceLocation *TrailingElseLoc,
149 ParsedAttributesWithRange &Attrs) {
150 const char *SemiError = 0;
151 StmtResult Res;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000152
Chris Lattner503fadc2006-08-10 05:45:44 +0000153 // Cases in this switch statement should fall through if the parser expects
154 // the token to end in a semicolon (in which case SemiError should be set),
155 // or they directly 'return;' if not.
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000156Retry:
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000157 tok::TokenKind Kind = Tok.getKind();
158 SourceLocation AtLoc;
159 switch (Kind) {
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000160 case tok::at: // May be a @try or @throw statement
161 {
Richard Smithc202b282012-04-14 00:33:13 +0000162 ProhibitAttributes(Attrs); // TODO: is it correct?
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000163 AtLoc = ConsumeToken(); // consume @
Sebastian Redlbab9a4b2008-12-11 20:12:42 +0000164 return ParseObjCAtStatement(AtLoc);
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000165 }
Fariborz Jahanian62fd2b42007-09-19 19:14:32 +0000166
Douglas Gregor9d64c5e2009-09-21 20:51:25 +0000167 case tok::code_completion:
John McCallfaf5fb42010-08-26 23:41:50 +0000168 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000169 cutOffParsing();
170 return StmtError();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000171
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000172 case tok::identifier: {
173 Token Next = NextToken();
174 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000175 // identifier ':' statement
Richard Smithc202b282012-04-14 00:33:13 +0000176 return ParseLabeledStatement(Attrs);
Argyrios Kyrtzidis07b8b632008-07-12 21:04:42 +0000177 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000178
Richard Smith4f605af2012-08-18 00:55:03 +0000179 // Look up the identifier, and typo-correct it to a keyword if it's not
180 // found.
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000181 if (Next.isNot(tok::coloncolon)) {
Richard Smith4f605af2012-08-18 00:55:03 +0000182 // Try to limit which sets of keywords should be included in typo
183 // correction based on what the next token is.
Kaelyn Uhrain3dfff192013-09-27 19:40:12 +0000184 StatementFilterCCC Validator(Next);
185 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
Richard Smith4f605af2012-08-18 00:55:03 +0000186 == ANK_Error) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000187 // Handle errors here by skipping up to the next semicolon or '}', and
188 // eat the semicolon if that's what stopped us.
189 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
190 if (Tok.is(tok::semi))
191 ConsumeToken();
192 return StmtError();
Richard Smith4f605af2012-08-18 00:55:03 +0000193 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000194
Richard Smith4f605af2012-08-18 00:55:03 +0000195 // If the identifier was typo-corrected, try again.
196 if (Tok.isNot(tok::identifier))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000197 goto Retry;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000198 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000199
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000200 // Fall through
201 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000202
Chris Lattner803802d2009-03-24 17:04:48 +0000203 default: {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000204 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
Chris Lattner49836b42009-04-02 04:16:50 +0000205 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Ted Kremenek5eec2b02010-11-10 05:59:39 +0000206 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
Richard Smithc202b282012-04-14 00:33:13 +0000207 DeclEnd, Attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000208 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
Chris Lattner803802d2009-03-24 17:04:48 +0000209 }
210
211 if (Tok.is(tok::r_brace)) {
Chris Lattnerf8afb622006-08-10 18:26:31 +0000212 Diag(Tok, diag::err_expected_statement);
Sebastian Redl042ad952008-12-11 19:30:53 +0000213 return StmtError();
Chris Lattnerf8afb622006-08-10 18:26:31 +0000214 }
Mike Stump11289f42009-09-09 15:08:12 +0000215
Richard Smithc202b282012-04-14 00:33:13 +0000216 return ParseExprStatement();
Chris Lattner803802d2009-03-24 17:04:48 +0000217 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000218
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000219 case tok::kw_case: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000220 return ParseCaseStatement();
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000221 case tok::kw_default: // C99 6.8.1: labeled-statement
Richard Smithc202b282012-04-14 00:33:13 +0000222 return ParseDefaultStatement();
Sebastian Redl042ad952008-12-11 19:30:53 +0000223
Chris Lattner9075bd72006-08-10 04:59:57 +0000224 case tok::l_brace: // C99 6.8.2: compound-statement
Richard Smithc202b282012-04-14 00:33:13 +0000225 return ParseCompoundStatement();
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000226 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +0000227 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
228 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000229 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000230
Chris Lattner9075bd72006-08-10 04:59:57 +0000231 case tok::kw_if: // C99 6.8.4.1: if-statement
Richard Smithc202b282012-04-14 00:33:13 +0000232 return ParseIfStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000233 case tok::kw_switch: // C99 6.8.4.2: switch-statement
Richard Smithc202b282012-04-14 00:33:13 +0000234 return ParseSwitchStatement(TrailingElseLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000235
Chris Lattner9075bd72006-08-10 04:59:57 +0000236 case tok::kw_while: // C99 6.8.5.1: while-statement
Richard Smithc202b282012-04-14 00:33:13 +0000237 return ParseWhileStatement(TrailingElseLoc);
Chris Lattner9075bd72006-08-10 04:59:57 +0000238 case tok::kw_do: // C99 6.8.5.2: do-statement
Richard Smithc202b282012-04-14 00:33:13 +0000239 Res = ParseDoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000240 SemiError = "do/while";
Chris Lattner9075bd72006-08-10 04:59:57 +0000241 break;
242 case tok::kw_for: // C99 6.8.5.3: for-statement
Richard Smithc202b282012-04-14 00:33:13 +0000243 return ParseForStatement(TrailingElseLoc);
Chris Lattner503fadc2006-08-10 05:45:44 +0000244
245 case tok::kw_goto: // C99 6.8.6.1: goto-statement
Richard Smithc202b282012-04-14 00:33:13 +0000246 Res = ParseGotoStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000247 SemiError = "goto";
Chris Lattner9075bd72006-08-10 04:59:57 +0000248 break;
Chris Lattner503fadc2006-08-10 05:45:44 +0000249 case tok::kw_continue: // C99 6.8.6.2: continue-statement
Richard Smithc202b282012-04-14 00:33:13 +0000250 Res = ParseContinueStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000251 SemiError = "continue";
Chris Lattner503fadc2006-08-10 05:45:44 +0000252 break;
253 case tok::kw_break: // C99 6.8.6.3: break-statement
Richard Smithc202b282012-04-14 00:33:13 +0000254 Res = ParseBreakStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000255 SemiError = "break";
Chris Lattner503fadc2006-08-10 05:45:44 +0000256 break;
257 case tok::kw_return: // C99 6.8.6.4: return-statement
Richard Smithc202b282012-04-14 00:33:13 +0000258 Res = ParseReturnStatement();
Chris Lattner34a95662009-06-14 00:07:48 +0000259 SemiError = "return";
Chris Lattner503fadc2006-08-10 05:45:44 +0000260 break;
Sebastian Redl042ad952008-12-11 19:30:53 +0000261
Sebastian Redlb219c902008-12-21 16:41:36 +0000262 case tok::kw_asm: {
Richard Smithc202b282012-04-14 00:33:13 +0000263 ProhibitAttributes(Attrs);
Steve Naroffb2c80c72008-02-07 03:50:06 +0000264 bool msAsm = false;
265 Res = ParseAsmStatement(msAsm);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +0000266 Res = Actions.ActOnFinishFullStmt(Res.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000267 if (msAsm) return Res;
Chris Lattner34a95662009-06-14 00:07:48 +0000268 SemiError = "asm";
Chris Lattner0116c472006-08-15 06:03:28 +0000269 break;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000270 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000271
Sebastian Redlb219c902008-12-21 16:41:36 +0000272 case tok::kw_try: // C++ 15: try-block
Richard Smithc202b282012-04-14 00:33:13 +0000273 return ParseCXXTryBlock();
John Wiegley1c0675e2011-04-28 01:08:34 +0000274
275 case tok::kw___try:
Richard Smithc202b282012-04-14 00:33:13 +0000276 ProhibitAttributes(Attrs); // TODO: is it correct?
277 return ParseSEHTryBlock();
Eli Friedmanec52f922012-02-23 23:47:16 +0000278
279 case tok::annot_pragma_vis:
Richard Smithc202b282012-04-14 00:33:13 +0000280 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000281 HandlePragmaVisibility();
282 return StmtEmpty();
283
284 case tok::annot_pragma_pack:
Richard Smithc202b282012-04-14 00:33:13 +0000285 ProhibitAttributes(Attrs);
Eli Friedmanec52f922012-02-23 23:47:16 +0000286 HandlePragmaPack();
287 return StmtEmpty();
Eli Friedman68be1642012-10-04 02:36:51 +0000288
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000289 case tok::annot_pragma_msstruct:
290 ProhibitAttributes(Attrs);
291 HandlePragmaMSStruct();
292 return StmtEmpty();
293
Eli Friedmanae8ee252012-10-08 23:52:38 +0000294 case tok::annot_pragma_align:
295 ProhibitAttributes(Attrs);
296 HandlePragmaAlign();
297 return StmtEmpty();
298
Eli Friedmanbbbbac62012-10-09 22:46:54 +0000299 case tok::annot_pragma_weak:
300 ProhibitAttributes(Attrs);
301 HandlePragmaWeak();
302 return StmtEmpty();
303
304 case tok::annot_pragma_weakalias:
305 ProhibitAttributes(Attrs);
306 HandlePragmaWeakAlias();
307 return StmtEmpty();
308
309 case tok::annot_pragma_redefine_extname:
310 ProhibitAttributes(Attrs);
311 HandlePragmaRedefineExtname();
312 return StmtEmpty();
313
Eli Friedman68be1642012-10-04 02:36:51 +0000314 case tok::annot_pragma_fp_contract:
Lang Hamesa930e712012-10-21 01:10:01 +0000315 Diag(Tok, diag::err_pragma_fp_contract_scope);
316 ConsumeToken();
317 return StmtError();
318
Eli Friedman68be1642012-10-04 02:36:51 +0000319 case tok::annot_pragma_opencl_extension:
320 ProhibitAttributes(Attrs);
321 HandlePragmaOpenCLExtension();
322 return StmtEmpty();
Alexey Bataeva769e072013-03-22 06:34:35 +0000323
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000324 case tok::annot_pragma_captured:
Richard Smith12a41bd2013-09-16 21:17:44 +0000325 ProhibitAttributes(Attrs);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000326 return HandlePragmaCaptured();
327
Alexey Bataeva769e072013-03-22 06:34:35 +0000328 case tok::annot_pragma_openmp:
Richard Smith12a41bd2013-09-16 21:17:44 +0000329 ProhibitAttributes(Attrs);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +0000330 return ParseOpenMPDeclarativeOrExecutableDirective();
331
Sebastian Redlb219c902008-12-21 16:41:36 +0000332 }
333
Chris Lattner503fadc2006-08-10 05:45:44 +0000334 // If we reached this code, the statement must end in a semicolon.
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000335 if (Tok.is(tok::semi)) {
Chris Lattner503fadc2006-08-10 05:45:44 +0000336 ConsumeToken();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000337 } else if (!Res.isInvalid()) {
Chris Lattner8e3eed02009-06-14 00:23:56 +0000338 // If the result was valid, then we do want to diagnose this. Use
339 // ExpectAndConsume to emit the diagnostic, even though we know it won't
340 // succeed.
341 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
Chris Lattner0046de12008-11-13 18:52:53 +0000342 // Skip until we see a } or ;, but don't eat it.
343 SkipUntil(tok::r_brace, true, true);
Chris Lattner503fadc2006-08-10 05:45:44 +0000344 }
Mike Stump11289f42009-09-09 15:08:12 +0000345
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000346 return Res;
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000347}
348
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000349/// \brief Parse an expression statement.
Richard Smithc202b282012-04-14 00:33:13 +0000350StmtResult Parser::ParseExprStatement() {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000351 // If a case keyword is missing, this is where it should be inserted.
352 Token OldToken = Tok;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000353
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000354 // expression[opt] ';'
Douglas Gregorda6c89d2011-04-27 06:18:01 +0000355 ExprResult Expr(ParseExpression());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000356 if (Expr.isInvalid()) {
357 // If the expression is invalid, skip ahead to the next semicolon or '}'.
358 // Not doing this opens us up to the possibility of infinite loops if
359 // ParseExpression does not consume any tokens.
360 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
361 if (Tok.is(tok::semi))
362 ConsumeToken();
John McCalleaef89b2013-03-22 02:10:40 +0000363 return Actions.ActOnExprStmtError();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000364 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000365
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000366 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
367 Actions.CheckCaseExpression(Expr.get())) {
368 // If a constant expression is followed by a colon inside a switch block,
369 // suggest a missing case keyword.
370 Diag(OldToken, diag::err_expected_case_before_expression)
371 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000372
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000373 // Recover parsing as a case statement.
Richard Smithc202b282012-04-14 00:33:13 +0000374 return ParseCaseStatement(/*MissingCase=*/true, Expr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000375 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000376
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000377 // Otherwise, eat the semicolon.
378 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000379 return Actions.ActOnExprStmt(Expr);
John Wiegley1c0675e2011-04-28 01:08:34 +0000380}
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000381
Richard Smithc202b282012-04-14 00:33:13 +0000382StmtResult Parser::ParseSEHTryBlock() {
John Wiegley1c0675e2011-04-28 01:08:34 +0000383 assert(Tok.is(tok::kw___try) && "Expected '__try'");
384 SourceLocation Loc = ConsumeToken();
385 return ParseSEHTryBlockCommon(Loc);
386}
387
388/// ParseSEHTryBlockCommon
389///
390/// seh-try-block:
391/// '__try' compound-statement seh-handler
392///
393/// seh-handler:
394/// seh-except-block
395/// seh-finally-block
396///
397StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
398 if(Tok.isNot(tok::l_brace))
399 return StmtError(Diag(Tok,diag::err_expected_lbrace));
400
Joao Matos566359c2012-09-04 17:49:35 +0000401 StmtResult TryBlock(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000402 if(TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000403 return TryBlock;
John Wiegley1c0675e2011-04-28 01:08:34 +0000404
405 StmtResult Handler;
Richard Smithc202b282012-04-14 00:33:13 +0000406 if (Tok.is(tok::identifier) &&
Douglas Gregor60060d62011-10-21 03:57:52 +0000407 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000408 SourceLocation Loc = ConsumeToken();
409 Handler = ParseSEHExceptBlock(Loc);
410 } else if (Tok.is(tok::kw___finally)) {
411 SourceLocation Loc = ConsumeToken();
412 Handler = ParseSEHFinallyBlock(Loc);
413 } else {
414 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
415 }
416
417 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000418 return Handler;
John Wiegley1c0675e2011-04-28 01:08:34 +0000419
420 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
421 TryLoc,
422 TryBlock.take(),
423 Handler.take());
424}
425
426/// ParseSEHExceptBlock - Handle __except
427///
428/// seh-except-block:
429/// '__except' '(' seh-filter-expression ')' compound-statement
430///
431StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
432 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
433 raii2(Ident___exception_code, false),
434 raii3(Ident_GetExceptionCode, false);
435
436 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
437 return StmtError();
438
439 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
440
David Blaikiebbafb8a2012-03-11 07:00:24 +0000441 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000442 Ident__exception_info->setIsPoisoned(false);
443 Ident___exception_info->setIsPoisoned(false);
444 Ident_GetExceptionInfo->setIsPoisoned(false);
445 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000446 ExprResult FilterExpr(ParseExpression());
Francois Pichetbfaf4772011-04-28 03:14:31 +0000447
David Blaikiebbafb8a2012-03-11 07:00:24 +0000448 if (getLangOpts().Borland) {
Francois Pichetbfaf4772011-04-28 03:14:31 +0000449 Ident__exception_info->setIsPoisoned(true);
450 Ident___exception_info->setIsPoisoned(true);
451 Ident_GetExceptionInfo->setIsPoisoned(true);
452 }
John Wiegley1c0675e2011-04-28 01:08:34 +0000453
454 if(FilterExpr.isInvalid())
455 return StmtError();
456
457 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
458 return StmtError();
459
Richard Smithc202b282012-04-14 00:33:13 +0000460 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000461
462 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000463 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000464
465 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
466}
467
468/// ParseSEHFinallyBlock - Handle __finally
469///
470/// seh-finally-block:
471/// '__finally' compound-statement
472///
473StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
474 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
475 raii2(Ident___abnormal_termination, false),
476 raii3(Ident_AbnormalTermination, false);
477
Richard Smithc202b282012-04-14 00:33:13 +0000478 StmtResult Block(ParseCompoundStatement());
John Wiegley1c0675e2011-04-28 01:08:34 +0000479 if(Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000480 return Block;
John Wiegley1c0675e2011-04-28 01:08:34 +0000481
482 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000483}
484
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000485/// ParseLabeledStatement - We have an identifier and a ':' after it.
Chris Lattner6dfd9782006-08-10 18:31:37 +0000486///
487/// labeled-statement:
488/// identifier ':' statement
Chris Lattnere37e2332006-08-15 04:50:22 +0000489/// [GNU] identifier ':' attributes[opt] statement
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000490///
Richard Smithc202b282012-04-14 00:33:13 +0000491StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000492 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
493 "Not an identifier!");
494
495 Token IdentTok = Tok; // Save the whole token.
496 ConsumeToken(); // eat the identifier.
497
498 assert(Tok.is(tok::colon) && "Not a label!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000499
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000500 // identifier ':' statement
501 SourceLocation ColonLoc = ConsumeToken();
502
Richard Smithc202b282012-04-14 00:33:13 +0000503 // Read label attributes, if present. attrs will contain both C++11 and GNU
504 // attributes (if present) after this point.
John McCall53fa7142010-12-24 02:08:15 +0000505 MaybeParseGNUAttributes(attrs);
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000506
John McCalldadc5752010-08-24 06:29:42 +0000507 StmtResult SubStmt(ParseStatement());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000508
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000509 // Broken substmt shouldn't prevent the label from being added to the AST.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000510 if (SubStmt.isInvalid())
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000511 SubStmt = Actions.ActOnNullStmt(ColonLoc);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000512
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000513 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
514 IdentTok.getLocation());
Richard Smithc202b282012-04-14 00:33:13 +0000515 if (AttributeList *Attrs = attrs.getList()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000516 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
Richard Smithc202b282012-04-14 00:33:13 +0000517 attrs.clear();
518 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000519
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000520 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
521 SubStmt.get());
Argyrios Kyrtzidis832e8982008-07-09 22:53:07 +0000522}
Chris Lattnerf8afb622006-08-10 18:26:31 +0000523
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000524/// ParseCaseStatement
525/// labeled-statement:
526/// 'case' constant-expression ':' statement
Chris Lattner476c3ad2006-08-13 22:09:58 +0000527/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
Chris Lattner8693a512006-08-13 21:54:02 +0000528///
Richard Smithc202b282012-04-14 00:33:13 +0000529StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
Richard Smithd4257d82011-04-21 22:48:40 +0000530 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattner34a22092009-03-04 04:23:07 +0000532 // It is very very common for code to contain many case statements recursively
533 // nested, as in (but usually without indentation):
534 // case 1:
535 // case 2:
536 // case 3:
537 // case 4:
538 // case 5: etc.
539 //
540 // Parsing this naively works, but is both inefficient and can cause us to run
541 // out of stack space in our recursive descent parser. As a special case,
Chris Lattner2b19a6582009-03-04 18:24:58 +0000542 // flatten this recursion into an iterative loop. This is complex and gross,
Chris Lattner34a22092009-03-04 04:23:07 +0000543 // but all the grossness is constrained to ParseCaseStatement (and some
544 // wierdness in the actions), so this is just local grossness :).
Mike Stump11289f42009-09-09 15:08:12 +0000545
Chris Lattner34a22092009-03-04 04:23:07 +0000546 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
547 // example above.
John McCalldadc5752010-08-24 06:29:42 +0000548 StmtResult TopLevelCase(true);
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattner34a22092009-03-04 04:23:07 +0000550 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
551 // gets updated each time a new case is parsed, and whose body is unset so
552 // far. When parsing 'case 4', this is the 'case 3' node.
Richard Trieu3481fcd2011-09-09 02:16:15 +0000553 Stmt *DeepestParsedCaseStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattner34a22092009-03-04 04:23:07 +0000555 // While we have case statements, eat and stack them.
David Majnemer0ac67fa2011-06-13 05:50:12 +0000556 SourceLocation ColonLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000557 do {
Richard Trieu2c850c02011-04-21 21:44:26 +0000558 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
559 ConsumeToken(); // eat the 'case'.
Mike Stump11289f42009-09-09 15:08:12 +0000560
Douglas Gregord328d572009-09-21 18:10:23 +0000561 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +0000562 Actions.CodeCompleteCase(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000563 cutOffParsing();
564 return StmtError();
Douglas Gregord328d572009-09-21 18:10:23 +0000565 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000566
Chris Lattner125c0ee2009-12-10 00:38:54 +0000567 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
568 /// Disable this form of error recovery while we're parsing the case
569 /// expression.
570 ColonProtectionRAIIObject ColonProtection(*this);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000571
Richard Trieu2c850c02011-04-21 21:44:26 +0000572 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
573 MissingCase = false;
Chris Lattner34a22092009-03-04 04:23:07 +0000574 if (LHS.isInvalid()) {
Chris Lattner476c3ad2006-08-13 22:09:58 +0000575 SkipUntil(tok::colon);
Sebastian Redl042ad952008-12-11 19:30:53 +0000576 return StmtError();
Chris Lattner476c3ad2006-08-13 22:09:58 +0000577 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000578
Chris Lattner34a22092009-03-04 04:23:07 +0000579 // GNU case range extension.
580 SourceLocation DotDotDotLoc;
John McCalldadc5752010-08-24 06:29:42 +0000581 ExprResult RHS;
Chris Lattner34a22092009-03-04 04:23:07 +0000582 if (Tok.is(tok::ellipsis)) {
583 Diag(Tok, diag::ext_gnu_case_range);
584 DotDotDotLoc = ConsumeToken();
Sebastian Redl042ad952008-12-11 19:30:53 +0000585
Chris Lattner34a22092009-03-04 04:23:07 +0000586 RHS = ParseConstantExpression();
587 if (RHS.isInvalid()) {
588 SkipUntil(tok::colon);
589 return StmtError();
590 }
591 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000592
Chris Lattner125c0ee2009-12-10 00:38:54 +0000593 ColonProtection.restore();
Sebastian Redl042ad952008-12-11 19:30:53 +0000594
John McCall0140bfe2011-01-22 09:28:32 +0000595 if (Tok.is(tok::colon)) {
596 ColonLoc = ConsumeToken();
597
598 // Treat "case blah;" as a typo for "case blah:".
599 } else if (Tok.is(tok::semi)) {
600 ColonLoc = ConsumeToken();
601 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
602 << FixItHint::CreateReplacement(ColonLoc, ":");
603 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000604 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
605 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
606 << FixItHint::CreateInsertion(ExpectedLoc, ":");
607 ColonLoc = ExpectedLoc;
Chris Lattner34a22092009-03-04 04:23:07 +0000608 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000609
John McCalldadc5752010-08-24 06:29:42 +0000610 StmtResult Case =
John McCallb268a282010-08-23 23:25:46 +0000611 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
612 RHS.get(), ColonLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000613
Chris Lattner34a22092009-03-04 04:23:07 +0000614 // If we had a sema error parsing this case, then just ignore it and
615 // continue parsing the sub-stmt.
616 if (Case.isInvalid()) {
617 if (TopLevelCase.isInvalid()) // No parsed case stmts.
618 return ParseStatement();
619 // Otherwise, just don't add it as a nested case.
620 } else {
621 // If this is the first case statement we parsed, it becomes TopLevelCase.
622 // Otherwise we link it into the current chain.
John McCall37ad5512010-08-23 06:44:23 +0000623 Stmt *NextDeepest = Case.get();
Chris Lattner34a22092009-03-04 04:23:07 +0000624 if (TopLevelCase.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000625 TopLevelCase = Case;
Chris Lattner34a22092009-03-04 04:23:07 +0000626 else
John McCallb268a282010-08-23 23:25:46 +0000627 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
Chris Lattner34a22092009-03-04 04:23:07 +0000628 DeepestParsedCaseStmt = NextDeepest;
629 }
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattner34a22092009-03-04 04:23:07 +0000631 // Handle all case statements.
632 } while (Tok.is(tok::kw_case));
Mike Stump11289f42009-09-09 15:08:12 +0000633
Chris Lattner34a22092009-03-04 04:23:07 +0000634 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
Mike Stump11289f42009-09-09 15:08:12 +0000635
Chris Lattner34a22092009-03-04 04:23:07 +0000636 // If we found a non-case statement, start by parsing it.
John McCalldadc5752010-08-24 06:29:42 +0000637 StmtResult SubStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000638
Chris Lattner34a22092009-03-04 04:23:07 +0000639 if (Tok.isNot(tok::r_brace)) {
640 SubStmt = ParseStatement();
641 } else {
642 // Nicely diagnose the common error "switch (X) { case 4: }", which is
643 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000644 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000645 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
646 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
Chris Lattner34a22092009-03-04 04:23:07 +0000647 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000648 }
Mike Stump11289f42009-09-09 15:08:12 +0000649
Chris Lattner34a22092009-03-04 04:23:07 +0000650 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000651 if (SubStmt.isInvalid())
Chris Lattner34a22092009-03-04 04:23:07 +0000652 SubStmt = Actions.ActOnNullStmt(SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000653
Chris Lattner34a22092009-03-04 04:23:07 +0000654 // Install the body into the most deeply-nested case.
John McCallb268a282010-08-23 23:25:46 +0000655 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
Sebastian Redl042ad952008-12-11 19:30:53 +0000656
Chris Lattner34a22092009-03-04 04:23:07 +0000657 // Return the top level parsed statement tree.
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000658 return TopLevelCase;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000659}
660
661/// ParseDefaultStatement
662/// labeled-statement:
663/// 'default' ':' statement
664/// Note that this does not parse the 'statement' at the end.
665///
Richard Smithc202b282012-04-14 00:33:13 +0000666StmtResult Parser::ParseDefaultStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000667 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000668 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000669
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000670 SourceLocation ColonLoc;
John McCall0140bfe2011-01-22 09:28:32 +0000671 if (Tok.is(tok::colon)) {
672 ColonLoc = ConsumeToken();
673
674 // Treat "default;" as a typo for "default:".
675 } else if (Tok.is(tok::semi)) {
676 ColonLoc = ConsumeToken();
677 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
678 << FixItHint::CreateReplacement(ColonLoc, ":");
679 } else {
Douglas Gregor0d0a9652010-12-23 22:56:40 +0000680 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
681 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
682 << FixItHint::CreateInsertion(ExpectedLoc, ":");
683 ColonLoc = ExpectedLoc;
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000684 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000685
Richard Smith1002d102012-02-17 01:35:32 +0000686 StmtResult SubStmt;
687
688 if (Tok.isNot(tok::r_brace)) {
689 SubStmt = ParseStatement();
690 } else {
691 // Diagnose the common error "switch (X) {... default: }", which is
692 // not valid.
David Majnemerc6a99872011-06-14 15:24:38 +0000693 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Richard Smith1002d102012-02-17 01:35:32 +0000694 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
695 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
696 SubStmt = true;
Chris Lattner30f910e2006-10-16 05:52:41 +0000697 }
698
Richard Smith1002d102012-02-17 01:35:32 +0000699 // Broken sub-stmt shouldn't prevent forming the case statement properly.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000700 if (SubStmt.isInvalid())
Richard Smith1002d102012-02-17 01:35:32 +0000701 SubStmt = Actions.ActOnNullStmt(ColonLoc);
Sebastian Redl042ad952008-12-11 19:30:53 +0000702
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000703 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000704 SubStmt.get(), getCurScope());
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000705}
706
Richard Smithc202b282012-04-14 00:33:13 +0000707StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
708 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000709}
Chris Lattnerd2685cf2006-08-10 05:59:48 +0000710
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000711/// ParseCompoundStatement - Parse a "{}" block.
712///
713/// compound-statement: [C99 6.8.2]
714/// { block-item-list[opt] }
715/// [GNU] { label-declarations block-item-list } [TODO]
716///
717/// block-item-list:
718/// block-item
719/// block-item-list block-item
720///
721/// block-item:
722/// declaration
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000723/// [GNU] '__extension__' declaration
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000724/// statement
725/// [OMP] openmp-directive [TODO]
726///
727/// [GNU] label-declarations:
728/// [GNU] label-declaration
729/// [GNU] label-declarations label-declaration
730///
731/// [GNU] label-declaration:
732/// [GNU] '__label__' identifier-list ';'
733///
734/// [OMP] openmp-directive: [TODO]
735/// [OMP] barrier-directive
736/// [OMP] flush-directive
Chris Lattner30f910e2006-10-16 05:52:41 +0000737///
Richard Smithc202b282012-04-14 00:33:13 +0000738StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000739 unsigned ScopeFlags) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000740 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
Sebastian Redl042ad952008-12-11 19:30:53 +0000741
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000742 // Enter a scope to hold everything within the compound stmt. Compound
743 // statements can always hold declarations.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000744 ParseScope CompoundScope(this, ScopeFlags);
Chris Lattnerf2978802007-01-21 06:52:16 +0000745
746 // Parse the statements in the body.
Sebastian Redl042ad952008-12-11 19:30:53 +0000747 return ParseCompoundStatementBody(isStmtExpr);
Chris Lattnerf2978802007-01-21 06:52:16 +0000748}
749
Lang Hames2954cea2012-11-03 22:29:05 +0000750/// Parse any pragmas at the start of the compound expression. We handle these
751/// separately since some pragmas (FP_CONTRACT) must appear before any C
752/// statement in the compound, but may be intermingled with other pragmas.
753void Parser::ParseCompoundStatementLeadingPragmas() {
754 bool checkForPragmas = true;
755 while (checkForPragmas) {
756 switch (Tok.getKind()) {
757 case tok::annot_pragma_vis:
758 HandlePragmaVisibility();
759 break;
760 case tok::annot_pragma_pack:
761 HandlePragmaPack();
762 break;
763 case tok::annot_pragma_msstruct:
764 HandlePragmaMSStruct();
765 break;
766 case tok::annot_pragma_align:
767 HandlePragmaAlign();
768 break;
769 case tok::annot_pragma_weak:
770 HandlePragmaWeak();
771 break;
772 case tok::annot_pragma_weakalias:
773 HandlePragmaWeakAlias();
774 break;
775 case tok::annot_pragma_redefine_extname:
776 HandlePragmaRedefineExtname();
777 break;
778 case tok::annot_pragma_opencl_extension:
779 HandlePragmaOpenCLExtension();
780 break;
781 case tok::annot_pragma_fp_contract:
782 HandlePragmaFPContract();
783 break;
784 default:
785 checkForPragmas = false;
786 break;
787 }
788 }
789
790}
791
Chris Lattnerf2978802007-01-21 06:52:16 +0000792/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
Steve Naroff66356bd2007-09-16 14:56:35 +0000793/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
Chris Lattnerf2978802007-01-21 06:52:16 +0000794/// consume the '}' at the end of the block. It does not manipulate the scope
795/// stack.
John McCalldadc5752010-08-24 06:29:42 +0000796StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
Mike Stump11289f42009-09-09 15:08:12 +0000797 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Chris Lattnerbd61a952009-03-05 00:00:31 +0000798 Tok.getLocation(),
799 "in compound statement ('{}')");
Lang Hames5de91cc2012-10-02 04:45:10 +0000800
801 // Record the state of the FP_CONTRACT pragma, restore on leaving the
802 // compound statement.
803 Sema::FPContractStateRAII SaveFPContractState(Actions);
804
Douglas Gregore9bba4f2010-09-15 14:51:05 +0000805 InMessageExpressionRAIIObject InMessage(*this, false);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000806 BalancedDelimiterTracker T(*this, tok::l_brace);
807 if (T.consumeOpen())
808 return StmtError();
Chris Lattnerf2978802007-01-21 06:52:16 +0000809
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000810 Sema::CompoundScopeRAII CompoundScope(Actions);
811
Lang Hames2954cea2012-11-03 22:29:05 +0000812 // Parse any pragmas at the beginning of the compound statement.
813 ParseCompoundStatementLeadingPragmas();
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000814
Lang Hames2954cea2012-11-03 22:29:05 +0000815 StmtVector Stmts;
Lang Hamesa930e712012-10-21 01:10:01 +0000816
Chris Lattner43e7f312011-02-18 02:08:43 +0000817 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
818 // only allowed at the start of a compound stmt regardless of the language.
819 while (Tok.is(tok::kw___label__)) {
820 SourceLocation LabelLoc = ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000821
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000822 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner43e7f312011-02-18 02:08:43 +0000823 while (1) {
824 if (Tok.isNot(tok::identifier)) {
825 Diag(Tok, diag::err_expected_ident);
826 break;
827 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000828
Chris Lattner43e7f312011-02-18 02:08:43 +0000829 IdentifierInfo *II = Tok.getIdentifierInfo();
830 SourceLocation IdLoc = ConsumeToken();
Abramo Bagnara1c3af962011-03-05 18:21:20 +0000831 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000832
Chris Lattner43e7f312011-02-18 02:08:43 +0000833 if (!Tok.is(tok::comma))
834 break;
835 ConsumeToken();
836 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000837
John McCall084e83d2011-03-24 11:26:52 +0000838 DeclSpec DS(AttrFactory);
Rafael Espindolaab417692013-07-09 12:05:01 +0000839 DeclGroupPtrTy Res =
840 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner43e7f312011-02-18 02:08:43 +0000841 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000842
Chris Lattner02f1b612012-04-28 16:12:17 +0000843 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
Chris Lattner43e7f312011-02-18 02:08:43 +0000844 if (R.isUsable())
845 Stmts.push_back(R.release());
846 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000847
Chris Lattner43e7f312011-02-18 02:08:43 +0000848 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000849 if (Tok.is(tok::annot_pragma_unused)) {
850 HandlePragmaUnused();
851 continue;
852 }
853
David Blaikiebbafb8a2012-03-11 07:00:24 +0000854 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
Francois Pichet4a7de3e2011-05-06 20:48:22 +0000855 Tok.is(tok::kw___if_not_exists))) {
856 ParseMicrosoftIfExistsStatement(Stmts);
857 continue;
858 }
859
John McCalldadc5752010-08-24 06:29:42 +0000860 StmtResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000861 if (Tok.isNot(tok::kw___extension__)) {
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000862 R = ParseStatementOrDeclaration(Stmts, false);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000863 } else {
864 // __extension__ can start declarations and it can also be a unary
865 // operator for expressions. Consume multiple __extension__ markers here
866 // until we can determine which is which.
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000867 // FIXME: This loses extension expressions in the AST!
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000868 SourceLocation ExtLoc = ConsumeToken();
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000869 while (Tok.is(tok::kw___extension__))
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000870 ConsumeToken();
Chris Lattner1ff6e732008-10-20 06:51:33 +0000871
John McCall084e83d2011-03-24 11:26:52 +0000872 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +0000873 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000874
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000875 // If this is the start of a declaration, parse it as such.
Argyrios Kyrtzidis2c7137d2008-10-05 00:06:24 +0000876 if (isDeclarationStatement()) {
Eli Friedman15af3ee2009-05-16 23:40:44 +0000877 // __extension__ silences extension warnings in the subdeclaration.
Chris Lattner49836b42009-04-02 04:16:50 +0000878 // FIXME: Save the __extension__ on the decl as a node somehow?
Eli Friedman15af3ee2009-05-16 23:40:44 +0000879 ExtensionRAIIObject O(Diags);
880
Chris Lattner49836b42009-04-02 04:16:50 +0000881 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Fariborz Jahanian1db5c942010-09-28 20:42:35 +0000882 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
883 Declarator::BlockContext, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000884 attrs);
Chris Lattner49836b42009-04-02 04:16:50 +0000885 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000886 } else {
Eli Friedmaneb3a9b02009-01-27 08:43:38 +0000887 // Otherwise this was a unary __extension__ marker.
John McCalldadc5752010-08-24 06:29:42 +0000888 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
Chris Lattnerfdc07482008-03-13 06:32:11 +0000889
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000890 if (Res.isInvalid()) {
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000891 SkipUntil(tok::semi);
892 continue;
893 }
Sebastian Redlc2edafb2009-01-18 18:03:53 +0000894
Alexis Hunt96d5c762009-11-21 08:43:09 +0000895 // FIXME: Use attributes?
Chris Lattner1ff6e732008-10-20 06:51:33 +0000896 // Eat the semicolon at the end of stmt and convert the expr into a
897 // statement.
Douglas Gregor45d6bdf2010-09-07 15:23:11 +0000898 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
Richard Smith945f8d32013-01-14 22:39:08 +0000899 R = Actions.ActOnExprStmt(Res);
Chris Lattnerdfaf9f82007-08-27 01:01:57 +0000900 }
901 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000902
Sebastian Redl17f2c7d2008-12-09 13:15:23 +0000903 if (R.isUsable())
Sebastian Redld9f7b1c2008-12-10 00:02:53 +0000904 Stmts.push_back(R.release());
Chris Lattner30f910e2006-10-16 05:52:41 +0000905 }
Sebastian Redl042ad952008-12-11 19:30:53 +0000906
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000907 SourceLocation CloseLoc = Tok.getLocation();
908
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000909 // We broke out of the while loop because we found a '}' or EOF.
Nico Webera48b6c22012-12-30 23:36:56 +0000910 if (!T.consumeClose())
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000911 // Recover by creating a compound statement with what we parsed so far,
912 // instead of dropping everything and returning StmtError();
Nico Webera48b6c22012-12-30 23:36:56 +0000913 CloseLoc = T.getCloseLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +0000914
Argyrios Kyrtzidis6db85012012-03-24 02:26:51 +0000915 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000916 Stmts, isStmtExpr);
Chris Lattner0ccd51e2006-08-09 05:47:47 +0000917}
Chris Lattnerc951dae2006-08-10 04:23:57 +0000918
Chris Lattnerc0081db2008-12-12 06:31:07 +0000919/// ParseParenExprOrCondition:
920/// [C ] '(' expression ')'
Chris Lattner10da53c2008-12-12 06:35:28 +0000921/// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
Chris Lattnerc0081db2008-12-12 06:31:07 +0000922///
923/// This function parses and performs error recovery on the specified condition
924/// or expression (depending on whether we're in C++ or C mode). This function
925/// goes out of its way to recover well. It returns true if there was a parser
926/// error (the right paren couldn't be found), which indicates that the caller
927/// should try to recover harder. It returns false if the condition is
928/// successfully parsed. Note that a successful parse can still have semantic
929/// errors in the condition.
John McCalldadc5752010-08-24 06:29:42 +0000930bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
John McCall48871652010-08-21 09:40:31 +0000931 Decl *&DeclResult,
Douglas Gregore60e41a2010-05-06 17:25:47 +0000932 SourceLocation Loc,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000933 bool ConvertToBoolean) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000934 BalancedDelimiterTracker T(*this, tok::l_paren);
935 T.consumeOpen();
936
David Blaikiebbafb8a2012-03-11 07:00:24 +0000937 if (getLangOpts().CPlusPlus)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +0000938 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000939 else {
940 ExprResult = ParseExpression();
John McCall48871652010-08-21 09:40:31 +0000941 DeclResult = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000942
Douglas Gregore60e41a2010-05-06 17:25:47 +0000943 // If required, convert to a boolean value.
944 if (!ExprResult.isInvalid() && ConvertToBoolean)
945 ExprResult
John McCallb268a282010-08-23 23:25:46 +0000946 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000947 }
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chris Lattnerc0081db2008-12-12 06:31:07 +0000949 // If the parser was confused by the condition and we don't have a ')', try to
950 // recover by skipping ahead to a semi and bailing out. If condexp is
951 // semantically invalid but we have well formed code, keep going.
John McCall48871652010-08-21 09:40:31 +0000952 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
Chris Lattnerc0081db2008-12-12 06:31:07 +0000953 SkipUntil(tok::semi);
954 // Skipping may have stopped if it found the containing ')'. If so, we can
955 // continue parsing the if statement.
956 if (Tok.isNot(tok::r_paren))
957 return true;
958 }
Mike Stump11289f42009-09-09 15:08:12 +0000959
Chris Lattnerc0081db2008-12-12 06:31:07 +0000960 // Otherwise the condition is valid or the rparen is present.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000961 T.consumeClose();
Chad Rosier67055f52012-07-10 21:35:27 +0000962
Chris Lattner70d44982012-04-28 16:24:20 +0000963 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
964 // that all callers are looking for a statement after the condition, so ")"
965 // isn't valid.
966 while (Tok.is(tok::r_paren)) {
967 Diag(Tok, diag::err_extraneous_rparen_in_condition)
968 << FixItHint::CreateRemoval(Tok.getLocation());
969 ConsumeParen();
970 }
Chad Rosier67055f52012-07-10 21:35:27 +0000971
Chris Lattnerc0081db2008-12-12 06:31:07 +0000972 return false;
973}
974
975
Chris Lattnerc951dae2006-08-10 04:23:57 +0000976/// ParseIfStatement
977/// if-statement: [C99 6.8.4.1]
978/// 'if' '(' expression ')' statement
979/// 'if' '(' expression ')' statement 'else' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +0000980/// [C++] 'if' '(' condition ')' statement
981/// [C++] 'if' '(' condition ')' statement 'else' statement
Chris Lattner30f910e2006-10-16 05:52:41 +0000982///
Richard Smithc202b282012-04-14 00:33:13 +0000983StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000984 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +0000985 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
Chris Lattnerc951dae2006-08-10 04:23:57 +0000986
Chris Lattnerfeb00b62007-10-09 17:41:39 +0000987 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +0000988 Diag(Tok, diag::err_expected_lparen_after) << "if";
Chris Lattnerc951dae2006-08-10 04:23:57 +0000989 SkipUntil(tok::semi);
Sebastian Redl042ad952008-12-11 19:30:53 +0000990 return StmtError();
Chris Lattnerc951dae2006-08-10 04:23:57 +0000991 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +0000992
David Blaikiebbafb8a2012-03-11 07:00:24 +0000993 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000994
Chris Lattner2dd1b722007-08-26 23:08:06 +0000995 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
996 // the case for C90.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +0000997 //
998 // C++ 6.4p3:
999 // A name introduced by a declaration in a condition is in scope from its
1000 // point of declaration until the end of the substatements controlled by the
1001 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001002 // C++ 3.3.2p4:
1003 // Names declared in the for-init-statement, and in the condition of if,
1004 // while, for, and switch statements are local to the if, while, for, or
1005 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001006 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001007 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
Chris Lattner2dd1b722007-08-26 23:08:06 +00001008
Chris Lattnerc951dae2006-08-10 04:23:57 +00001009 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001010 ExprResult CondExp;
John McCall48871652010-08-21 09:40:31 +00001011 Decl *CondVar = 0;
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001012 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001013 return StmtError();
Chris Lattnerbc2d77c2008-12-12 06:19:11 +00001014
David Blaikiea5696df2012-05-16 04:20:04 +00001015 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001016
Chris Lattner8fb26252007-08-22 05:28:50 +00001017 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001018 // there is no compound stmt. C90 does not have this clause. We only do this
1019 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001020 //
1021 // C++ 6.4p1:
1022 // The substatement in a selection-statement (each substatement, in the else
1023 // form of the if statement) implicitly defines a local scope.
1024 //
1025 // For C++ we create a scope for the condition and a new scope for
1026 // substatements because:
1027 // -When the 'then' scope exits, we want the condition declaration to still be
1028 // active for the 'else' scope too.
1029 // -Sema will detect name clashes by considering declarations of a
1030 // 'ControlScope' as part of its direct subscope.
1031 // -If we wanted the condition and substatement to be in the same scope, we
1032 // would have to notify ParseStatement not to create a new scope. It's
1033 // simpler to let it create a new scope.
1034 //
Mike Stump11289f42009-09-09 15:08:12 +00001035 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001036 C99orCXX && Tok.isNot(tok::l_brace));
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001037
Chris Lattner5c5808a2007-10-29 05:08:52 +00001038 // Read the 'then' stmt.
1039 SourceLocation ThenStmtLoc = Tok.getLocation();
Nico Weber3cef1082011-12-22 23:26:17 +00001040
1041 SourceLocation InnerStatementTrailingElseLoc;
1042 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
Chris Lattnerac4471c2007-05-28 05:38:24 +00001043
Chris Lattner37e54f42007-08-22 05:16:28 +00001044 // Pop the 'if' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001045 InnerScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001046
Chris Lattnerc951dae2006-08-10 04:23:57 +00001047 // If it has an else, parse it.
Chris Lattner30f910e2006-10-16 05:52:41 +00001048 SourceLocation ElseLoc;
Chris Lattner5c5808a2007-10-29 05:08:52 +00001049 SourceLocation ElseStmtLoc;
John McCalldadc5752010-08-24 06:29:42 +00001050 StmtResult ElseStmt;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001051
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001052 if (Tok.is(tok::kw_else)) {
Nico Weber3cef1082011-12-22 23:26:17 +00001053 if (TrailingElseLoc)
1054 *TrailingElseLoc = Tok.getLocation();
1055
Chris Lattneraf635312006-10-16 06:06:51 +00001056 ElseLoc = ConsumeToken();
Chris Lattnerdf742642010-04-12 06:12:50 +00001057 ElseStmtLoc = Tok.getLocation();
Sebastian Redl042ad952008-12-11 19:30:53 +00001058
Chris Lattner8fb26252007-08-22 05:28:50 +00001059 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001060 // there is no compound stmt. C90 does not have this clause. We only do
1061 // this if the body isn't a compound statement to avoid push/pop in common
1062 // cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001063 //
1064 // C++ 6.4p1:
1065 // The substatement in a selection-statement (each substatement, in the else
1066 // form of the if statement) implicitly defines a local scope.
1067 //
Sebastian Redl042ad952008-12-11 19:30:53 +00001068 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001069 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001070
Chris Lattner30f910e2006-10-16 05:52:41 +00001071 ElseStmt = ParseStatement();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001072
Chris Lattner37e54f42007-08-22 05:16:28 +00001073 // Pop the 'else' scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001074 InnerScope.Exit();
Douglas Gregor4ecb7202011-07-30 08:36:53 +00001075 } else if (Tok.is(tok::code_completion)) {
1076 Actions.CodeCompleteAfterIf(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001077 cutOffParsing();
1078 return StmtError();
Nico Weber3cef1082011-12-22 23:26:17 +00001079 } else if (InnerStatementTrailingElseLoc.isValid()) {
1080 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
Chris Lattnerc951dae2006-08-10 04:23:57 +00001081 }
Sebastian Redl042ad952008-12-11 19:30:53 +00001082
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001083 IfScope.Exit();
Mike Stump11289f42009-09-09 15:08:12 +00001084
Chris Lattner5c5808a2007-10-29 05:08:52 +00001085 // If the then or else stmt is invalid and the other is valid (and present),
Mike Stump11289f42009-09-09 15:08:12 +00001086 // make turn the invalid one into a null stmt to avoid dropping the other
Chris Lattner5c5808a2007-10-29 05:08:52 +00001087 // part. If both are invalid, return error.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001088 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1089 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1090 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
Sebastian Redl511ed552008-11-25 22:21:31 +00001091 // Both invalid, or one is invalid and other is non-present: return error.
Sebastian Redl042ad952008-12-11 19:30:53 +00001092 return StmtError();
Chris Lattner5c5808a2007-10-29 05:08:52 +00001093 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001094
Chris Lattner5c5808a2007-10-29 05:08:52 +00001095 // Now if either are invalid, replace with a ';'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001096 if (ThenStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001097 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001098 if (ElseStmt.isInvalid())
Chris Lattner5c5808a2007-10-29 05:08:52 +00001099 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001100
John McCallb268a282010-08-23 23:25:46 +00001101 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +00001102 ElseLoc, ElseStmt.get());
Chris Lattnerc951dae2006-08-10 04:23:57 +00001103}
1104
Chris Lattner9075bd72006-08-10 04:59:57 +00001105/// ParseSwitchStatement
1106/// switch-statement:
1107/// 'switch' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001108/// [C++] 'switch' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001109StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001110 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001111 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
Chris Lattner9075bd72006-08-10 04:59:57 +00001112
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001113 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001114 Diag(Tok, diag::err_expected_lparen_after) << "switch";
Chris Lattner9075bd72006-08-10 04:59:57 +00001115 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001116 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001117 }
Chris Lattner2dd1b722007-08-26 23:08:06 +00001118
David Blaikiebbafb8a2012-03-11 07:00:24 +00001119 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001120
Chris Lattner2dd1b722007-08-26 23:08:06 +00001121 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1122 // not the case for C90. Start the switch scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001123 //
1124 // C++ 6.4p3:
1125 // A name introduced by a declaration in a condition is in scope from its
1126 // point of declaration until the end of the substatements controlled by the
1127 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001128 // C++ 3.3.2p4:
1129 // Names declared in the for-init-statement, and in the condition of if,
1130 // while, for, and switch statements are local to the if, while, for, or
1131 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001132 //
Richard Trieu2c850c02011-04-21 21:44:26 +00001133 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
Chris Lattnerc0081db2008-12-12 06:31:07 +00001134 if (C99orCXX)
1135 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001136 ParseScope SwitchScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001137
Chris Lattner9075bd72006-08-10 04:59:57 +00001138 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001139 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001140 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001141 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
Sebastian Redlb62406f2008-12-11 19:48:14 +00001142 return StmtError();
Eli Friedman44842d12008-12-17 22:19:57 +00001143
John McCalldadc5752010-08-24 06:29:42 +00001144 StmtResult Switch
John McCallb268a282010-08-23 23:25:46 +00001145 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001146
Douglas Gregore60e41a2010-05-06 17:25:47 +00001147 if (Switch.isInvalid()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001148 // Skip the switch body.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001149 // FIXME: This is not optimal recovery, but parsing the body is more
1150 // dangerous due to the presence of case and default statements, which
1151 // will have no place to connect back with the switch.
Douglas Gregor4abc32d2010-05-20 23:20:59 +00001152 if (Tok.is(tok::l_brace)) {
1153 ConsumeBrace();
1154 SkipUntil(tok::r_brace, false, false);
1155 } else
Douglas Gregore60e41a2010-05-06 17:25:47 +00001156 SkipUntil(tok::semi);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001157 return Switch;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001158 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001159
Chris Lattner8fb26252007-08-22 05:28:50 +00001160 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001161 // there is no compound stmt. C90 does not have this clause. We only do this
1162 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001163 //
1164 // C++ 6.4p1:
1165 // The substatement in a selection-statement (each substatement, in the else
1166 // form of the if statement) implicitly defines a local scope.
1167 //
1168 // See comments in ParseIfStatement for why we create a scope for the
1169 // condition and a new scope for substatement in C++.
1170 //
Mike Stump11289f42009-09-09 15:08:12 +00001171 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001172 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redl042ad952008-12-11 19:30:53 +00001173
Chris Lattner9075bd72006-08-10 04:59:57 +00001174 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001175 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001176
Chris Lattner8fd2d012010-01-24 01:50:29 +00001177 // Pop the scopes.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001178 InnerScope.Exit();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001179 SwitchScope.Exit();
Sebastian Redl042ad952008-12-11 19:30:53 +00001180
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001181 if (Body.isInvalid()) {
Chris Lattner8fd2d012010-01-24 01:50:29 +00001182 // FIXME: Remove the case statement list from the Switch statement.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001183
1184 // Put the synthesized null statement on the same line as the end of switch
1185 // condition.
1186 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1187 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1188 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001189
John McCallb268a282010-08-23 23:25:46 +00001190 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001191}
1192
1193/// ParseWhileStatement
1194/// while-statement: [C99 6.8.5.1]
1195/// 'while' '(' expression ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001196/// [C++] 'while' '(' condition ')' statement
Richard Smithc202b282012-04-14 00:33:13 +00001197StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001198 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
Chris Lattner30f910e2006-10-16 05:52:41 +00001199 SourceLocation WhileLoc = Tok.getLocation();
Chris Lattner9075bd72006-08-10 04:59:57 +00001200 ConsumeToken(); // eat the 'while'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001201
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001202 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001203 Diag(Tok, diag::err_expected_lparen_after) << "while";
Chris Lattner9075bd72006-08-10 04:59:57 +00001204 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001205 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001206 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001207
David Blaikiebbafb8a2012-03-11 07:00:24 +00001208 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001209
Chris Lattner2dd1b722007-08-26 23:08:06 +00001210 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1211 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001212 //
1213 // C++ 6.4p3:
1214 // A name introduced by a declaration in a condition is in scope from its
1215 // point of declaration until the end of the substatements controlled by the
1216 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001217 // C++ 3.3.2p4:
1218 // Names declared in the for-init-statement, and in the condition of if,
1219 // while, for, and switch statements are local to the if, while, for, or
1220 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001221 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001222 unsigned ScopeFlags;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001223 if (C99orCXX)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001224 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1225 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001226 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001227 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1228 ParseScope WhileScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001229
Chris Lattner9075bd72006-08-10 04:59:57 +00001230 // Parse the condition.
John McCalldadc5752010-08-24 06:29:42 +00001231 ExprResult Cond;
John McCall48871652010-08-21 09:40:31 +00001232 Decl *CondVar = 0;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001233 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
Chris Lattnerc0081db2008-12-12 06:31:07 +00001234 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001235
David Blaikiea5696df2012-05-16 04:20:04 +00001236 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001237
Chris Lattner8fb26252007-08-22 05:28:50 +00001238 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001239 // there is no compound stmt. C90 does not have this clause. We only do this
1240 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001241 //
1242 // C++ 6.5p2:
1243 // The substatement in an iteration-statement implicitly defines a local scope
1244 // which is entered and exited each time through the loop.
1245 //
1246 // See comments in ParseIfStatement for why we create a scope for the
1247 // condition and a new scope for substatement in C++.
1248 //
Mike Stump11289f42009-09-09 15:08:12 +00001249 ParseScope InnerScope(this, Scope::DeclScope,
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001250 C99orCXX && Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001251
Chris Lattner9075bd72006-08-10 04:59:57 +00001252 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001253 StmtResult Body(ParseStatement(TrailingElseLoc));
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001254
Chris Lattner8fb26252007-08-22 05:28:50 +00001255 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001256 InnerScope.Exit();
1257 WhileScope.Exit();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001258
John McCall48871652010-08-21 09:40:31 +00001259 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001260 return StmtError();
1261
John McCallb268a282010-08-23 23:25:46 +00001262 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
Chris Lattner9075bd72006-08-10 04:59:57 +00001263}
1264
1265/// ParseDoStatement
1266/// do-statement: [C99 6.8.5.2]
1267/// 'do' statement 'while' '(' expression ')' ';'
Chris Lattner503fadc2006-08-10 05:45:44 +00001268/// Note: this lets the caller parse the end ';'.
Richard Smithc202b282012-04-14 00:33:13 +00001269StmtResult Parser::ParseDoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001270 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001271 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001272
Chris Lattner2dd1b722007-08-26 23:08:06 +00001273 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1274 // the case for C90. Start the loop scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001275 unsigned ScopeFlags;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001276 if (getLangOpts().C99)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001277 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001278 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001279 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
Sebastian Redlb62406f2008-12-11 19:48:14 +00001280
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001281 ParseScope DoScope(this, ScopeFlags);
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001282
Chris Lattner8fb26252007-08-22 05:28:50 +00001283 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001284 // there is no compound stmt. C90 does not have this clause. We only do this
1285 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidisfea38012008-09-11 04:46:46 +00001286 //
1287 // C++ 6.5p2:
1288 // The substatement in an iteration-statement implicitly defines a local scope
1289 // which is entered and exited each time through the loop.
1290 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001291 ParseScope InnerScope(this, Scope::DeclScope,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001292 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001293 Tok.isNot(tok::l_brace));
Sebastian Redlb62406f2008-12-11 19:48:14 +00001294
Chris Lattner9075bd72006-08-10 04:59:57 +00001295 // Read the body statement.
John McCalldadc5752010-08-24 06:29:42 +00001296 StmtResult Body(ParseStatement());
Chris Lattner9075bd72006-08-10 04:59:57 +00001297
Chris Lattner8fb26252007-08-22 05:28:50 +00001298 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001299 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001300
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001301 if (Tok.isNot(tok::kw_while)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001302 if (!Body.isInvalid()) {
Chris Lattner0046de12008-11-13 18:52:53 +00001303 Diag(Tok, diag::err_expected_while);
Chris Lattner03c40412008-11-23 23:17:07 +00001304 Diag(DoLoc, diag::note_matching) << "do";
Chris Lattner0046de12008-11-13 18:52:53 +00001305 SkipUntil(tok::semi, false, true);
1306 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001307 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001308 }
Chris Lattneraf635312006-10-16 06:06:51 +00001309 SourceLocation WhileLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00001310
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001311 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001312 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
Chris Lattner0046de12008-11-13 18:52:53 +00001313 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001314 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001315 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001316
Chris Lattner10da53c2008-12-12 06:35:28 +00001317 // Parse the parenthesized condition.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001318 BalancedDelimiterTracker T(*this, tok::l_paren);
1319 T.consumeOpen();
Chad Rosier67055f52012-07-10 21:35:27 +00001320
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001321 // FIXME: Do not just parse the attribute contents and throw them away
1322 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001323 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001324 ProhibitAttributes(attrs);
1325
John McCalldadc5752010-08-24 06:29:42 +00001326 ExprResult Cond = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001327 T.consumeClose();
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001328 DoScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001329
Sebastian Redlb62406f2008-12-11 19:48:14 +00001330 if (Cond.isInvalid() || Body.isInvalid())
1331 return StmtError();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001332
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001333 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1334 Cond.get(), T.getCloseLocation());
Chris Lattner9075bd72006-08-10 04:59:57 +00001335}
1336
1337/// ParseForStatement
1338/// for-statement: [C99 6.8.5.3]
1339/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1340/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001341/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1342/// [C++] statement
Richard Smith02e85f32011-04-14 22:09:26 +00001343/// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001344/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1345/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001346///
1347/// [C++] for-init-statement:
1348/// [C++] expression-statement
1349/// [C++] simple-declaration
1350///
Richard Smith02e85f32011-04-14 22:09:26 +00001351/// [C++0x] for-range-declaration:
1352/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1353/// [C++0x] for-range-initializer:
1354/// [C++0x] expression
1355/// [C++0x] braced-init-list [TODO]
Richard Smithc202b282012-04-14 00:33:13 +00001356StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001357 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001358 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001359
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001360 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00001361 Diag(Tok, diag::err_expected_lparen_after) << "for";
Chris Lattner9075bd72006-08-10 04:59:57 +00001362 SkipUntil(tok::semi);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001363 return StmtError();
Chris Lattner9075bd72006-08-10 04:59:57 +00001364 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001365
Chad Rosier67055f52012-07-10 21:35:27 +00001366 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1367 getLangOpts().ObjC1;
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001368
Chris Lattner2dd1b722007-08-26 23:08:06 +00001369 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1370 // the case for C90. Start the loop scope.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001371 //
1372 // C++ 6.4p3:
1373 // A name introduced by a declaration in a condition is in scope from its
1374 // point of declaration until the end of the substatements controlled by the
1375 // condition.
Argyrios Kyrtzidis47f98652008-09-11 23:08:39 +00001376 // C++ 3.3.2p4:
1377 // Names declared in the for-init-statement, and in the condition of if,
1378 // while, for, and switch statements are local to the if, while, for, or
1379 // switch statement (including the controlled statement).
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001380 // C++ 6.5.3p1:
1381 // Names declared in the for-init-statement are in the same declarative-region
1382 // as those declared in the condition.
1383 //
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001384 unsigned ScopeFlags;
Chris Lattner934074c2009-04-22 00:54:41 +00001385 if (C99orCXXorObjC)
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001386 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1387 Scope::DeclScope | Scope::ControlScope;
Chris Lattner2dd1b722007-08-26 23:08:06 +00001388 else
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001389 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1390
1391 ParseScope ForScope(this, ScopeFlags);
Chris Lattner9075bd72006-08-10 04:59:57 +00001392
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001393 BalancedDelimiterTracker T(*this, tok::l_paren);
1394 T.consumeOpen();
1395
John McCalldadc5752010-08-24 06:29:42 +00001396 ExprResult Value;
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001397
Richard Smith02e85f32011-04-14 22:09:26 +00001398 bool ForEach = false, ForRange = false;
John McCalldadc5752010-08-24 06:29:42 +00001399 StmtResult FirstPart;
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001400 bool SecondPartIsInvalid = false;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001401 FullExprArg SecondPart(Actions);
John McCalldadc5752010-08-24 06:29:42 +00001402 ExprResult Collection;
Richard Smith02e85f32011-04-14 22:09:26 +00001403 ForRangeInit ForRangeInit;
Douglas Gregore60e41a2010-05-06 17:25:47 +00001404 FullExprArg ThirdPart(Actions);
John McCall48871652010-08-21 09:40:31 +00001405 Decl *SecondVar = 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001406
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001407 if (Tok.is(tok::code_completion)) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001408 Actions.CodeCompleteOrdinaryName(getCurScope(),
John McCallfaf5fb42010-08-26 23:41:50 +00001409 C99orCXXorObjC? Sema::PCC_ForInit
1410 : Sema::PCC_Expression);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001411 cutOffParsing();
1412 return StmtError();
Douglas Gregor9d64c5e2009-09-21 20:51:25 +00001413 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001414
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001415 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001416 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001417
Chris Lattner9075bd72006-08-10 04:59:57 +00001418 // Parse the first part of the for specifier.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001419 if (Tok.is(tok::semi)) { // for (;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001420 ProhibitAttributes(attrs);
Chris Lattner53361ac2006-08-10 05:19:57 +00001421 // no first part, eat the ';'.
1422 ConsumeToken();
Eli Friedman0ffc31c2011-12-20 01:50:37 +00001423 } else if (isForInitDeclaration()) { // for (int X = 4;
Chris Lattner53361ac2006-08-10 05:19:57 +00001424 // Parse declaration, which eats the ';'.
Chris Lattner934074c2009-04-22 00:54:41 +00001425 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
Chris Lattnerab1803652006-08-10 05:22:36 +00001426 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001427
Richard Smith02e85f32011-04-14 22:09:26 +00001428 // In C++0x, "for (T NS:a" might not be a typo for ::
David Blaikiebbafb8a2012-03-11 07:00:24 +00001429 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
Richard Smith02e85f32011-04-14 22:09:26 +00001430 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1431
Chris Lattner49836b42009-04-02 04:16:50 +00001432 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Benjamin Kramerf0623432012-08-23 22:51:59 +00001433 StmtVector Stmts;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001434 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
Richard Smith02e85f32011-04-14 22:09:26 +00001435 DeclEnd, attrs, false,
1436 MightBeForRangeStmt ?
1437 &ForRangeInit : 0);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001438 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001439
Richard Smith02e85f32011-04-14 22:09:26 +00001440 if (ForRangeInit.ParsedForRangeDecl()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001441 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001442 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
Richard Smith58c74332011-09-04 19:54:14 +00001443
Richard Smith02e85f32011-04-14 22:09:26 +00001444 ForRange = true;
1445 } else if (Tok.is(tok::semi)) { // for (int x = 4;
Chris Lattner32dc41c2009-03-29 17:27:48 +00001446 ConsumeToken();
1447 } else if ((ForEach = isTokIdentifier_in())) {
Fariborz Jahaniane774fa62009-11-19 22:12:37 +00001448 Actions.ActOnForEachDeclStmt(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001449 // ObjC: for (id x in expr)
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001450 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001451
Douglas Gregor68762e72010-08-23 21:17:50 +00001452 if (Tok.is(tok::code_completion)) {
1453 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001454 cutOffParsing();
1455 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001456 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001457 Collection = ParseExpression();
Chris Lattner32dc41c2009-03-29 17:27:48 +00001458 } else {
1459 Diag(Tok, diag::err_expected_semi_for);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001460 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001461 } else {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001462 ProhibitAttributes(attrs);
Chris Lattner89c50c62006-08-11 06:41:18 +00001463 Value = ParseExpression();
Chris Lattner71e23ce2006-11-04 20:18:38 +00001464
John McCall34376a62010-12-04 03:47:34 +00001465 ForEach = isTokIdentifier_in();
1466
Chris Lattnercd68f642007-06-27 01:06:29 +00001467 // Turn the expression into a stmt.
John McCall34376a62010-12-04 03:47:34 +00001468 if (!Value.isInvalid()) {
1469 if (ForEach)
1470 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1471 else
Richard Smith945f8d32013-01-14 22:39:08 +00001472 FirstPart = Actions.ActOnExprStmt(Value);
John McCall34376a62010-12-04 03:47:34 +00001473 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001474
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001475 if (Tok.is(tok::semi)) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001476 ConsumeToken();
John McCall34376a62010-12-04 03:47:34 +00001477 } else if (ForEach) {
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001478 ConsumeToken(); // consume 'in'
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001479
Douglas Gregor68762e72010-08-23 21:17:50 +00001480 if (Tok.is(tok::code_completion)) {
1481 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001482 cutOffParsing();
1483 return StmtError();
Douglas Gregor68762e72010-08-23 21:17:50 +00001484 }
Douglas Gregore60e41a2010-05-06 17:25:47 +00001485 Collection = ParseExpression();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001486 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
Richard Smith4f848f12011-12-20 22:56:20 +00001487 // User tried to write the reasonable, but ill-formed, for-range-statement
1488 // for (expr : expr) { ... }
1489 Diag(Tok, diag::err_for_range_expected_decl)
1490 << FirstPart.get()->getSourceRange();
1491 SkipUntil(tok::r_paren, false, true);
1492 SecondPartIsInvalid = true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001493 } else {
Douglas Gregor230a7e62011-02-17 03:38:46 +00001494 if (!Value.isInvalid()) {
1495 Diag(Tok, diag::err_expected_semi_for);
1496 } else {
1497 // Skip until semicolon or rparen, don't consume it.
1498 SkipUntil(tok::r_paren, true, true);
1499 if (Tok.is(tok::semi))
1500 ConsumeToken();
1501 }
Chris Lattner53361ac2006-08-10 05:19:57 +00001502 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001503 }
Richard Smith02e85f32011-04-14 22:09:26 +00001504 if (!ForEach && !ForRange) {
John McCallb268a282010-08-23 23:25:46 +00001505 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001506 // Parse the second part of the for specifier.
1507 if (Tok.is(tok::semi)) { // for (...;;
1508 // no second part.
Douglas Gregor230a7e62011-02-17 03:38:46 +00001509 } else if (Tok.is(tok::r_paren)) {
1510 // missing both semicolons.
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001511 } else {
John McCalldadc5752010-08-24 06:29:42 +00001512 ExprResult Second;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001513 if (getLangOpts().CPlusPlus)
Douglas Gregore60e41a2010-05-06 17:25:47 +00001514 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1515 else {
1516 Second = ParseExpression();
1517 if (!Second.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001518 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
John McCallb268a282010-08-23 23:25:46 +00001519 Second.get());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001520 }
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00001521 SecondPartIsInvalid = Second.isInvalid();
David Blaikiea5696df2012-05-16 04:20:04 +00001522 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001523 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001524
Douglas Gregor230a7e62011-02-17 03:38:46 +00001525 if (Tok.isNot(tok::semi)) {
1526 if (!SecondPartIsInvalid || SecondVar)
1527 Diag(Tok, diag::err_expected_semi_for);
1528 else
1529 // Skip until semicolon or rparen, don't consume it.
1530 SkipUntil(tok::r_paren, true, true);
1531 }
1532
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001533 if (Tok.is(tok::semi)) {
1534 ConsumeToken();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001535 }
Sebastian Redlb62406f2008-12-11 19:48:14 +00001536
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001537 // Parse the third part of the for specifier.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001538 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
John McCalldadc5752010-08-24 06:29:42 +00001539 ExprResult Third = ParseExpression();
Richard Smith945f8d32013-01-14 22:39:08 +00001540 // FIXME: The C++11 standard doesn't actually say that this is a
1541 // discarded-value expression, but it clearly should be.
1542 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
Douglas Gregore60e41a2010-05-06 17:25:47 +00001543 }
Chris Lattner9075bd72006-08-10 04:59:57 +00001544 }
Chris Lattner4564bc12006-08-10 23:14:52 +00001545 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001546 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001547
Richard Smith02e85f32011-04-14 22:09:26 +00001548 // We need to perform most of the semantic analysis for a C++0x for-range
1549 // statememt before parsing the body, in order to be able to deduce the type
1550 // of an auto-typed loop variable.
1551 StmtResult ForRangeStmt;
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001552 StmtResult ForEachStmt;
Chad Rosier67055f52012-07-10 21:35:27 +00001553
John McCall53848232011-07-27 01:07:15 +00001554 if (ForRange) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001555 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
Richard Smith02e85f32011-04-14 22:09:26 +00001556 ForRangeInit.ColonLoc,
1557 ForRangeInit.RangeExpr.get(),
Richard Smitha05b3b52012-09-20 21:52:32 +00001558 T.getCloseLocation(),
1559 Sema::BFRK_Build);
Richard Smith02e85f32011-04-14 22:09:26 +00001560
John McCall53848232011-07-27 01:07:15 +00001561
1562 // Similarly, we need to do the semantic analysis for a for-range
1563 // statement immediately in order to close over temporaries correctly.
1564 } else if (ForEach) {
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001565 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001566 FirstPart.take(),
Chad Rosier67055f52012-07-10 21:35:27 +00001567 Collection.take(),
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001568 T.getCloseLocation());
John McCall53848232011-07-27 01:07:15 +00001569 }
1570
Chris Lattner8fb26252007-08-22 05:28:50 +00001571 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
Chris Lattner8f44d202007-08-22 05:33:11 +00001572 // there is no compound stmt. C90 does not have this clause. We only do this
1573 // if the body isn't a compound statement to avoid push/pop in common cases.
Argyrios Kyrtzidis504bb842008-09-11 03:06:46 +00001574 //
1575 // C++ 6.5p2:
1576 // The substatement in an iteration-statement implicitly defines a local scope
1577 // which is entered and exited each time through the loop.
1578 //
1579 // See comments in ParseIfStatement for why we create a scope for
1580 // for-init-statement/condition and a new scope for substatement in C++.
1581 //
Mike Stump11289f42009-09-09 15:08:12 +00001582 ParseScope InnerScope(this, Scope::DeclScope,
Chris Lattner934074c2009-04-22 00:54:41 +00001583 C99orCXXorObjC && Tok.isNot(tok::l_brace));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001584
Chris Lattner9075bd72006-08-10 04:59:57 +00001585 // Read the body statement.
Nico Weber3cef1082011-12-22 23:26:17 +00001586 StmtResult Body(ParseStatement(TrailingElseLoc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001587
Chris Lattner8fb26252007-08-22 05:28:50 +00001588 // Pop the body scope if needed.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001589 InnerScope.Exit();
Chris Lattner8fb26252007-08-22 05:28:50 +00001590
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001591 // Leave the for-scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +00001592 ForScope.Exit();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001593
1594 if (Body.isInvalid())
Sebastian Redlb62406f2008-12-11 19:48:14 +00001595 return StmtError();
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001596
Richard Smith02e85f32011-04-14 22:09:26 +00001597 if (ForEach)
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001598 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1599 Body.take());
Mike Stump11289f42009-09-09 15:08:12 +00001600
Richard Smith02e85f32011-04-14 22:09:26 +00001601 if (ForRange)
1602 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1603
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001604 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1605 SecondPart, SecondVar, ThirdPart,
1606 T.getCloseLocation(), Body.take());
Chris Lattner9075bd72006-08-10 04:59:57 +00001607}
Chris Lattnerc951dae2006-08-10 04:23:57 +00001608
Chris Lattner503fadc2006-08-10 05:45:44 +00001609/// ParseGotoStatement
1610/// jump-statement:
1611/// 'goto' identifier ';'
1612/// [GNU] 'goto' '*' expression ';'
1613///
1614/// Note: this lets the caller parse the end ';'.
1615///
Richard Smithc202b282012-04-14 00:33:13 +00001616StmtResult Parser::ParseGotoStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001617 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001618 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001619
John McCalldadc5752010-08-24 06:29:42 +00001620 StmtResult Res;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001621 if (Tok.is(tok::identifier)) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001622 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1623 Tok.getLocation());
1624 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
Chris Lattner503fadc2006-08-10 05:45:44 +00001625 ConsumeToken();
Eli Friedman5d72d412009-04-28 00:51:18 +00001626 } else if (Tok.is(tok::star)) {
Chris Lattner503fadc2006-08-10 05:45:44 +00001627 // GNU indirect goto extension.
1628 Diag(Tok, diag::ext_gnu_indirect_goto);
Chris Lattneraf635312006-10-16 06:06:51 +00001629 SourceLocation StarLoc = ConsumeToken();
John McCalldadc5752010-08-24 06:29:42 +00001630 ExprResult R(ParseExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001631 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Chris Lattnera0927ce2006-08-12 16:59:03 +00001632 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001633 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001634 }
John McCallb268a282010-08-23 23:25:46 +00001635 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
Chris Lattnere34b2c22007-07-22 04:13:33 +00001636 } else {
1637 Diag(Tok, diag::err_expected_ident);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001638 return StmtError();
Chris Lattner503fadc2006-08-10 05:45:44 +00001639 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001640
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001641 return Res;
Chris Lattner503fadc2006-08-10 05:45:44 +00001642}
1643
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001644/// ParseContinueStatement
1645/// jump-statement:
1646/// 'continue' ';'
1647///
1648/// Note: this lets the caller parse the end ';'.
1649///
Richard Smithc202b282012-04-14 00:33:13 +00001650StmtResult Parser::ParseContinueStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001651 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001652 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001653}
1654
1655/// ParseBreakStatement
1656/// jump-statement:
1657/// 'break' ';'
1658///
1659/// Note: this lets the caller parse the end ';'.
1660///
Richard Smithc202b282012-04-14 00:33:13 +00001661StmtResult Parser::ParseBreakStatement() {
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001662 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
Douglas Gregor0be31a22010-07-02 17:43:08 +00001663 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
Chris Lattner33ad2ca2006-11-05 23:47:55 +00001664}
1665
Chris Lattner503fadc2006-08-10 05:45:44 +00001666/// ParseReturnStatement
1667/// jump-statement:
1668/// 'return' expression[opt] ';'
Richard Smithc202b282012-04-14 00:33:13 +00001669StmtResult Parser::ParseReturnStatement() {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001670 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
Chris Lattneraf635312006-10-16 06:06:51 +00001671 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
Sebastian Redlb62406f2008-12-11 19:48:14 +00001672
John McCalldadc5752010-08-24 06:29:42 +00001673 ExprResult R;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00001674 if (Tok.isNot(tok::semi)) {
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001675 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00001676 Actions.CodeCompleteReturn(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001677 cutOffParsing();
Douglas Gregor7aa6b222010-05-30 01:49:25 +00001678 return StmtError();
1679 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001680
David Blaikiebbafb8a2012-03-11 07:00:24 +00001681 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
Douglas Gregore9e27d92011-03-11 23:10:44 +00001682 R = ParseInitializer();
Richard Smith5d164bc2011-10-15 05:09:34 +00001683 if (R.isUsable())
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001684 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00001685 diag::warn_cxx98_compat_generalized_initializer_lists :
1686 diag::ext_generalized_initializer_lists)
Douglas Gregore9e27d92011-03-11 23:10:44 +00001687 << R.get()->getSourceRange();
1688 } else
1689 R = ParseExpression();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001690 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
Chris Lattnera0927ce2006-08-12 16:59:03 +00001691 SkipUntil(tok::semi, false, true);
Sebastian Redlb62406f2008-12-11 19:48:14 +00001692 return StmtError();
Chris Lattner30f910e2006-10-16 05:52:41 +00001693 }
Chris Lattnera0927ce2006-08-12 16:59:03 +00001694 }
John McCallb268a282010-08-23 23:25:46 +00001695 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
Chris Lattner503fadc2006-08-10 05:45:44 +00001696}
Chris Lattner0116c472006-08-15 06:03:28 +00001697
John McCallf413f5e2013-05-03 00:10:13 +00001698namespace {
1699 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1700 Parser &TheParser;
1701 SourceLocation AsmLoc;
1702 StringRef AsmString;
1703
1704 /// The tokens we streamed into AsmString and handed off to MC.
1705 ArrayRef<Token> AsmToks;
1706
1707 /// The offset of each token in AsmToks within AsmString.
1708 ArrayRef<unsigned> AsmTokOffsets;
1709
1710 public:
1711 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1712 StringRef AsmString,
1713 ArrayRef<Token> Toks,
1714 ArrayRef<unsigned> Offsets)
1715 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1716 AsmToks(Toks), AsmTokOffsets(Offsets) {
1717 assert(AsmToks.size() == AsmTokOffsets.size());
1718 }
1719
1720 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1721 InlineAsmIdentifierInfo &Info,
1722 bool IsUnevaluatedContext) {
1723 // Collect the desired tokens.
1724 SmallVector<Token, 16> LineToks;
1725 const Token *FirstOrigToken = 0;
1726 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1727
1728 unsigned NumConsumedToks;
1729 ExprResult Result =
1730 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1731 IsUnevaluatedContext);
1732
1733 // If we consumed the entire line, tell MC that.
1734 // Also do this if we consumed nothing as a way of reporting failure.
1735 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1736 // By not modifying LineBuf, we're implicitly consuming it all.
1737
1738 // Otherwise, consume up to the original tokens.
1739 } else {
1740 assert(FirstOrigToken && "not using original tokens?");
1741
1742 // Since we're using original tokens, apply that offset.
1743 assert(FirstOrigToken[NumConsumedToks].getLocation()
1744 == LineToks[NumConsumedToks].getLocation());
1745 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1746 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1747
1748 // The total length we've consumed is the relative offset
1749 // of the last token we consumed plus its length.
1750 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1751 + AsmToks[LastIndex].getLength()
1752 - AsmTokOffsets[FirstIndex]);
1753 LineBuf = LineBuf.substr(0, TotalOffset);
1754 }
1755
1756 // Initialize the "decl" with the lookup result.
1757 Info.OpDecl = static_cast<void*>(Result.take());
1758 return Info.OpDecl;
1759 }
1760
1761 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1762 unsigned &Offset) {
1763 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1764 Offset, AsmLoc);
1765 }
1766
1767 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1768 void *Context) {
1769 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1770 }
1771
1772 private:
1773 /// Collect the appropriate tokens for the given string.
1774 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1775 const Token *&FirstOrigToken) const {
1776 // For now, assert that the string we're working with is a substring
1777 // of what we gave to MC. This lets us use the original tokens.
1778 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1779 !std::less<const char*>()(AsmString.end(), Str.end()));
1780
1781 // Try to find a token whose offset matches the first token.
1782 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1783 const unsigned *FirstTokOffset
1784 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1785 FirstCharOffset);
1786
1787 // For now, assert that the start of the string exactly
1788 // corresponds to the start of a token.
1789 assert(*FirstTokOffset == FirstCharOffset);
1790
1791 // Use all the original tokens for this line. (We assume the
1792 // end of the line corresponds cleanly to a token break.)
1793 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1794 FirstOrigToken = &AsmToks[FirstTokIndex];
1795 unsigned LastCharOffset = Str.end() - AsmString.begin();
1796 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1797 if (AsmTokOffsets[i] >= LastCharOffset) break;
1798 TempToks.push_back(AsmToks[i]);
1799 }
1800 }
1801
1802 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1803 // Compute an offset into the inline asm buffer.
1804 // FIXME: This isn't right if .macro is involved (but hopefully, no
1805 // real-world code does that).
1806 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1807 const llvm::MemoryBuffer *LBuf =
1808 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1809 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1810
1811 // Figure out which token that offset points into.
1812 const unsigned *TokOffsetPtr =
1813 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1814 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1815 unsigned TokOffset = *TokOffsetPtr;
1816
1817 // If we come up with an answer which seems sane, use it; otherwise,
1818 // just point at the __asm keyword.
1819 // FIXME: Assert the answer is sane once we handle .macro correctly.
1820 SourceLocation Loc = AsmLoc;
1821 if (TokIndex < AsmToks.size()) {
1822 const Token &Tok = AsmToks[TokIndex];
1823 Loc = Tok.getLocation();
1824 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1825 }
1826 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1827 << D.getMessage();
1828 }
1829 };
1830}
1831
1832/// Parse an identifier in an MS-style inline assembly block.
1833///
1834/// \param CastInfo - a void* so that we don't have to teach Parser.h
1835/// about the actual type.
1836ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1837 unsigned &NumLineToksConsumed,
1838 void *CastInfo,
1839 bool IsUnevaluatedContext) {
1840 llvm::InlineAsmIdentifierInfo &Info =
1841 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1842
1843 // Push a fake token on the end so that we don't overrun the token
1844 // stream. We use ';' because it expression-parsing should never
1845 // overrun it.
1846 const tok::TokenKind EndOfStream = tok::semi;
1847 Token EndOfStreamTok;
1848 EndOfStreamTok.startToken();
1849 EndOfStreamTok.setKind(EndOfStream);
1850 LineToks.push_back(EndOfStreamTok);
1851
1852 // Also copy the current token over.
1853 LineToks.push_back(Tok);
1854
1855 PP.EnterTokenStream(LineToks.begin(),
1856 LineToks.size(),
1857 /*disable macros*/ true,
1858 /*owns tokens*/ false);
1859
1860 // Clear the current token and advance to the first token in LineToks.
1861 ConsumeAnyToken();
1862
1863 // Parse an optional scope-specifier if we're in C++.
1864 CXXScopeSpec SS;
1865 if (getLangOpts().CPlusPlus) {
1866 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1867 }
1868
1869 // Require an identifier here.
1870 SourceLocation TemplateKWLoc;
1871 UnqualifiedId Id;
1872 bool Invalid = ParseUnqualifiedId(SS,
1873 /*EnteringContext=*/false,
1874 /*AllowDestructorName=*/false,
1875 /*AllowConstructorName=*/false,
1876 /*ObjectType=*/ ParsedType(),
1877 TemplateKWLoc,
1878 Id);
1879
1880 // If we've run into the poison token we inserted before, or there
1881 // was a parsing error, then claim the entire line.
1882 if (Invalid || Tok.is(EndOfStream)) {
1883 NumLineToksConsumed = LineToks.size() - 2;
1884
1885 // Otherwise, claim up to the start of the next token.
1886 } else {
1887 // Figure out how many tokens we are into LineToks.
1888 unsigned LineIndex = 0;
1889 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1890 LineIndex++;
1891 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1892 }
1893
1894 NumLineToksConsumed = LineIndex;
1895 }
1896
1897 // Finally, restore the old parsing state by consuming all the
1898 // tokens we staged before, implicitly killing off the
1899 // token-lexer we pushed.
1900 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1901 ConsumeAnyToken();
1902 }
1903 ConsumeToken(EndOfStream);
1904
1905 // Leave LineToks in its original state.
1906 LineToks.pop_back();
1907 LineToks.pop_back();
1908
1909 // Perform the lookup.
1910 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1911 IsUnevaluatedContext);
1912}
1913
1914/// Turn a sequence of our tokens back into a string that we can hand
1915/// to the MC asm parser.
1916static bool buildMSAsmString(Preprocessor &PP,
1917 SourceLocation AsmLoc,
1918 ArrayRef<Token> AsmToks,
1919 SmallVectorImpl<unsigned> &TokOffsets,
1920 SmallString<512> &Asm) {
1921 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1922
1923 // Is this the start of a new assembly statement?
1924 bool isNewStatement = true;
1925
1926 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1927 const Token &Tok = AsmToks[i];
1928
1929 // Start each new statement with a newline and a tab.
1930 if (!isNewStatement &&
1931 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1932 Asm += "\n\t";
1933 isNewStatement = true;
1934 }
1935
1936 // Preserve the existence of leading whitespace except at the
1937 // start of a statement.
1938 if (!isNewStatement && Tok.hasLeadingSpace())
1939 Asm += ' ';
1940
1941 // Remember the offset of this token.
1942 TokOffsets.push_back(Asm.size());
1943
1944 // Don't actually write '__asm' into the assembly stream.
1945 if (Tok.is(tok::kw_asm)) {
1946 // Complain about __asm at the end of the stream.
1947 if (i + 1 == e) {
1948 PP.Diag(AsmLoc, diag::err_asm_empty);
1949 return true;
1950 }
1951
1952 continue;
1953 }
1954
1955 // Append the spelling of the token.
1956 SmallString<32> SpellingBuffer;
1957 bool SpellingInvalid = false;
1958 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
1959 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
1960
1961 // We are no longer at the start of a statement.
1962 isNewStatement = false;
1963 }
1964
1965 // Ensure that the buffer is null-terminated.
1966 Asm.push_back('\0');
1967 Asm.pop_back();
1968
1969 assert(TokOffsets.size() == AsmToks.size());
1970 return false;
1971}
1972
Eli Friedmana4b02c32011-09-30 01:13:51 +00001973/// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1974/// this routine is called to collect the tokens for an MS asm statement.
Chad Rosier32503022012-06-11 20:47:18 +00001975///
1976/// [MS] ms-asm-statement:
1977/// ms-asm-block
1978/// ms-asm-block ms-asm-statement
1979///
1980/// [MS] ms-asm-block:
1981/// '__asm' ms-asm-line '\n'
1982/// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1983///
1984/// [MS] ms-asm-instruction-block
1985/// ms-asm-line
1986/// ms-asm-line '\n' ms-asm-instruction-block
1987///
Eli Friedmana4b02c32011-09-30 01:13:51 +00001988StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1989 SourceManager &SrcMgr = PP.getSourceManager();
1990 SourceLocation EndLoc = AsmLoc;
Chad Rosier32503022012-06-11 20:47:18 +00001991 SmallVector<Token, 4> AsmToks;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00001992
1993 bool InBraces = false;
1994 unsigned short savedBraceCount = 0;
1995 bool InAsmComment = false;
1996 FileID FID;
1997 unsigned LineNo = 0;
1998 unsigned NumTokensRead = 0;
1999 SourceLocation LBraceLoc;
2000
2001 if (Tok.is(tok::l_brace)) {
2002 // Braced inline asm: consume the opening brace.
2003 InBraces = true;
2004 savedBraceCount = BraceCount;
2005 EndLoc = LBraceLoc = ConsumeBrace();
2006 ++NumTokensRead;
2007 } else {
2008 // Single-line inline asm; compute which line it is on.
2009 std::pair<FileID, unsigned> ExpAsmLoc =
2010 SrcMgr.getDecomposedExpansionLoc(EndLoc);
2011 FID = ExpAsmLoc.first;
2012 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2013 }
2014
2015 SourceLocation TokLoc = Tok.getLocation();
Eli Friedmana4b02c32011-09-30 01:13:51 +00002016 do {
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002017 // If we hit EOF, we're done, period.
2018 if (Tok.is(tok::eof))
Eli Friedmana4b02c32011-09-30 01:13:51 +00002019 break;
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002020
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002021 if (!InAsmComment && Tok.is(tok::semi)) {
2022 // A semicolon in an asm is the start of a comment.
2023 InAsmComment = true;
2024 if (InBraces) {
2025 // Compute which line the comment is on.
2026 std::pair<FileID, unsigned> ExpSemiLoc =
2027 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2028 FID = ExpSemiLoc.first;
2029 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2030 }
2031 } else if (!InBraces || InAsmComment) {
2032 // If end-of-line is significant, check whether this token is on a
2033 // new line.
2034 std::pair<FileID, unsigned> ExpLoc =
2035 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2036 if (ExpLoc.first != FID ||
2037 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2038 // If this is a single-line __asm, we're done.
2039 if (!InBraces)
2040 break;
2041 // We're no longer in a comment.
2042 InAsmComment = false;
2043 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2044 // Single-line asm always ends when a closing brace is seen.
2045 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2046 // does MSVC do here?
2047 break;
2048 }
2049 }
2050 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2051 BraceCount == (savedBraceCount + 1)) {
2052 // Consume the closing brace, and finish
2053 EndLoc = ConsumeBrace();
2054 break;
2055 }
2056
2057 // Consume the next token; make sure we don't modify the brace count etc.
2058 // if we are in a comment.
2059 EndLoc = TokLoc;
2060 if (InAsmComment)
2061 PP.Lex(Tok);
2062 else {
2063 AsmToks.push_back(Tok);
2064 ConsumeAnyToken();
2065 }
2066 TokLoc = Tok.getLocation();
2067 ++NumTokensRead;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002068 } while (1);
Chad Rosier32503022012-06-11 20:47:18 +00002069
Chad Rosierc97a6bb2012-08-14 19:22:06 +00002070 if (InBraces && BraceCount != savedBraceCount) {
2071 // __asm without closing brace (this can happen at EOF).
2072 Diag(Tok, diag::err_expected_rbrace);
2073 Diag(LBraceLoc, diag::note_matching) << "{";
2074 return StmtError();
2075 } else if (NumTokensRead == 0) {
2076 // Empty __asm.
2077 Diag(Tok, diag::err_expected_lbrace);
2078 return StmtError();
2079 }
2080
John McCallf413f5e2013-05-03 00:10:13 +00002081 // Okay, prepare to use MC to parse the assembly.
2082 SmallVector<StringRef, 4> ConstraintRefs;
2083 SmallVector<Expr*, 4> Exprs;
2084 SmallVector<StringRef, 4> ClobberRefs;
2085
2086 // We need an actual supported target.
2087 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2088 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
2089 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2090 ArchTy != llvm::Triple::x86_64);
2091 if (UnsupportedArch)
2092 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
2093
2094 // If we don't support assembly, or the assembly is empty, we don't
2095 // need to instantiate the AsmParser, etc.
2096 if (UnsupportedArch || AsmToks.empty()) {
2097 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2098 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2099 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2100 }
2101
2102 // Expand the tokens into a string buffer.
2103 SmallString<512> AsmString;
2104 SmallVector<unsigned, 8> TokOffsets;
2105 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2106 return StmtError();
2107
2108 // Find the target and create the target specific parser.
2109 std::string Error;
2110 const std::string &TT = TheTriple.getTriple();
2111 const llvm::Target *TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2112
John McCallf413f5e2013-05-03 00:10:13 +00002113 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
Rafael Espindola77056232013-05-13 01:24:18 +00002114 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002115 // Get the instruction descriptor.
2116 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
John McCallf413f5e2013-05-03 00:10:13 +00002117 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2118 OwningPtr<llvm::MCSubtargetInfo>
2119 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2120
2121 llvm::SourceMgr TempSrcMgr;
Bill Wendlingda1e3e72013-06-18 07:22:05 +00002122 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
John McCallf413f5e2013-05-03 00:10:13 +00002123 llvm::MemoryBuffer *Buffer =
2124 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2125
2126 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2127 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2128
2129 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2130 OwningPtr<llvm::MCAsmParser>
2131 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2132 OwningPtr<llvm::MCTargetAsmParser>
Joey Gouly92dfcfa2013-09-12 10:59:24 +00002133 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser, *MII));
John McCallf413f5e2013-05-03 00:10:13 +00002134
John McCallf413f5e2013-05-03 00:10:13 +00002135 llvm::MCInstPrinter *IP =
2136 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2137
2138 // Change to the Intel dialect.
2139 Parser->setAssemblerDialect(1);
2140 Parser->setTargetParser(*TargetParser.get());
2141 Parser->setParsingInlineAsm(true);
2142 TargetParser->setParsingInlineAsm(true);
2143
2144 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2145 AsmToks, TokOffsets);
2146 TargetParser->setSemaCallback(&Callback);
2147 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2148 &Callback);
2149
2150 unsigned NumOutputs;
2151 unsigned NumInputs;
2152 std::string AsmStringIR;
2153 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2154 SmallVector<std::string, 4> Constraints;
2155 SmallVector<std::string, 4> Clobbers;
2156 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2157 NumOutputs, NumInputs, OpExprs, Constraints,
2158 Clobbers, MII, IP, Callback))
2159 return StmtError();
2160
2161 // Build the vector of clobber StringRefs.
2162 unsigned NumClobbers = Clobbers.size();
2163 ClobberRefs.resize(NumClobbers);
2164 for (unsigned i = 0; i != NumClobbers; ++i)
2165 ClobberRefs[i] = StringRef(Clobbers[i]);
2166
2167 // Recast the void pointers and build the vector of constraint StringRefs.
2168 unsigned NumExprs = NumOutputs + NumInputs;
2169 ConstraintRefs.resize(NumExprs);
2170 Exprs.resize(NumExprs);
2171 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2172 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2173 if (!OpExpr)
2174 return StmtError();
2175
2176 // Need address of variable.
2177 if (OpExprs[i].second)
2178 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2179 .take();
2180
2181 ConstraintRefs[i] = StringRef(Constraints[i]);
2182 Exprs[i] = OpExpr;
2183 }
2184
Chad Rosierc6c71332012-08-06 20:03:45 +00002185 // FIXME: We should be passing source locations for better diagnostics.
John McCallf413f5e2013-05-03 00:10:13 +00002186 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2187 NumOutputs, NumInputs,
2188 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002189}
2190
Chris Lattner0116c472006-08-15 06:03:28 +00002191/// ParseAsmStatement - Parse a GNU extended asm statement.
Steve Naroff69e8f9e2008-02-11 23:15:56 +00002192/// asm-statement:
2193/// gnu-asm-statement
2194/// ms-asm-statement
2195///
2196/// [GNU] gnu-asm-statement:
Chris Lattner0116c472006-08-15 06:03:28 +00002197/// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2198///
2199/// [GNU] asm-argument:
2200/// asm-string-literal
2201/// asm-string-literal ':' asm-operands[opt]
2202/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2203/// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2204/// ':' asm-clobbers
2205///
2206/// [GNU] asm-clobbers:
2207/// asm-string-literal
2208/// asm-clobbers ',' asm-string-literal
2209///
John McCalldadc5752010-08-24 06:29:42 +00002210StmtResult Parser::ParseAsmStatement(bool &msAsm) {
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002211 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
Chris Lattner73c56c02007-10-29 04:04:16 +00002212 SourceLocation AsmLoc = ConsumeToken();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002213
Chad Rosierc8e56e82012-12-05 21:08:21 +00002214 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
Chad Rosier67055f52012-07-10 21:35:27 +00002215 !isTypeQualifier()) {
Steve Naroffb2c80c72008-02-07 03:50:06 +00002216 msAsm = true;
Eli Friedmana4b02c32011-09-30 01:13:51 +00002217 return ParseMicrosoftAsmStatement(AsmLoc);
Steve Naroffb2c80c72008-02-07 03:50:06 +00002218 }
John McCall084e83d2011-03-24 11:26:52 +00002219 DeclSpec DS(AttrFactory);
Chris Lattner0116c472006-08-15 06:03:28 +00002220 SourceLocation Loc = Tok.getLocation();
Alexis Hunt96d5c762009-11-21 08:43:09 +00002221 ParseTypeQualifierListOpt(DS, true, false);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002222
Chris Lattner0116c472006-08-15 06:03:28 +00002223 // GNU asms accept, but warn, about type-qualifiers other than volatile.
Chris Lattnera925dc62006-11-28 04:33:46 +00002224 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Chris Lattner6d29c102008-11-18 07:48:38 +00002225 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
Chris Lattnera925dc62006-11-28 04:33:46 +00002226 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Chris Lattner6d29c102008-11-18 07:48:38 +00002227 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
Richard Smith8e1ac332013-03-28 01:55:44 +00002228 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2229 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2230 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
Sebastian Redlb62406f2008-12-11 19:48:14 +00002231
Chris Lattner0116c472006-08-15 06:03:28 +00002232 // Remember if this was a volatile asm.
Anders Carlsson660bdd12007-11-23 23:12:25 +00002233 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002234 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002235 Diag(Tok, diag::err_expected_lparen_after) << "asm";
Chris Lattner0116c472006-08-15 06:03:28 +00002236 SkipUntil(tok::r_paren);
Sebastian Redlb62406f2008-12-11 19:48:14 +00002237 return StmtError();
Chris Lattner0116c472006-08-15 06:03:28 +00002238 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002239 BalancedDelimiterTracker T(*this, tok::l_paren);
2240 T.consumeOpen();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002241
John McCalldadc5752010-08-24 06:29:42 +00002242 ExprResult AsmString(ParseAsmStringLiteral());
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002243 if (AsmString.isInvalid()) {
Richard Smithd67aea22012-03-06 03:21:47 +00002244 // Consume up to and including the closing paren.
2245 T.skipToEnd();
Sebastian Redlb62406f2008-12-11 19:48:14 +00002246 return StmtError();
Ted Kremenekeb0a6c02011-12-02 01:30:14 +00002247 }
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002248
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002249 SmallVector<IdentifierInfo *, 4> Names;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002250 ExprVector Constraints;
2251 ExprVector Exprs;
2252 ExprVector Clobbers;
Chris Lattner0116c472006-08-15 06:03:28 +00002253
Anders Carlsson19fe1162008-02-05 23:03:50 +00002254 if (Tok.is(tok::r_paren)) {
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002255 // We have a simple asm expression like 'asm("foo")'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002256 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002257 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2258 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2259 Constraints, Exprs, AsmString.take(),
2260 Clobbers, T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002261 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002262
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002263 // Parse Outputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002264 bool AteExtraColon = false;
2265 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2266 // In C++ mode, parse "::" like ": :".
2267 AteExtraColon = Tok.is(tok::coloncolon);
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002268 ConsumeToken();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002269
Chris Lattner15768502009-12-20 23:08:04 +00002270 if (!AteExtraColon &&
2271 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002272 return StmtError();
2273 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002274
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002275 unsigned NumOutputs = Names.size();
2276
2277 // Parse Inputs, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002278 if (AteExtraColon ||
2279 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2280 // In C++ mode, parse "::" like ": :".
2281 if (AteExtraColon)
2282 AteExtraColon = false;
2283 else {
2284 AteExtraColon = Tok.is(tok::coloncolon);
2285 ConsumeToken();
2286 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002287
Chris Lattner15768502009-12-20 23:08:04 +00002288 if (!AteExtraColon &&
2289 ParseAsmOperandsOpt(Names, Constraints, Exprs))
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002290 return StmtError();
2291 }
2292
2293 assert(Names.size() == Constraints.size() &&
2294 Constraints.size() == Exprs.size() &&
2295 "Input operand size mismatch!");
2296
2297 unsigned NumInputs = Names.size() - NumOutputs;
2298
2299 // Parse the clobbers, if present.
Chris Lattner15768502009-12-20 23:08:04 +00002300 if (AteExtraColon || Tok.is(tok::colon)) {
2301 if (!AteExtraColon)
2302 ConsumeToken();
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002303
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002304 // Parse the asm-string list for clobbers if present.
2305 if (Tok.isNot(tok::r_paren)) {
2306 while (1) {
John McCalldadc5752010-08-24 06:29:42 +00002307 ExprResult Clobber(ParseAsmStringLiteral());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002308
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002309 if (Clobber.isInvalid())
2310 break;
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002311
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002312 Clobbers.push_back(Clobber.release());
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002313
Chandler Carruth3c31aa32010-07-22 07:11:21 +00002314 if (Tok.isNot(tok::comma)) break;
2315 ConsumeToken();
2316 }
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002317 }
2318 }
2319
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002320 T.consumeClose();
Chad Rosierde70e0e2012-08-25 00:11:56 +00002321 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2322 NumInputs, Names.data(), Constraints, Exprs,
2323 AsmString.take(), Clobbers,
2324 T.getCloseLocation());
Chris Lattner0116c472006-08-15 06:03:28 +00002325}
2326
2327/// ParseAsmOperands - Parse the asm-operands production as used by
Chris Lattnerbf5fff52009-12-20 23:00:41 +00002328/// asm-statement, assuming the leading ':' token was eaten.
Chris Lattner0116c472006-08-15 06:03:28 +00002329///
2330/// [GNU] asm-operands:
2331/// asm-operand
2332/// asm-operands ',' asm-operand
2333///
2334/// [GNU] asm-operand:
2335/// asm-string-literal '(' expression ')'
2336/// '[' identifier ']' asm-string-literal '(' expression ')'
2337///
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00002338//
2339// FIXME: Avoid unnecessary std::string trashing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002340bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
Richard Trieu2bd04012011-09-09 02:00:50 +00002341 SmallVectorImpl<Expr *> &Constraints,
2342 SmallVectorImpl<Expr *> &Exprs) {
Chris Lattner0116c472006-08-15 06:03:28 +00002343 // 'asm-operands' isn't present?
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002344 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002345 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002346
2347 while (1) {
Chris Lattner0116c472006-08-15 06:03:28 +00002348 // Read the [id] if present.
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002349 if (Tok.is(tok::l_square)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002350 BalancedDelimiterTracker T(*this, tok::l_square);
2351 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00002352
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002353 if (Tok.isNot(tok::identifier)) {
Chris Lattner0116c472006-08-15 06:03:28 +00002354 Diag(Tok, diag::err_expected_ident);
2355 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002356 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002357 }
Mike Stump11289f42009-09-09 15:08:12 +00002358
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002359 IdentifierInfo *II = Tok.getIdentifierInfo();
Chris Lattner645ff3f2007-10-29 04:06:22 +00002360 ConsumeToken();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002361
Anders Carlsson9a020f92010-01-30 22:25:16 +00002362 Names.push_back(II);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002363 T.consumeClose();
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002364 } else
Anders Carlsson9a020f92010-01-30 22:25:16 +00002365 Names.push_back(0);
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002366
John McCalldadc5752010-08-24 06:29:42 +00002367 ExprResult Constraint(ParseAsmStringLiteral());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002368 if (Constraint.isInvalid()) {
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002369 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002370 return true;
Anders Carlsson94ea8aa2007-11-22 01:36:19 +00002371 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002372 Constraints.push_back(Constraint.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002373
Chris Lattnerfeb00b62007-10-09 17:41:39 +00002374 if (Tok.isNot(tok::l_paren)) {
Chris Lattner6d29c102008-11-18 07:48:38 +00002375 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
Chris Lattner0116c472006-08-15 06:03:28 +00002376 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002377 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002378 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002379
Chris Lattner0116c472006-08-15 06:03:28 +00002380 // Read the parenthesized expression.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002381 BalancedDelimiterTracker T(*this, tok::l_paren);
2382 T.consumeOpen();
John McCalldadc5752010-08-24 06:29:42 +00002383 ExprResult Res(ParseExpression());
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002384 T.consumeClose();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002385 if (Res.isInvalid()) {
Chris Lattner0116c472006-08-15 06:03:28 +00002386 SkipUntil(tok::r_paren);
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002387 return true;
Chris Lattner0116c472006-08-15 06:03:28 +00002388 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00002389 Exprs.push_back(Res.release());
Chris Lattner0116c472006-08-15 06:03:28 +00002390 // Eat the comma and continue parsing if it exists.
Anders Carlsson2e64d1a2008-02-09 19:57:29 +00002391 if (Tok.isNot(tok::comma)) return false;
Chris Lattner0116c472006-08-15 06:03:28 +00002392 ConsumeToken();
2393 }
2394}
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002395
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002396Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
Chris Lattner12f2ea52009-03-05 00:49:17 +00002397 assert(Tok.is(tok::l_brace));
2398 SourceLocation LBraceLoc = Tok.getLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002399
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00002400 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
Richard Smith1ab34b32012-11-19 21:13:18 +00002401 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002402 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002403 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002404 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002405
John McCallfaf5fb42010-08-26 23:41:50 +00002406 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2407 "parsing function body");
Mike Stump11289f42009-09-09 15:08:12 +00002408
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002409 // Do not enter a scope for the brace, as the arguments are in the same scope
2410 // (the function body) as the body itself. Instead, just read the statement
2411 // list and put it into a CompoundStmt for safe keeping.
John McCalldadc5752010-08-24 06:29:42 +00002412 StmtResult FnBody(ParseCompoundStatementBody());
Sebastian Redl042ad952008-12-11 19:30:53 +00002413
Fariborz Jahanian8e632942007-11-08 19:01:26 +00002414 // If the function body could not be parsed, make a bogus compoundstmt.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002415 if (FnBody.isInvalid()) {
2416 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002417 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002418 }
Sebastian Redl042ad952008-12-11 19:30:53 +00002419
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002420 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002421 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Seo Sanghyeon34f92ac2007-12-01 08:06:07 +00002422}
Sebastian Redlb219c902008-12-21 16:41:36 +00002423
Sebastian Redla7b98a72009-04-26 20:35:05 +00002424/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2425///
2426/// function-try-block:
2427/// 'try' ctor-initializer[opt] compound-statement handler-seq
2428///
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002429Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
Sebastian Redla7b98a72009-04-26 20:35:05 +00002430 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2431 SourceLocation TryLoc = ConsumeToken();
2432
John McCallfaf5fb42010-08-26 23:41:50 +00002433 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2434 "parsing function try block");
Sebastian Redla7b98a72009-04-26 20:35:05 +00002435
2436 // Constructor initializer list?
2437 if (Tok.is(tok::colon))
2438 ParseConstructorInitializer(Decl);
Douglas Gregor5ca153f2011-09-07 20:36:12 +00002439 else
2440 Actions.ActOnDefaultCtorInitializers(Decl);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002441
Richard Smith1ab34b32012-11-19 21:13:18 +00002442 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2443 trySkippingFunctionBody()) {
Erik Verbruggen6e922512012-04-12 10:11:59 +00002444 BodyScope.Exit();
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00002445 return Actions.ActOnSkippedFunctionBody(Decl);
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002446 }
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002447
Sebastian Redld98ecd62009-04-26 21:08:36 +00002448 SourceLocation LBraceLoc = Tok.getLocation();
David Blaikie1c9c9042012-11-10 01:04:23 +00002449 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
Sebastian Redla7b98a72009-04-26 20:35:05 +00002450 // If we failed to parse the try-catch, we just give the function an empty
2451 // compound statement as the body.
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002452 if (FnBody.isInvalid()) {
2453 Sema::CompoundScopeRAII CompoundScope(Actions);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +00002454 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002455 }
Sebastian Redla7b98a72009-04-26 20:35:05 +00002456
Douglas Gregora0ff0c32011-03-16 17:05:57 +00002457 BodyScope.Exit();
John McCallb268a282010-08-23 23:25:46 +00002458 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
Sebastian Redla7b98a72009-04-26 20:35:05 +00002459}
2460
Erik Verbruggen6e922512012-04-12 10:11:59 +00002461bool Parser::trySkippingFunctionBody() {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002462 assert(Tok.is(tok::l_brace));
Erik Verbruggen6e922512012-04-12 10:11:59 +00002463 assert(SkipFunctionBodies &&
2464 "Should only be called when SkipFunctionBodies is enabled");
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002465
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002466 if (!PP.isCodeCompletionEnabled()) {
2467 ConsumeBrace();
2468 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false);
2469 return true;
2470 }
2471
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002472 // We're in code-completion mode. Skip parsing for all function bodies unless
2473 // the body contains the code-completion point.
2474 TentativeParsingAction PA(*this);
2475 ConsumeBrace();
2476 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
Argyrios Kyrtzidis289e4a32012-10-31 17:29:28 +00002477 /*StopAtCodeCompletion=*/true)) {
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00002478 PA.Commit();
2479 return true;
2480 }
2481
2482 PA.Revert();
2483 return false;
2484}
2485
Sebastian Redlb219c902008-12-21 16:41:36 +00002486/// ParseCXXTryBlock - Parse a C++ try-block.
2487///
2488/// try-block:
2489/// 'try' compound-statement handler-seq
2490///
Richard Smithc202b282012-04-14 00:33:13 +00002491StmtResult Parser::ParseCXXTryBlock() {
Sebastian Redlb219c902008-12-21 16:41:36 +00002492 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2493
2494 SourceLocation TryLoc = ConsumeToken();
Sebastian Redla7b98a72009-04-26 20:35:05 +00002495 return ParseCXXTryBlockCommon(TryLoc);
2496}
2497
2498/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2499/// function-try-block.
2500///
2501/// try-block:
2502/// 'try' compound-statement handler-seq
2503///
2504/// function-try-block:
2505/// 'try' ctor-initializer[opt] compound-statement handler-seq
2506///
2507/// handler-seq:
2508/// handler handler-seq[opt]
2509///
John Wiegley1c0675e2011-04-28 01:08:34 +00002510/// [Borland] try-block:
2511/// 'try' compound-statement seh-except-block
2512/// 'try' compound-statment seh-finally-block
2513///
David Blaikie1c9c9042012-11-10 01:04:23 +00002514StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002515 if (Tok.isNot(tok::l_brace))
2516 return StmtError(Diag(Tok, diag::err_expected_lbrace));
Alexis Hunt96d5c762009-11-21 08:43:09 +00002517 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002518
2519 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
David Blaikie3403feb2012-11-13 18:51:45 +00002520 Scope::DeclScope | Scope::TryScope |
2521 (FnTry ? Scope::FnTryCatchScope : 0)));
Sebastian Redlb219c902008-12-21 16:41:36 +00002522 if (TryBlock.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002523 return TryBlock;
Sebastian Redlb219c902008-12-21 16:41:36 +00002524
John Wiegley1c0675e2011-04-28 01:08:34 +00002525 // Borland allows SEH-handlers with 'try'
Chad Rosier67055f52012-07-10 21:35:27 +00002526
Richard Smithc202b282012-04-14 00:33:13 +00002527 if ((Tok.is(tok::identifier) &&
2528 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2529 Tok.is(tok::kw___finally)) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002530 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2531 StmtResult Handler;
Douglas Gregor60060d62011-10-21 03:57:52 +00002532 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
John Wiegley1c0675e2011-04-28 01:08:34 +00002533 SourceLocation Loc = ConsumeToken();
2534 Handler = ParseSEHExceptBlock(Loc);
2535 }
2536 else {
2537 SourceLocation Loc = ConsumeToken();
2538 Handler = ParseSEHFinallyBlock(Loc);
2539 }
2540 if(Handler.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002541 return Handler;
John McCall53fa7142010-12-24 02:08:15 +00002542
John Wiegley1c0675e2011-04-28 01:08:34 +00002543 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2544 TryLoc,
2545 TryBlock.take(),
2546 Handler.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002547 }
John Wiegley1c0675e2011-04-28 01:08:34 +00002548 else {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002549 StmtVector Handlers;
Richard Smithc202b282012-04-14 00:33:13 +00002550 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002551 MaybeParseCXX11Attributes(attrs);
John Wiegley1c0675e2011-04-28 01:08:34 +00002552 ProhibitAttributes(attrs);
Sebastian Redlb219c902008-12-21 16:41:36 +00002553
John Wiegley1c0675e2011-04-28 01:08:34 +00002554 if (Tok.isNot(tok::kw_catch))
2555 return StmtError(Diag(Tok, diag::err_expected_catch));
2556 while (Tok.is(tok::kw_catch)) {
David Blaikie1c9c9042012-11-10 01:04:23 +00002557 StmtResult Handler(ParseCXXCatchBlock(FnTry));
John Wiegley1c0675e2011-04-28 01:08:34 +00002558 if (!Handler.isInvalid())
2559 Handlers.push_back(Handler.release());
2560 }
2561 // Don't bother creating the full statement if we don't have any usable
2562 // handlers.
2563 if (Handlers.empty())
2564 return StmtError();
2565
Robert Wilhelmcafda822013-08-22 09:20:03 +00002566 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
John Wiegley1c0675e2011-04-28 01:08:34 +00002567 }
Sebastian Redlb219c902008-12-21 16:41:36 +00002568}
2569
2570/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2571///
Richard Smith1dba27c2013-01-29 09:02:09 +00002572/// handler:
2573/// 'catch' '(' exception-declaration ')' compound-statement
Sebastian Redlb219c902008-12-21 16:41:36 +00002574///
Richard Smith1dba27c2013-01-29 09:02:09 +00002575/// exception-declaration:
2576/// attribute-specifier-seq[opt] type-specifier-seq declarator
2577/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2578/// '...'
Sebastian Redlb219c902008-12-21 16:41:36 +00002579///
David Blaikie1c9c9042012-11-10 01:04:23 +00002580StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
Sebastian Redlb219c902008-12-21 16:41:36 +00002581 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2582
2583 SourceLocation CatchLoc = ConsumeToken();
2584
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002585 BalancedDelimiterTracker T(*this, tok::l_paren);
2586 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redlb219c902008-12-21 16:41:36 +00002587 return StmtError();
2588
2589 // C++ 3.3.2p3:
2590 // The name in a catch exception-declaration is local to the handler and
2591 // shall not be redeclared in the outermost block of the handler.
David Blaikie1c9c9042012-11-10 01:04:23 +00002592 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
David Blaikie3403feb2012-11-13 18:51:45 +00002593 (FnCatch ? Scope::FnTryCatchScope : 0));
Sebastian Redlb219c902008-12-21 16:41:36 +00002594
2595 // exception-declaration is equivalent to '...' or a parameter-declaration
2596 // without default arguments.
John McCall48871652010-08-21 09:40:31 +00002597 Decl *ExceptionDecl = 0;
Sebastian Redlb219c902008-12-21 16:41:36 +00002598 if (Tok.isNot(tok::ellipsis)) {
Richard Smith1dba27c2013-01-29 09:02:09 +00002599 ParsedAttributesWithRange Attributes(AttrFactory);
2600 MaybeParseCXX11Attributes(Attributes);
2601
John McCall084e83d2011-03-24 11:26:52 +00002602 DeclSpec DS(AttrFactory);
Richard Smith1dba27c2013-01-29 09:02:09 +00002603 DS.takeAttributesFrom(Attributes);
2604
Sebastian Redl54c04d42008-12-22 19:15:10 +00002605 if (ParseCXXTypeSpecifierSeq(DS))
2606 return StmtError();
Richard Smith1dba27c2013-01-29 09:02:09 +00002607
Sebastian Redlb219c902008-12-21 16:41:36 +00002608 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2609 ParseDeclarator(ExDecl);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002610 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
Sebastian Redlb219c902008-12-21 16:41:36 +00002611 } else
2612 ConsumeToken();
2613
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002614 T.consumeClose();
2615 if (T.getCloseLocation().isInvalid())
Sebastian Redlb219c902008-12-21 16:41:36 +00002616 return StmtError();
2617
2618 if (Tok.isNot(tok::l_brace))
2619 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2620
Alexis Hunt96d5c762009-11-21 08:43:09 +00002621 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
Richard Smithc202b282012-04-14 00:33:13 +00002622 StmtResult Block(ParseCompoundStatement());
Sebastian Redlb219c902008-12-21 16:41:36 +00002623 if (Block.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002624 return Block;
Sebastian Redlb219c902008-12-21 16:41:36 +00002625
John McCallb268a282010-08-23 23:25:46 +00002626 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
Sebastian Redlb219c902008-12-21 16:41:36 +00002627}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002628
2629void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
Douglas Gregor43edb322011-10-24 22:31:10 +00002630 IfExistsCondition Result;
Francois Picheta5b3fcb2011-05-07 17:30:27 +00002631 if (ParseMicrosoftIfExistsCondition(Result))
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002632 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002633
Douglas Gregor43edb322011-10-24 22:31:10 +00002634 // Handle dependent statements by parsing the braces as a compound statement.
2635 // This is not the same behavior as Visual C++, which don't treat this as a
2636 // compound statement, but for Clang's type checking we can't have anything
2637 // inside these braces escaping to the surrounding code.
2638 if (Result.Behavior == IEB_Dependent) {
2639 if (!Tok.is(tok::l_brace)) {
2640 Diag(Tok, diag::err_expected_lbrace);
Richard Smithc202b282012-04-14 00:33:13 +00002641 return;
Douglas Gregor43edb322011-10-24 22:31:10 +00002642 }
Richard Smithc202b282012-04-14 00:33:13 +00002643
2644 StmtResult Compound = ParseCompoundStatement();
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002645 if (Compound.isInvalid())
2646 return;
Richard Smithc202b282012-04-14 00:33:13 +00002647
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002648 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2649 Result.IsIfExists,
Richard Smithc202b282012-04-14 00:33:13 +00002650 Result.SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002651 Result.Name,
2652 Compound.get());
2653 if (DepResult.isUsable())
2654 Stmts.push_back(DepResult.get());
Douglas Gregor43edb322011-10-24 22:31:10 +00002655 return;
2656 }
Richard Smithc202b282012-04-14 00:33:13 +00002657
Douglas Gregor43edb322011-10-24 22:31:10 +00002658 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2659 if (Braces.consumeOpen()) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002660 Diag(Tok, diag::err_expected_lbrace);
2661 return;
2662 }
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002663
Douglas Gregor43edb322011-10-24 22:31:10 +00002664 switch (Result.Behavior) {
2665 case IEB_Parse:
2666 // Parse the statements below.
2667 break;
Chad Rosier67055f52012-07-10 21:35:27 +00002668
Douglas Gregor43edb322011-10-24 22:31:10 +00002669 case IEB_Dependent:
2670 llvm_unreachable("Dependent case handled above");
Chad Rosier67055f52012-07-10 21:35:27 +00002671
Douglas Gregor43edb322011-10-24 22:31:10 +00002672 case IEB_Skip:
2673 Braces.skipToEnd();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002674 return;
2675 }
2676
2677 // Condition is true, parse the statements.
2678 while (Tok.isNot(tok::r_brace)) {
2679 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2680 if (R.isUsable())
2681 Stmts.push_back(R.release());
2682 }
Douglas Gregor43edb322011-10-24 22:31:10 +00002683 Braces.consumeClose();
Francois Pichet4a7de3e2011-05-06 20:48:22 +00002684}