1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Statement and Block portions of the Parser
13 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/Attributes.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Parse/Parser.h"
18 #include "clang/Parse/RAIIObjectsForParser.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/LoopHint.h"
21 #include "clang/Sema/PrettyDeclStackTrace.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/TypoCorrection.h"
24 using namespace clang;
26 //===----------------------------------------------------------------------===//
27 // C99 6.8: Statements and Blocks.
28 //===----------------------------------------------------------------------===//
30 /// \brief Parse a standalone statement (for instance, as the body of an 'if',
31 /// 'while', or 'for').
32 StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
33 bool AllowOpenMPStandalone) {
36 // We may get back a null statement if we found a #pragma. Keep going until
37 // we get an actual statement.
40 Res = ParseStatementOrDeclaration(
41 Stmts, AllowOpenMPStandalone ? ACK_StatementsOpenMPAnyExecutable
42 : ACK_StatementsOpenMPNonStandalone,
44 } while (!Res.isInvalid() && !Res.get());
49 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
50 /// StatementOrDeclaration:
56 /// compound-statement
57 /// expression-statement
58 /// selection-statement
59 /// iteration-statement
61 /// [C++] declaration-statement
63 /// [MS] seh-try-block
64 /// [OBC] objc-throw-statement
65 /// [OBC] objc-try-catch-statement
66 /// [OBC] objc-synchronized-statement
67 /// [GNU] asm-statement
68 /// [OMP] openmp-construct [TODO]
70 /// labeled-statement:
71 /// identifier ':' statement
72 /// 'case' constant-expression ':' statement
73 /// 'default' ':' statement
75 /// selection-statement:
79 /// iteration-statement:
84 /// expression-statement:
85 /// expression[opt] ';'
88 /// 'goto' identifier ';'
91 /// 'return' expression[opt] ';'
92 /// [GNU] 'goto' '*' expression ';'
94 /// [OBC] objc-throw-statement:
95 /// [OBC] '@' 'throw' expression ';'
96 /// [OBC] '@' 'throw' ';'
99 Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
100 AllowedConstructsKind Allowed,
101 SourceLocation *TrailingElseLoc) {
103 ParenBraceBracketBalancer BalancerRAIIObj(*this);
105 ParsedAttributesWithRange Attrs(AttrFactory);
106 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
107 if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
110 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
111 Stmts, Allowed, TrailingElseLoc, Attrs);
113 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
114 "attributes on empty statement");
116 if (Attrs.empty() || Res.isInvalid())
119 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
123 class StatementFilterCCC : public CorrectionCandidateCallback {
125 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
126 WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
127 tok::identifier, tok::star, tok::amp);
128 WantExpressionKeywords =
129 nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
130 WantRemainingKeywords =
131 nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
132 WantCXXNamedCasts = false;
135 bool ValidateCandidate(const TypoCorrection &candidate) override {
136 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
137 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
138 if (NextToken.is(tok::equal))
139 return candidate.getCorrectionDeclAs<VarDecl>();
140 if (NextToken.is(tok::period) &&
141 candidate.getCorrectionDeclAs<NamespaceDecl>())
143 return CorrectionCandidateCallback::ValidateCandidate(candidate);
152 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
153 AllowedConstructsKind Allowed, SourceLocation *TrailingElseLoc,
154 ParsedAttributesWithRange &Attrs) {
155 const char *SemiError = nullptr;
158 // Cases in this switch statement should fall through if the parser expects
159 // the token to end in a semicolon (in which case SemiError should be set),
160 // or they directly 'return;' if not.
162 tok::TokenKind Kind = Tok.getKind();
163 SourceLocation AtLoc;
165 case tok::at: // May be a @try or @throw statement
167 ProhibitAttributes(Attrs); // TODO: is it correct?
168 AtLoc = ConsumeToken(); // consume @
169 return ParseObjCAtStatement(AtLoc);
172 case tok::code_completion:
173 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
177 case tok::identifier: {
178 Token Next = NextToken();
179 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
180 // identifier ':' statement
181 return ParseLabeledStatement(Attrs);
184 // Look up the identifier, and typo-correct it to a keyword if it's not
186 if (Next.isNot(tok::coloncolon)) {
187 // Try to limit which sets of keywords should be included in typo
188 // correction based on what the next token is.
189 if (TryAnnotateName(/*IsAddressOfOperand*/ false,
190 llvm::make_unique<StatementFilterCCC>(Next)) ==
192 // Handle errors here by skipping up to the next semicolon or '}', and
193 // eat the semicolon if that's what stopped us.
194 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
195 if (Tok.is(tok::semi))
200 // If the identifier was typo-corrected, try again.
201 if (Tok.isNot(tok::identifier))
209 if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
210 Allowed == ACK_Any) &&
211 isDeclarationStatement()) {
212 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
213 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
215 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
218 if (Tok.is(tok::r_brace)) {
219 Diag(Tok, diag::err_expected_statement);
223 return ParseExprStatement();
226 case tok::kw_case: // C99 6.8.1: labeled-statement
227 return ParseCaseStatement();
228 case tok::kw_default: // C99 6.8.1: labeled-statement
229 return ParseDefaultStatement();
231 case tok::l_brace: // C99 6.8.2: compound-statement
232 return ParseCompoundStatement();
233 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
234 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
235 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
238 case tok::kw_if: // C99 6.8.4.1: if-statement
239 return ParseIfStatement(TrailingElseLoc);
240 case tok::kw_switch: // C99 6.8.4.2: switch-statement
241 return ParseSwitchStatement(TrailingElseLoc);
243 case tok::kw_while: // C99 6.8.5.1: while-statement
244 return ParseWhileStatement(TrailingElseLoc);
245 case tok::kw_do: // C99 6.8.5.2: do-statement
246 Res = ParseDoStatement();
247 SemiError = "do/while";
249 case tok::kw_for: // C99 6.8.5.3: for-statement
250 return ParseForStatement(TrailingElseLoc);
252 case tok::kw_goto: // C99 6.8.6.1: goto-statement
253 Res = ParseGotoStatement();
256 case tok::kw_continue: // C99 6.8.6.2: continue-statement
257 Res = ParseContinueStatement();
258 SemiError = "continue";
260 case tok::kw_break: // C99 6.8.6.3: break-statement
261 Res = ParseBreakStatement();
264 case tok::kw_return: // C99 6.8.6.4: return-statement
265 Res = ParseReturnStatement();
266 SemiError = "return";
268 case tok::kw_co_return: // C++ Coroutines: co_return statement
269 Res = ParseReturnStatement();
270 SemiError = "co_return";
274 ProhibitAttributes(Attrs);
276 Res = ParseAsmStatement(msAsm);
277 Res = Actions.ActOnFinishFullStmt(Res.get());
278 if (msAsm) return Res;
283 case tok::kw___if_exists:
284 case tok::kw___if_not_exists:
285 ProhibitAttributes(Attrs);
286 ParseMicrosoftIfExistsStatement(Stmts);
287 // An __if_exists block is like a compound statement, but it doesn't create
291 case tok::kw_try: // C++ 15: try-block
292 return ParseCXXTryBlock();
295 ProhibitAttributes(Attrs); // TODO: is it correct?
296 return ParseSEHTryBlock();
298 case tok::kw___leave:
299 Res = ParseSEHLeaveStatement();
300 SemiError = "__leave";
303 case tok::annot_pragma_vis:
304 ProhibitAttributes(Attrs);
305 HandlePragmaVisibility();
308 case tok::annot_pragma_pack:
309 ProhibitAttributes(Attrs);
313 case tok::annot_pragma_msstruct:
314 ProhibitAttributes(Attrs);
315 HandlePragmaMSStruct();
318 case tok::annot_pragma_align:
319 ProhibitAttributes(Attrs);
323 case tok::annot_pragma_weak:
324 ProhibitAttributes(Attrs);
328 case tok::annot_pragma_weakalias:
329 ProhibitAttributes(Attrs);
330 HandlePragmaWeakAlias();
333 case tok::annot_pragma_redefine_extname:
334 ProhibitAttributes(Attrs);
335 HandlePragmaRedefineExtname();
338 case tok::annot_pragma_fp_contract:
339 ProhibitAttributes(Attrs);
340 Diag(Tok, diag::err_pragma_fp_contract_scope);
344 case tok::annot_pragma_fp:
345 ProhibitAttributes(Attrs);
346 Diag(Tok, diag::err_pragma_fp_scope);
350 case tok::annot_pragma_opencl_extension:
351 ProhibitAttributes(Attrs);
352 HandlePragmaOpenCLExtension();
355 case tok::annot_pragma_captured:
356 ProhibitAttributes(Attrs);
357 return HandlePragmaCaptured();
359 case tok::annot_pragma_openmp:
360 ProhibitAttributes(Attrs);
361 return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
363 case tok::annot_pragma_ms_pointers_to_members:
364 ProhibitAttributes(Attrs);
365 HandlePragmaMSPointersToMembers();
368 case tok::annot_pragma_ms_pragma:
369 ProhibitAttributes(Attrs);
370 HandlePragmaMSPragma();
373 case tok::annot_pragma_ms_vtordisp:
374 ProhibitAttributes(Attrs);
375 HandlePragmaMSVtorDisp();
378 case tok::annot_pragma_loop_hint:
379 ProhibitAttributes(Attrs);
380 return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
382 case tok::annot_pragma_dump:
387 // If we reached this code, the statement must end in a semicolon.
388 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
389 // If the result was valid, then we do want to diagnose this. Use
390 // ExpectAndConsume to emit the diagnostic, even though we know it won't
392 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
393 // Skip until we see a } or ;, but don't eat it.
394 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
400 /// \brief Parse an expression statement.
401 StmtResult Parser::ParseExprStatement() {
402 // If a case keyword is missing, this is where it should be inserted.
403 Token OldToken = Tok;
405 ExprStatementTokLoc = Tok.getLocation();
407 // expression[opt] ';'
408 ExprResult Expr(ParseExpression());
409 if (Expr.isInvalid()) {
410 // If the expression is invalid, skip ahead to the next semicolon or '}'.
411 // Not doing this opens us up to the possibility of infinite loops if
412 // ParseExpression does not consume any tokens.
413 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
414 if (Tok.is(tok::semi))
416 return Actions.ActOnExprStmtError();
419 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
420 Actions.CheckCaseExpression(Expr.get())) {
421 // If a constant expression is followed by a colon inside a switch block,
422 // suggest a missing case keyword.
423 Diag(OldToken, diag::err_expected_case_before_expression)
424 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
426 // Recover parsing as a case statement.
427 return ParseCaseStatement(/*MissingCase=*/true, Expr);
430 // Otherwise, eat the semicolon.
431 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
432 return Actions.ActOnExprStmt(Expr);
435 /// ParseSEHTryBlockCommon
438 /// '__try' compound-statement seh-handler
442 /// seh-finally-block
444 StmtResult Parser::ParseSEHTryBlock() {
445 assert(Tok.is(tok::kw___try) && "Expected '__try'");
446 SourceLocation TryLoc = ConsumeToken();
448 if (Tok.isNot(tok::l_brace))
449 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
451 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
452 Scope::DeclScope | Scope::SEHTryScope));
453 if(TryBlock.isInvalid())
457 if (Tok.is(tok::identifier) &&
458 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
459 SourceLocation Loc = ConsumeToken();
460 Handler = ParseSEHExceptBlock(Loc);
461 } else if (Tok.is(tok::kw___finally)) {
462 SourceLocation Loc = ConsumeToken();
463 Handler = ParseSEHFinallyBlock(Loc);
465 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
468 if(Handler.isInvalid())
471 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
477 /// ParseSEHExceptBlock - Handle __except
479 /// seh-except-block:
480 /// '__except' '(' seh-filter-expression ')' compound-statement
482 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
483 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
484 raii2(Ident___exception_code, false),
485 raii3(Ident_GetExceptionCode, false);
487 if (ExpectAndConsume(tok::l_paren))
490 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
491 Scope::SEHExceptScope);
493 if (getLangOpts().Borland) {
494 Ident__exception_info->setIsPoisoned(false);
495 Ident___exception_info->setIsPoisoned(false);
496 Ident_GetExceptionInfo->setIsPoisoned(false);
499 ExprResult FilterExpr;
501 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
502 Scope::SEHFilterScope);
503 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
506 if (getLangOpts().Borland) {
507 Ident__exception_info->setIsPoisoned(true);
508 Ident___exception_info->setIsPoisoned(true);
509 Ident_GetExceptionInfo->setIsPoisoned(true);
512 if(FilterExpr.isInvalid())
515 if (ExpectAndConsume(tok::r_paren))
518 if (Tok.isNot(tok::l_brace))
519 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
521 StmtResult Block(ParseCompoundStatement());
523 if(Block.isInvalid())
526 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
529 /// ParseSEHFinallyBlock - Handle __finally
531 /// seh-finally-block:
532 /// '__finally' compound-statement
534 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
535 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
536 raii2(Ident___abnormal_termination, false),
537 raii3(Ident_AbnormalTermination, false);
539 if (Tok.isNot(tok::l_brace))
540 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
542 ParseScope FinallyScope(this, 0);
543 Actions.ActOnStartSEHFinallyBlock();
545 StmtResult Block(ParseCompoundStatement());
546 if(Block.isInvalid()) {
547 Actions.ActOnAbortSEHFinallyBlock();
551 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
556 /// seh-leave-statement:
559 StmtResult Parser::ParseSEHLeaveStatement() {
560 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
561 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
564 /// ParseLabeledStatement - We have an identifier and a ':' after it.
566 /// labeled-statement:
567 /// identifier ':' statement
568 /// [GNU] identifier ':' attributes[opt] statement
570 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
571 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
572 "Not an identifier!");
574 Token IdentTok = Tok; // Save the whole token.
575 ConsumeToken(); // eat the identifier.
577 assert(Tok.is(tok::colon) && "Not a label!");
579 // identifier ':' statement
580 SourceLocation ColonLoc = ConsumeToken();
582 // Read label attributes, if present.
584 if (Tok.is(tok::kw___attribute)) {
585 ParsedAttributesWithRange TempAttrs(AttrFactory);
586 ParseGNUAttributes(TempAttrs);
588 // In C++, GNU attributes only apply to the label if they are followed by a
589 // semicolon, to disambiguate label attributes from attributes on a labeled
592 // This doesn't quite match what GCC does; if the attribute list is empty
593 // and followed by a semicolon, GCC will reject (it appears to parse the
594 // attributes as part of a statement in that case). That looks like a bug.
595 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
596 attrs.takeAllFrom(TempAttrs);
597 else if (isDeclarationStatement()) {
599 // FIXME: We should do this whether or not we have a declaration
600 // statement, but that doesn't work correctly (because ProhibitAttributes
601 // can't handle GNU attributes), so only call it in the one case where
602 // GNU attributes are allowed.
603 SubStmt = ParseStatementOrDeclarationAfterAttributes(
604 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
606 if (!TempAttrs.empty() && !SubStmt.isInvalid())
607 SubStmt = Actions.ProcessStmtAttributes(
608 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
610 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
614 // If we've not parsed a statement yet, parse one now.
615 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
616 SubStmt = ParseStatement();
618 // Broken substmt shouldn't prevent the label from being added to the AST.
619 if (SubStmt.isInvalid())
620 SubStmt = Actions.ActOnNullStmt(ColonLoc);
622 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
623 IdentTok.getLocation());
624 if (AttributeList *Attrs = attrs.getList()) {
625 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
629 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
633 /// ParseCaseStatement
634 /// labeled-statement:
635 /// 'case' constant-expression ':' statement
636 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
638 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
639 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
641 // It is very very common for code to contain many case statements recursively
642 // nested, as in (but usually without indentation):
649 // Parsing this naively works, but is both inefficient and can cause us to run
650 // out of stack space in our recursive descent parser. As a special case,
651 // flatten this recursion into an iterative loop. This is complex and gross,
652 // but all the grossness is constrained to ParseCaseStatement (and some
653 // weirdness in the actions), so this is just local grossness :).
655 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
657 StmtResult TopLevelCase(true);
659 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
660 // gets updated each time a new case is parsed, and whose body is unset so
661 // far. When parsing 'case 4', this is the 'case 3' node.
662 Stmt *DeepestParsedCaseStmt = nullptr;
664 // While we have case statements, eat and stack them.
665 SourceLocation ColonLoc;
667 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
668 ConsumeToken(); // eat the 'case'.
669 ColonLoc = SourceLocation();
671 if (Tok.is(tok::code_completion)) {
672 Actions.CodeCompleteCase(getCurScope());
677 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
678 /// Disable this form of error recovery while we're parsing the case
680 ColonProtectionRAIIObject ColonProtection(*this);
684 LHS = ParseConstantExpression();
685 if (!getLangOpts().CPlusPlus11) {
686 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
687 return Actions.VerifyIntegerConstantExpression(E);
690 if (LHS.isInvalid()) {
691 // If constant-expression is parsed unsuccessfully, recover by skipping
692 // current case statement (moving to the colon that ends it).
693 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
694 TryConsumeToken(tok::colon, ColonLoc);
704 // GNU case range extension.
705 SourceLocation DotDotDotLoc;
707 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
708 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
709 RHS = ParseConstantExpression();
710 if (RHS.isInvalid()) {
711 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
712 TryConsumeToken(tok::colon, ColonLoc);
719 ColonProtection.restore();
721 if (TryConsumeToken(tok::colon, ColonLoc)) {
722 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
723 TryConsumeToken(tok::coloncolon, ColonLoc)) {
724 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
725 Diag(ColonLoc, diag::err_expected_after)
726 << "'case'" << tok::colon
727 << FixItHint::CreateReplacement(ColonLoc, ":");
729 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
730 Diag(ExpectedLoc, diag::err_expected_after)
731 << "'case'" << tok::colon
732 << FixItHint::CreateInsertion(ExpectedLoc, ":");
733 ColonLoc = ExpectedLoc;
737 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
738 RHS.get(), ColonLoc);
740 // If we had a sema error parsing this case, then just ignore it and
741 // continue parsing the sub-stmt.
742 if (Case.isInvalid()) {
743 if (TopLevelCase.isInvalid()) // No parsed case stmts.
744 return ParseStatement(/*TrailingElseLoc=*/nullptr,
745 /*AllowOpenMPStandalone=*/true);
746 // Otherwise, just don't add it as a nested case.
748 // If this is the first case statement we parsed, it becomes TopLevelCase.
749 // Otherwise we link it into the current chain.
750 Stmt *NextDeepest = Case.get();
751 if (TopLevelCase.isInvalid())
754 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
755 DeepestParsedCaseStmt = NextDeepest;
758 // Handle all case statements.
759 } while (Tok.is(tok::kw_case));
761 // If we found a non-case statement, start by parsing it.
764 if (Tok.isNot(tok::r_brace)) {
765 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
766 /*AllowOpenMPStandalone=*/true);
768 // Nicely diagnose the common error "switch (X) { case 4: }", which is
769 // not valid. If ColonLoc doesn't point to a valid text location, there was
770 // another parsing error, so avoid producing extra diagnostics.
771 if (ColonLoc.isValid()) {
772 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
773 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
774 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
776 SubStmt = StmtError();
779 // Install the body into the most deeply-nested case.
780 if (DeepestParsedCaseStmt) {
781 // Broken sub-stmt shouldn't prevent forming the case statement properly.
782 if (SubStmt.isInvalid())
783 SubStmt = Actions.ActOnNullStmt(SourceLocation());
784 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
787 // Return the top level parsed statement tree.
791 /// ParseDefaultStatement
792 /// labeled-statement:
793 /// 'default' ':' statement
794 /// Note that this does not parse the 'statement' at the end.
796 StmtResult Parser::ParseDefaultStatement() {
797 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
798 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
800 SourceLocation ColonLoc;
801 if (TryConsumeToken(tok::colon, ColonLoc)) {
802 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
803 // Treat "default;" as a typo for "default:".
804 Diag(ColonLoc, diag::err_expected_after)
805 << "'default'" << tok::colon
806 << FixItHint::CreateReplacement(ColonLoc, ":");
808 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
809 Diag(ExpectedLoc, diag::err_expected_after)
810 << "'default'" << tok::colon
811 << FixItHint::CreateInsertion(ExpectedLoc, ":");
812 ColonLoc = ExpectedLoc;
817 if (Tok.isNot(tok::r_brace)) {
818 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
819 /*AllowOpenMPStandalone=*/true);
821 // Diagnose the common error "switch (X) {... default: }", which is
823 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
824 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
825 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
829 // Broken sub-stmt shouldn't prevent forming the case statement properly.
830 if (SubStmt.isInvalid())
831 SubStmt = Actions.ActOnNullStmt(ColonLoc);
833 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
834 SubStmt.get(), getCurScope());
837 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
838 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
841 /// ParseCompoundStatement - Parse a "{}" block.
843 /// compound-statement: [C99 6.8.2]
844 /// { block-item-list[opt] }
845 /// [GNU] { label-declarations block-item-list } [TODO]
849 /// block-item-list block-item
853 /// [GNU] '__extension__' declaration
856 /// [GNU] label-declarations:
857 /// [GNU] label-declaration
858 /// [GNU] label-declarations label-declaration
860 /// [GNU] label-declaration:
861 /// [GNU] '__label__' identifier-list ';'
863 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
864 unsigned ScopeFlags) {
865 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
867 // Enter a scope to hold everything within the compound stmt. Compound
868 // statements can always hold declarations.
869 ParseScope CompoundScope(this, ScopeFlags);
871 // Parse the statements in the body.
872 return ParseCompoundStatementBody(isStmtExpr);
875 /// Parse any pragmas at the start of the compound expression. We handle these
876 /// separately since some pragmas (FP_CONTRACT) must appear before any C
877 /// statement in the compound, but may be intermingled with other pragmas.
878 void Parser::ParseCompoundStatementLeadingPragmas() {
879 bool checkForPragmas = true;
880 while (checkForPragmas) {
881 switch (Tok.getKind()) {
882 case tok::annot_pragma_vis:
883 HandlePragmaVisibility();
885 case tok::annot_pragma_pack:
888 case tok::annot_pragma_msstruct:
889 HandlePragmaMSStruct();
891 case tok::annot_pragma_align:
894 case tok::annot_pragma_weak:
897 case tok::annot_pragma_weakalias:
898 HandlePragmaWeakAlias();
900 case tok::annot_pragma_redefine_extname:
901 HandlePragmaRedefineExtname();
903 case tok::annot_pragma_opencl_extension:
904 HandlePragmaOpenCLExtension();
906 case tok::annot_pragma_fp_contract:
907 HandlePragmaFPContract();
909 case tok::annot_pragma_fp:
912 case tok::annot_pragma_ms_pointers_to_members:
913 HandlePragmaMSPointersToMembers();
915 case tok::annot_pragma_ms_pragma:
916 HandlePragmaMSPragma();
918 case tok::annot_pragma_ms_vtordisp:
919 HandlePragmaMSVtorDisp();
921 case tok::annot_pragma_dump:
925 checkForPragmas = false;
932 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
933 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
934 /// consume the '}' at the end of the block. It does not manipulate the scope
936 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
937 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
939 "in compound statement ('{}')");
941 // Record the state of the FP_CONTRACT pragma, restore on leaving the
942 // compound statement.
943 Sema::FPContractStateRAII SaveFPContractState(Actions);
945 InMessageExpressionRAIIObject InMessage(*this, false);
946 BalancedDelimiterTracker T(*this, tok::l_brace);
950 Sema::CompoundScopeRAII CompoundScope(Actions);
952 // Parse any pragmas at the beginning of the compound statement.
953 ParseCompoundStatementLeadingPragmas();
957 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
958 // only allowed at the start of a compound stmt regardless of the language.
959 while (Tok.is(tok::kw___label__)) {
960 SourceLocation LabelLoc = ConsumeToken();
962 SmallVector<Decl *, 8> DeclsInGroup;
964 if (Tok.isNot(tok::identifier)) {
965 Diag(Tok, diag::err_expected) << tok::identifier;
969 IdentifierInfo *II = Tok.getIdentifierInfo();
970 SourceLocation IdLoc = ConsumeToken();
971 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
973 if (!TryConsumeToken(tok::comma))
977 DeclSpec DS(AttrFactory);
979 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
980 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
982 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
984 Stmts.push_back(R.get());
987 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
988 Tok.isNot(tok::eof)) {
989 if (Tok.is(tok::annot_pragma_unused)) {
990 HandlePragmaUnused();
995 if (Tok.isNot(tok::kw___extension__)) {
996 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
998 // __extension__ can start declarations and it can also be a unary
999 // operator for expressions. Consume multiple __extension__ markers here
1000 // until we can determine which is which.
1001 // FIXME: This loses extension expressions in the AST!
1002 SourceLocation ExtLoc = ConsumeToken();
1003 while (Tok.is(tok::kw___extension__))
1006 ParsedAttributesWithRange attrs(AttrFactory);
1007 MaybeParseCXX11Attributes(attrs, nullptr,
1008 /*MightBeObjCMessageSend*/ true);
1010 // If this is the start of a declaration, parse it as such.
1011 if (isDeclarationStatement()) {
1012 // __extension__ silences extension warnings in the subdeclaration.
1013 // FIXME: Save the __extension__ on the decl as a node somehow?
1014 ExtensionRAIIObject O(Diags);
1016 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1017 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
1019 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1021 // Otherwise this was a unary __extension__ marker.
1022 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1024 if (Res.isInvalid()) {
1025 SkipUntil(tok::semi);
1029 // FIXME: Use attributes?
1030 // Eat the semicolon at the end of stmt and convert the expr into a
1032 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1033 R = Actions.ActOnExprStmt(Res);
1038 Stmts.push_back(R.get());
1041 SourceLocation CloseLoc = Tok.getLocation();
1043 // We broke out of the while loop because we found a '}' or EOF.
1044 if (!T.consumeClose())
1045 // Recover by creating a compound statement with what we parsed so far,
1046 // instead of dropping everything and returning StmtError();
1047 CloseLoc = T.getCloseLocation();
1049 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1053 /// ParseParenExprOrCondition:
1054 /// [C ] '(' expression ')'
1055 /// [C++] '(' condition ')'
1056 /// [C++1z] '(' init-statement[opt] condition ')'
1058 /// This function parses and performs error recovery on the specified condition
1059 /// or expression (depending on whether we're in C++ or C mode). This function
1060 /// goes out of its way to recover well. It returns true if there was a parser
1061 /// error (the right paren couldn't be found), which indicates that the caller
1062 /// should try to recover harder. It returns false if the condition is
1063 /// successfully parsed. Note that a successful parse can still have semantic
1064 /// errors in the condition.
1065 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1066 Sema::ConditionResult &Cond,
1068 Sema::ConditionKind CK) {
1069 BalancedDelimiterTracker T(*this, tok::l_paren);
1072 if (getLangOpts().CPlusPlus)
1073 Cond = ParseCXXCondition(InitStmt, Loc, CK);
1075 ExprResult CondExpr = ParseExpression();
1077 // If required, convert to a boolean value.
1078 if (CondExpr.isInvalid())
1079 Cond = Sema::ConditionError();
1081 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1084 // If the parser was confused by the condition and we don't have a ')', try to
1085 // recover by skipping ahead to a semi and bailing out. If condexp is
1086 // semantically invalid but we have well formed code, keep going.
1087 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1088 SkipUntil(tok::semi);
1089 // Skipping may have stopped if it found the containing ')'. If so, we can
1090 // continue parsing the if statement.
1091 if (Tok.isNot(tok::r_paren))
1095 // Otherwise the condition is valid or the rparen is present.
1098 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1099 // that all callers are looking for a statement after the condition, so ")"
1101 while (Tok.is(tok::r_paren)) {
1102 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1103 << FixItHint::CreateRemoval(Tok.getLocation());
1111 /// ParseIfStatement
1112 /// if-statement: [C99 6.8.4.1]
1113 /// 'if' '(' expression ')' statement
1114 /// 'if' '(' expression ')' statement 'else' statement
1115 /// [C++] 'if' '(' condition ')' statement
1116 /// [C++] 'if' '(' condition ')' statement 'else' statement
1118 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1119 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1120 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1122 bool IsConstexpr = false;
1123 if (Tok.is(tok::kw_constexpr)) {
1124 Diag(Tok, getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_constexpr_if
1125 : diag::ext_constexpr_if);
1130 if (Tok.isNot(tok::l_paren)) {
1131 Diag(Tok, diag::err_expected_lparen_after) << "if";
1132 SkipUntil(tok::semi);
1136 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1138 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1139 // the case for C90.
1142 // A name introduced by a declaration in a condition is in scope from its
1143 // point of declaration until the end of the substatements controlled by the
1146 // Names declared in the for-init-statement, and in the condition of if,
1147 // while, for, and switch statements are local to the if, while, for, or
1148 // switch statement (including the controlled statement).
1150 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1152 // Parse the condition.
1153 StmtResult InitStmt;
1154 Sema::ConditionResult Cond;
1155 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1156 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1157 : Sema::ConditionKind::Boolean))
1160 llvm::Optional<bool> ConstexprCondition;
1162 ConstexprCondition = Cond.getKnownValue();
1164 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1165 // there is no compound stmt. C90 does not have this clause. We only do this
1166 // if the body isn't a compound statement to avoid push/pop in common cases.
1169 // The substatement in a selection-statement (each substatement, in the else
1170 // form of the if statement) implicitly defines a local scope.
1172 // For C++ we create a scope for the condition and a new scope for
1173 // substatements because:
1174 // -When the 'then' scope exits, we want the condition declaration to still be
1175 // active for the 'else' scope too.
1176 // -Sema will detect name clashes by considering declarations of a
1177 // 'ControlScope' as part of its direct subscope.
1178 // -If we wanted the condition and substatement to be in the same scope, we
1179 // would have to notify ParseStatement not to create a new scope. It's
1180 // simpler to let it create a new scope.
1182 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1184 // Read the 'then' stmt.
1185 SourceLocation ThenStmtLoc = Tok.getLocation();
1187 SourceLocation InnerStatementTrailingElseLoc;
1188 StmtResult ThenStmt;
1190 EnterExpressionEvaluationContext PotentiallyDiscarded(
1191 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1193 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1194 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1197 // Pop the 'if' scope if needed.
1200 // If it has an else, parse it.
1201 SourceLocation ElseLoc;
1202 SourceLocation ElseStmtLoc;
1203 StmtResult ElseStmt;
1205 if (Tok.is(tok::kw_else)) {
1206 if (TrailingElseLoc)
1207 *TrailingElseLoc = Tok.getLocation();
1209 ElseLoc = ConsumeToken();
1210 ElseStmtLoc = Tok.getLocation();
1212 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1213 // there is no compound stmt. C90 does not have this clause. We only do
1214 // this if the body isn't a compound statement to avoid push/pop in common
1218 // The substatement in a selection-statement (each substatement, in the else
1219 // form of the if statement) implicitly defines a local scope.
1221 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1222 Tok.is(tok::l_brace));
1224 EnterExpressionEvaluationContext PotentiallyDiscarded(
1225 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1227 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1228 ElseStmt = ParseStatement();
1230 // Pop the 'else' scope if needed.
1232 } else if (Tok.is(tok::code_completion)) {
1233 Actions.CodeCompleteAfterIf(getCurScope());
1236 } else if (InnerStatementTrailingElseLoc.isValid()) {
1237 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1242 // If the then or else stmt is invalid and the other is valid (and present),
1243 // make turn the invalid one into a null stmt to avoid dropping the other
1244 // part. If both are invalid, return error.
1245 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1246 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1247 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1248 // Both invalid, or one is invalid and other is non-present: return error.
1252 // Now if either are invalid, replace with a ';'.
1253 if (ThenStmt.isInvalid())
1254 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1255 if (ElseStmt.isInvalid())
1256 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1258 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1259 ThenStmt.get(), ElseLoc, ElseStmt.get());
1262 /// ParseSwitchStatement
1263 /// switch-statement:
1264 /// 'switch' '(' expression ')' statement
1265 /// [C++] 'switch' '(' condition ')' statement
1266 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1267 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1268 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1270 if (Tok.isNot(tok::l_paren)) {
1271 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1272 SkipUntil(tok::semi);
1276 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1278 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1279 // not the case for C90. Start the switch scope.
1282 // A name introduced by a declaration in a condition is in scope from its
1283 // point of declaration until the end of the substatements controlled by the
1286 // Names declared in the for-init-statement, and in the condition of if,
1287 // while, for, and switch statements are local to the if, while, for, or
1288 // switch statement (including the controlled statement).
1290 unsigned ScopeFlags = Scope::SwitchScope;
1292 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1293 ParseScope SwitchScope(this, ScopeFlags);
1295 // Parse the condition.
1296 StmtResult InitStmt;
1297 Sema::ConditionResult Cond;
1298 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1299 Sema::ConditionKind::Switch))
1303 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1305 if (Switch.isInvalid()) {
1306 // Skip the switch body.
1307 // FIXME: This is not optimal recovery, but parsing the body is more
1308 // dangerous due to the presence of case and default statements, which
1309 // will have no place to connect back with the switch.
1310 if (Tok.is(tok::l_brace)) {
1312 SkipUntil(tok::r_brace);
1314 SkipUntil(tok::semi);
1318 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1319 // there is no compound stmt. C90 does not have this clause. We only do this
1320 // if the body isn't a compound statement to avoid push/pop in common cases.
1323 // The substatement in a selection-statement (each substatement, in the else
1324 // form of the if statement) implicitly defines a local scope.
1326 // See comments in ParseIfStatement for why we create a scope for the
1327 // condition and a new scope for substatement in C++.
1329 getCurScope()->AddFlags(Scope::BreakScope);
1330 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1332 // We have incremented the mangling number for the SwitchScope and the
1333 // InnerScope, which is one too many.
1335 getCurScope()->decrementMSManglingNumber();
1337 // Read the body statement.
1338 StmtResult Body(ParseStatement(TrailingElseLoc));
1344 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1347 /// ParseWhileStatement
1348 /// while-statement: [C99 6.8.5.1]
1349 /// 'while' '(' expression ')' statement
1350 /// [C++] 'while' '(' condition ')' statement
1351 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1352 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1353 SourceLocation WhileLoc = Tok.getLocation();
1354 ConsumeToken(); // eat the 'while'.
1356 if (Tok.isNot(tok::l_paren)) {
1357 Diag(Tok, diag::err_expected_lparen_after) << "while";
1358 SkipUntil(tok::semi);
1362 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1364 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1365 // the case for C90. Start the loop scope.
1368 // A name introduced by a declaration in a condition is in scope from its
1369 // point of declaration until the end of the substatements controlled by the
1372 // Names declared in the for-init-statement, and in the condition of if,
1373 // while, for, and switch statements are local to the if, while, for, or
1374 // switch statement (including the controlled statement).
1376 unsigned ScopeFlags;
1378 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1379 Scope::DeclScope | Scope::ControlScope;
1381 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1382 ParseScope WhileScope(this, ScopeFlags);
1384 // Parse the condition.
1385 Sema::ConditionResult Cond;
1386 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1387 Sema::ConditionKind::Boolean))
1390 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1391 // there is no compound stmt. C90 does not have this clause. We only do this
1392 // if the body isn't a compound statement to avoid push/pop in common cases.
1395 // The substatement in an iteration-statement implicitly defines a local scope
1396 // which is entered and exited each time through the loop.
1398 // See comments in ParseIfStatement for why we create a scope for the
1399 // condition and a new scope for substatement in C++.
1401 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1403 // Read the body statement.
1404 StmtResult Body(ParseStatement(TrailingElseLoc));
1406 // Pop the body scope if needed.
1410 if (Cond.isInvalid() || Body.isInvalid())
1413 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1416 /// ParseDoStatement
1417 /// do-statement: [C99 6.8.5.2]
1418 /// 'do' statement 'while' '(' expression ')' ';'
1419 /// Note: this lets the caller parse the end ';'.
1420 StmtResult Parser::ParseDoStatement() {
1421 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1422 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1424 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1425 // the case for C90. Start the loop scope.
1426 unsigned ScopeFlags;
1427 if (getLangOpts().C99)
1428 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1430 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1432 ParseScope DoScope(this, ScopeFlags);
1434 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1435 // there is no compound stmt. C90 does not have this clause. We only do this
1436 // if the body isn't a compound statement to avoid push/pop in common cases.
1439 // The substatement in an iteration-statement implicitly defines a local scope
1440 // which is entered and exited each time through the loop.
1442 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1443 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1445 // Read the body statement.
1446 StmtResult Body(ParseStatement());
1448 // Pop the body scope if needed.
1451 if (Tok.isNot(tok::kw_while)) {
1452 if (!Body.isInvalid()) {
1453 Diag(Tok, diag::err_expected_while);
1454 Diag(DoLoc, diag::note_matching) << "'do'";
1455 SkipUntil(tok::semi, StopBeforeMatch);
1459 SourceLocation WhileLoc = ConsumeToken();
1461 if (Tok.isNot(tok::l_paren)) {
1462 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1463 SkipUntil(tok::semi, StopBeforeMatch);
1467 // Parse the parenthesized expression.
1468 BalancedDelimiterTracker T(*this, tok::l_paren);
1471 // A do-while expression is not a condition, so can't have attributes.
1472 DiagnoseAndSkipCXX11Attributes();
1474 ExprResult Cond = ParseExpression();
1478 if (Cond.isInvalid() || Body.isInvalid())
1481 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1482 Cond.get(), T.getCloseLocation());
1485 bool Parser::isForRangeIdentifier() {
1486 assert(Tok.is(tok::identifier));
1488 const Token &Next = NextToken();
1489 if (Next.is(tok::colon))
1492 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1493 TentativeParsingAction PA(*this);
1495 SkipCXX11Attributes();
1496 bool Result = Tok.is(tok::colon);
1504 /// ParseForStatement
1505 /// for-statement: [C99 6.8.5.3]
1506 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1507 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1508 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1511 /// 'co_await'[opt] [Coroutines]
1512 /// '(' for-range-declaration ':' for-range-initializer ')'
1514 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1515 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1517 /// [C++] for-init-statement:
1518 /// [C++] expression-statement
1519 /// [C++] simple-declaration
1521 /// [C++0x] for-range-declaration:
1522 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1523 /// [C++0x] for-range-initializer:
1524 /// [C++0x] expression
1525 /// [C++0x] braced-init-list [TODO]
1526 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1527 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1528 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1530 SourceLocation CoawaitLoc;
1531 if (Tok.is(tok::kw_co_await))
1532 CoawaitLoc = ConsumeToken();
1534 if (Tok.isNot(tok::l_paren)) {
1535 Diag(Tok, diag::err_expected_lparen_after) << "for";
1536 SkipUntil(tok::semi);
1540 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1541 getLangOpts().ObjC1;
1543 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1544 // the case for C90. Start the loop scope.
1547 // A name introduced by a declaration in a condition is in scope from its
1548 // point of declaration until the end of the substatements controlled by the
1551 // Names declared in the for-init-statement, and in the condition of if,
1552 // while, for, and switch statements are local to the if, while, for, or
1553 // switch statement (including the controlled statement).
1555 // Names declared in the for-init-statement are in the same declarative-region
1556 // as those declared in the condition.
1558 unsigned ScopeFlags = 0;
1560 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1562 ParseScope ForScope(this, ScopeFlags);
1564 BalancedDelimiterTracker T(*this, tok::l_paren);
1569 bool ForEach = false, ForRange = false;
1570 StmtResult FirstPart;
1571 Sema::ConditionResult SecondPart;
1572 ExprResult Collection;
1573 ForRangeInit ForRangeInit;
1574 FullExprArg ThirdPart(Actions);
1576 if (Tok.is(tok::code_completion)) {
1577 Actions.CodeCompleteOrdinaryName(getCurScope(),
1578 C99orCXXorObjC? Sema::PCC_ForInit
1579 : Sema::PCC_Expression);
1584 ParsedAttributesWithRange attrs(AttrFactory);
1585 MaybeParseCXX11Attributes(attrs);
1587 // Parse the first part of the for specifier.
1588 if (Tok.is(tok::semi)) { // for (;
1589 ProhibitAttributes(attrs);
1590 // no first part, eat the ';'.
1592 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1593 isForRangeIdentifier()) {
1594 ProhibitAttributes(attrs);
1595 IdentifierInfo *Name = Tok.getIdentifierInfo();
1596 SourceLocation Loc = ConsumeToken();
1597 MaybeParseCXX11Attributes(attrs);
1599 ForRangeInit.ColonLoc = ConsumeToken();
1600 if (Tok.is(tok::l_brace))
1601 ForRangeInit.RangeExpr = ParseBraceInitializer();
1603 ForRangeInit.RangeExpr = ParseExpression();
1605 Diag(Loc, diag::err_for_range_identifier)
1606 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1607 ? FixItHint::CreateInsertion(Loc, "auto &&")
1610 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1611 attrs, attrs.Range.getEnd());
1613 } else if (isForInitDeclaration()) { // for (int X = 4;
1614 // Parse declaration, which eats the ';'.
1615 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1616 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1618 // In C++0x, "for (T NS:a" might not be a typo for ::
1619 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1620 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1622 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1623 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1624 Declarator::ForContext, DeclEnd, attrs, false,
1625 MightBeForRangeStmt ? &ForRangeInit : nullptr);
1626 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1627 if (ForRangeInit.ParsedForRangeDecl()) {
1628 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1629 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1632 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1634 } else if ((ForEach = isTokIdentifier_in())) {
1635 Actions.ActOnForEachDeclStmt(DG);
1636 // ObjC: for (id x in expr)
1637 ConsumeToken(); // consume 'in'
1639 if (Tok.is(tok::code_completion)) {
1640 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1644 Collection = ParseExpression();
1646 Diag(Tok, diag::err_expected_semi_for);
1649 ProhibitAttributes(attrs);
1650 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1652 ForEach = isTokIdentifier_in();
1654 // Turn the expression into a stmt.
1655 if (!Value.isInvalid()) {
1657 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1659 FirstPart = Actions.ActOnExprStmt(Value);
1662 if (Tok.is(tok::semi)) {
1664 } else if (ForEach) {
1665 ConsumeToken(); // consume 'in'
1667 if (Tok.is(tok::code_completion)) {
1668 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1672 Collection = ParseExpression();
1673 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1674 // User tried to write the reasonable, but ill-formed, for-range-statement
1675 // for (expr : expr) { ... }
1676 Diag(Tok, diag::err_for_range_expected_decl)
1677 << FirstPart.get()->getSourceRange();
1678 SkipUntil(tok::r_paren, StopBeforeMatch);
1679 SecondPart = Sema::ConditionError();
1681 if (!Value.isInvalid()) {
1682 Diag(Tok, diag::err_expected_semi_for);
1684 // Skip until semicolon or rparen, don't consume it.
1685 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1686 if (Tok.is(tok::semi))
1692 // Parse the second part of the for specifier.
1693 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1694 if (!ForEach && !ForRange && !SecondPart.isInvalid()) {
1695 // Parse the second part of the for specifier.
1696 if (Tok.is(tok::semi)) { // for (...;;
1698 } else if (Tok.is(tok::r_paren)) {
1699 // missing both semicolons.
1701 if (getLangOpts().CPlusPlus)
1703 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean);
1705 ExprResult SecondExpr = ParseExpression();
1706 if (SecondExpr.isInvalid())
1707 SecondPart = Sema::ConditionError();
1710 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1711 Sema::ConditionKind::Boolean);
1715 if (Tok.isNot(tok::semi)) {
1716 if (!SecondPart.isInvalid())
1717 Diag(Tok, diag::err_expected_semi_for);
1719 // Skip until semicolon or rparen, don't consume it.
1720 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1723 if (Tok.is(tok::semi)) {
1727 // Parse the third part of the for specifier.
1728 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1729 ExprResult Third = ParseExpression();
1730 // FIXME: The C++11 standard doesn't actually say that this is a
1731 // discarded-value expression, but it clearly should be.
1732 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1738 // C++ Coroutines [stmt.iter]:
1739 // 'co_await' can only be used for a range-based for statement.
1740 if (CoawaitLoc.isValid() && !ForRange) {
1741 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1742 CoawaitLoc = SourceLocation();
1745 // We need to perform most of the semantic analysis for a C++0x for-range
1746 // statememt before parsing the body, in order to be able to deduce the type
1747 // of an auto-typed loop variable.
1748 StmtResult ForRangeStmt;
1749 StmtResult ForEachStmt;
1752 ExprResult CorrectedRange =
1753 Actions.CorrectDelayedTyposInExpr(ForRangeInit.RangeExpr.get());
1754 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1755 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1756 ForRangeInit.ColonLoc, CorrectedRange.get(),
1757 T.getCloseLocation(), Sema::BFRK_Build);
1759 // Similarly, we need to do the semantic analysis for a for-range
1760 // statement immediately in order to close over temporaries correctly.
1761 } else if (ForEach) {
1762 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1765 T.getCloseLocation());
1767 // In OpenMP loop region loop control variable must be captured and be
1768 // private. Perform analysis of first part (if any).
1769 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1770 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1774 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1775 // there is no compound stmt. C90 does not have this clause. We only do this
1776 // if the body isn't a compound statement to avoid push/pop in common cases.
1779 // The substatement in an iteration-statement implicitly defines a local scope
1780 // which is entered and exited each time through the loop.
1782 // See comments in ParseIfStatement for why we create a scope for
1783 // for-init-statement/condition and a new scope for substatement in C++.
1785 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1786 Tok.is(tok::l_brace));
1788 // The body of the for loop has the same local mangling number as the
1789 // for-init-statement.
1790 // It will only be incremented if the body contains other things that would
1791 // normally increment the mangling number (like a compound statement).
1793 getCurScope()->decrementMSManglingNumber();
1795 // Read the body statement.
1796 StmtResult Body(ParseStatement(TrailingElseLoc));
1798 // Pop the body scope if needed.
1801 // Leave the for-scope.
1804 if (Body.isInvalid())
1808 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1812 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1814 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1815 SecondPart, ThirdPart, T.getCloseLocation(),
1819 /// ParseGotoStatement
1821 /// 'goto' identifier ';'
1822 /// [GNU] 'goto' '*' expression ';'
1824 /// Note: this lets the caller parse the end ';'.
1826 StmtResult Parser::ParseGotoStatement() {
1827 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1828 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1831 if (Tok.is(tok::identifier)) {
1832 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1834 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1836 } else if (Tok.is(tok::star)) {
1837 // GNU indirect goto extension.
1838 Diag(Tok, diag::ext_gnu_indirect_goto);
1839 SourceLocation StarLoc = ConsumeToken();
1840 ExprResult R(ParseExpression());
1841 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1842 SkipUntil(tok::semi, StopBeforeMatch);
1845 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1847 Diag(Tok, diag::err_expected) << tok::identifier;
1854 /// ParseContinueStatement
1858 /// Note: this lets the caller parse the end ';'.
1860 StmtResult Parser::ParseContinueStatement() {
1861 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1862 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1865 /// ParseBreakStatement
1869 /// Note: this lets the caller parse the end ';'.
1871 StmtResult Parser::ParseBreakStatement() {
1872 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1873 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1876 /// ParseReturnStatement
1878 /// 'return' expression[opt] ';'
1879 /// 'return' braced-init-list ';'
1880 /// 'co_return' expression[opt] ';'
1881 /// 'co_return' braced-init-list ';'
1882 StmtResult Parser::ParseReturnStatement() {
1883 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1884 "Not a return stmt!");
1885 bool IsCoreturn = Tok.is(tok::kw_co_return);
1886 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1889 if (Tok.isNot(tok::semi)) {
1890 // FIXME: Code completion for co_return.
1891 if (Tok.is(tok::code_completion) && !IsCoreturn) {
1892 Actions.CodeCompleteReturn(getCurScope());
1897 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1898 R = ParseInitializer();
1900 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1901 diag::warn_cxx98_compat_generalized_initializer_lists :
1902 diag::ext_generalized_initializer_lists)
1903 << R.get()->getSourceRange();
1905 R = ParseExpression();
1906 if (R.isInvalid()) {
1907 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1912 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
1913 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1916 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1917 AllowedConstructsKind Allowed,
1918 SourceLocation *TrailingElseLoc,
1919 ParsedAttributesWithRange &Attrs) {
1920 // Create temporary attribute list.
1921 ParsedAttributesWithRange TempAttrs(AttrFactory);
1923 // Get loop hints and consume annotated token.
1924 while (Tok.is(tok::annot_pragma_loop_hint)) {
1926 if (!HandlePragmaLoopHint(Hint))
1929 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1930 ArgsUnion(Hint.ValueExpr)};
1931 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1932 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1933 AttributeList::AS_Pragma);
1936 // Get the next statement.
1937 MaybeParseCXX11Attributes(Attrs);
1939 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1940 Stmts, Allowed, TrailingElseLoc, Attrs);
1942 Attrs.takeAllFrom(TempAttrs);
1946 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1947 assert(Tok.is(tok::l_brace));
1948 SourceLocation LBraceLoc = Tok.getLocation();
1950 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1951 "parsing function body");
1953 // Save and reset current vtordisp stack if we have entered a C++ method body.
1955 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1956 Sema::PragmaStackSentinelRAII
1957 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1959 // Do not enter a scope for the brace, as the arguments are in the same scope
1960 // (the function body) as the body itself. Instead, just read the statement
1961 // list and put it into a CompoundStmt for safe keeping.
1962 StmtResult FnBody(ParseCompoundStatementBody());
1964 // If the function body could not be parsed, make a bogus compoundstmt.
1965 if (FnBody.isInvalid()) {
1966 Sema::CompoundScopeRAII CompoundScope(Actions);
1967 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1971 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1974 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1976 /// function-try-block:
1977 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1979 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1980 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1981 SourceLocation TryLoc = ConsumeToken();
1983 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1984 "parsing function try block");
1986 // Constructor initializer list?
1987 if (Tok.is(tok::colon))
1988 ParseConstructorInitializer(Decl);
1990 Actions.ActOnDefaultCtorInitializers(Decl);
1992 // Save and reset current vtordisp stack if we have entered a C++ method body.
1994 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1995 Sema::PragmaStackSentinelRAII
1996 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1998 SourceLocation LBraceLoc = Tok.getLocation();
1999 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2000 // If we failed to parse the try-catch, we just give the function an empty
2001 // compound statement as the body.
2002 if (FnBody.isInvalid()) {
2003 Sema::CompoundScopeRAII CompoundScope(Actions);
2004 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2008 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2011 bool Parser::trySkippingFunctionBody() {
2012 assert(SkipFunctionBodies &&
2013 "Should only be called when SkipFunctionBodies is enabled");
2014 if (!PP.isCodeCompletionEnabled()) {
2019 // We're in code-completion mode. Skip parsing for all function bodies unless
2020 // the body contains the code-completion point.
2021 TentativeParsingAction PA(*this);
2022 bool IsTryCatch = Tok.is(tok::kw_try);
2024 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2025 if (llvm::any_of(Toks, [](const Token &Tok) {
2026 return Tok.is(tok::code_completion);
2031 if (ErrorInPrologue) {
2033 SkipMalformedDecl();
2036 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2040 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2041 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2042 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2051 /// ParseCXXTryBlock - Parse a C++ try-block.
2054 /// 'try' compound-statement handler-seq
2056 StmtResult Parser::ParseCXXTryBlock() {
2057 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2059 SourceLocation TryLoc = ConsumeToken();
2060 return ParseCXXTryBlockCommon(TryLoc);
2063 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2064 /// function-try-block.
2067 /// 'try' compound-statement handler-seq
2069 /// function-try-block:
2070 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2073 /// handler handler-seq[opt]
2075 /// [Borland] try-block:
2076 /// 'try' compound-statement seh-except-block
2077 /// 'try' compound-statement seh-finally-block
2079 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2080 if (Tok.isNot(tok::l_brace))
2081 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2083 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2084 Scope::DeclScope | Scope::TryScope |
2085 (FnTry ? Scope::FnTryCatchScope : 0)));
2086 if (TryBlock.isInvalid())
2089 // Borland allows SEH-handlers with 'try'
2091 if ((Tok.is(tok::identifier) &&
2092 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2093 Tok.is(tok::kw___finally)) {
2094 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2096 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2097 SourceLocation Loc = ConsumeToken();
2098 Handler = ParseSEHExceptBlock(Loc);
2101 SourceLocation Loc = ConsumeToken();
2102 Handler = ParseSEHFinallyBlock(Loc);
2104 if(Handler.isInvalid())
2107 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2113 StmtVector Handlers;
2115 // C++11 attributes can't appear here, despite this context seeming
2117 DiagnoseAndSkipCXX11Attributes();
2119 if (Tok.isNot(tok::kw_catch))
2120 return StmtError(Diag(Tok, diag::err_expected_catch));
2121 while (Tok.is(tok::kw_catch)) {
2122 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2123 if (!Handler.isInvalid())
2124 Handlers.push_back(Handler.get());
2126 // Don't bother creating the full statement if we don't have any usable
2128 if (Handlers.empty())
2131 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2135 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2138 /// 'catch' '(' exception-declaration ')' compound-statement
2140 /// exception-declaration:
2141 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2142 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2145 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2146 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2148 SourceLocation CatchLoc = ConsumeToken();
2150 BalancedDelimiterTracker T(*this, tok::l_paren);
2151 if (T.expectAndConsume())
2155 // The name in a catch exception-declaration is local to the handler and
2156 // shall not be redeclared in the outermost block of the handler.
2157 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2158 (FnCatch ? Scope::FnTryCatchScope : 0));
2160 // exception-declaration is equivalent to '...' or a parameter-declaration
2161 // without default arguments.
2162 Decl *ExceptionDecl = nullptr;
2163 if (Tok.isNot(tok::ellipsis)) {
2164 ParsedAttributesWithRange Attributes(AttrFactory);
2165 MaybeParseCXX11Attributes(Attributes);
2167 DeclSpec DS(AttrFactory);
2168 DS.takeAttributesFrom(Attributes);
2170 if (ParseCXXTypeSpecifierSeq(DS))
2173 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2174 ParseDeclarator(ExDecl);
2175 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2180 if (T.getCloseLocation().isInvalid())
2183 if (Tok.isNot(tok::l_brace))
2184 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2186 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2187 StmtResult Block(ParseCompoundStatement());
2188 if (Block.isInvalid())
2191 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2194 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2195 IfExistsCondition Result;
2196 if (ParseMicrosoftIfExistsCondition(Result))
2199 // Handle dependent statements by parsing the braces as a compound statement.
2200 // This is not the same behavior as Visual C++, which don't treat this as a
2201 // compound statement, but for Clang's type checking we can't have anything
2202 // inside these braces escaping to the surrounding code.
2203 if (Result.Behavior == IEB_Dependent) {
2204 if (!Tok.is(tok::l_brace)) {
2205 Diag(Tok, diag::err_expected) << tok::l_brace;
2209 StmtResult Compound = ParseCompoundStatement();
2210 if (Compound.isInvalid())
2213 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2218 if (DepResult.isUsable())
2219 Stmts.push_back(DepResult.get());
2223 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2224 if (Braces.consumeOpen()) {
2225 Diag(Tok, diag::err_expected) << tok::l_brace;
2229 switch (Result.Behavior) {
2231 // Parse the statements below.
2235 llvm_unreachable("Dependent case handled above");
2242 // Condition is true, parse the statements.
2243 while (Tok.isNot(tok::r_brace)) {
2244 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2246 Stmts.push_back(R.get());
2248 Braces.consumeClose();
2251 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2252 MaybeParseGNUAttributes(Attrs);
2257 if (Attrs.getList()->getKind() != AttributeList::AT_OpenCLUnrollHint)
2260 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2261 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);