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:
386 case tok::annot_pragma_attribute:
387 HandlePragmaAttribute();
391 // If we reached this code, the statement must end in a semicolon.
392 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
393 // If the result was valid, then we do want to diagnose this. Use
394 // ExpectAndConsume to emit the diagnostic, even though we know it won't
396 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
397 // Skip until we see a } or ;, but don't eat it.
398 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
404 /// \brief Parse an expression statement.
405 StmtResult Parser::ParseExprStatement() {
406 // If a case keyword is missing, this is where it should be inserted.
407 Token OldToken = Tok;
409 ExprStatementTokLoc = Tok.getLocation();
411 // expression[opt] ';'
412 ExprResult Expr(ParseExpression());
413 if (Expr.isInvalid()) {
414 // If the expression is invalid, skip ahead to the next semicolon or '}'.
415 // Not doing this opens us up to the possibility of infinite loops if
416 // ParseExpression does not consume any tokens.
417 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
418 if (Tok.is(tok::semi))
420 return Actions.ActOnExprStmtError();
423 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
424 Actions.CheckCaseExpression(Expr.get())) {
425 // If a constant expression is followed by a colon inside a switch block,
426 // suggest a missing case keyword.
427 Diag(OldToken, diag::err_expected_case_before_expression)
428 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
430 // Recover parsing as a case statement.
431 return ParseCaseStatement(/*MissingCase=*/true, Expr);
434 // Otherwise, eat the semicolon.
435 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
436 return Actions.ActOnExprStmt(Expr);
439 /// ParseSEHTryBlockCommon
442 /// '__try' compound-statement seh-handler
446 /// seh-finally-block
448 StmtResult Parser::ParseSEHTryBlock() {
449 assert(Tok.is(tok::kw___try) && "Expected '__try'");
450 SourceLocation TryLoc = ConsumeToken();
452 if (Tok.isNot(tok::l_brace))
453 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
455 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
456 Scope::DeclScope | Scope::SEHTryScope));
457 if(TryBlock.isInvalid())
461 if (Tok.is(tok::identifier) &&
462 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
463 SourceLocation Loc = ConsumeToken();
464 Handler = ParseSEHExceptBlock(Loc);
465 } else if (Tok.is(tok::kw___finally)) {
466 SourceLocation Loc = ConsumeToken();
467 Handler = ParseSEHFinallyBlock(Loc);
469 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
472 if(Handler.isInvalid())
475 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
481 /// ParseSEHExceptBlock - Handle __except
483 /// seh-except-block:
484 /// '__except' '(' seh-filter-expression ')' compound-statement
486 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
487 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
488 raii2(Ident___exception_code, false),
489 raii3(Ident_GetExceptionCode, false);
491 if (ExpectAndConsume(tok::l_paren))
494 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
495 Scope::SEHExceptScope);
497 if (getLangOpts().Borland) {
498 Ident__exception_info->setIsPoisoned(false);
499 Ident___exception_info->setIsPoisoned(false);
500 Ident_GetExceptionInfo->setIsPoisoned(false);
503 ExprResult FilterExpr;
505 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
506 Scope::SEHFilterScope);
507 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
510 if (getLangOpts().Borland) {
511 Ident__exception_info->setIsPoisoned(true);
512 Ident___exception_info->setIsPoisoned(true);
513 Ident_GetExceptionInfo->setIsPoisoned(true);
516 if(FilterExpr.isInvalid())
519 if (ExpectAndConsume(tok::r_paren))
522 if (Tok.isNot(tok::l_brace))
523 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
525 StmtResult Block(ParseCompoundStatement());
527 if(Block.isInvalid())
530 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
533 /// ParseSEHFinallyBlock - Handle __finally
535 /// seh-finally-block:
536 /// '__finally' compound-statement
538 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
539 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
540 raii2(Ident___abnormal_termination, false),
541 raii3(Ident_AbnormalTermination, false);
543 if (Tok.isNot(tok::l_brace))
544 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
546 ParseScope FinallyScope(this, 0);
547 Actions.ActOnStartSEHFinallyBlock();
549 StmtResult Block(ParseCompoundStatement());
550 if(Block.isInvalid()) {
551 Actions.ActOnAbortSEHFinallyBlock();
555 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
560 /// seh-leave-statement:
563 StmtResult Parser::ParseSEHLeaveStatement() {
564 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
565 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
568 /// ParseLabeledStatement - We have an identifier and a ':' after it.
570 /// labeled-statement:
571 /// identifier ':' statement
572 /// [GNU] identifier ':' attributes[opt] statement
574 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
575 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
576 "Not an identifier!");
578 Token IdentTok = Tok; // Save the whole token.
579 ConsumeToken(); // eat the identifier.
581 assert(Tok.is(tok::colon) && "Not a label!");
583 // identifier ':' statement
584 SourceLocation ColonLoc = ConsumeToken();
586 // Read label attributes, if present.
588 if (Tok.is(tok::kw___attribute)) {
589 ParsedAttributesWithRange TempAttrs(AttrFactory);
590 ParseGNUAttributes(TempAttrs);
592 // In C++, GNU attributes only apply to the label if they are followed by a
593 // semicolon, to disambiguate label attributes from attributes on a labeled
596 // This doesn't quite match what GCC does; if the attribute list is empty
597 // and followed by a semicolon, GCC will reject (it appears to parse the
598 // attributes as part of a statement in that case). That looks like a bug.
599 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
600 attrs.takeAllFrom(TempAttrs);
601 else if (isDeclarationStatement()) {
603 // FIXME: We should do this whether or not we have a declaration
604 // statement, but that doesn't work correctly (because ProhibitAttributes
605 // can't handle GNU attributes), so only call it in the one case where
606 // GNU attributes are allowed.
607 SubStmt = ParseStatementOrDeclarationAfterAttributes(
608 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
610 if (!TempAttrs.empty() && !SubStmt.isInvalid())
611 SubStmt = Actions.ProcessStmtAttributes(
612 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
614 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
618 // If we've not parsed a statement yet, parse one now.
619 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
620 SubStmt = ParseStatement();
622 // Broken substmt shouldn't prevent the label from being added to the AST.
623 if (SubStmt.isInvalid())
624 SubStmt = Actions.ActOnNullStmt(ColonLoc);
626 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
627 IdentTok.getLocation());
628 if (AttributeList *Attrs = attrs.getList()) {
629 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
633 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
637 /// ParseCaseStatement
638 /// labeled-statement:
639 /// 'case' constant-expression ':' statement
640 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
642 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
643 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
645 // It is very very common for code to contain many case statements recursively
646 // nested, as in (but usually without indentation):
653 // Parsing this naively works, but is both inefficient and can cause us to run
654 // out of stack space in our recursive descent parser. As a special case,
655 // flatten this recursion into an iterative loop. This is complex and gross,
656 // but all the grossness is constrained to ParseCaseStatement (and some
657 // weirdness in the actions), so this is just local grossness :).
659 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
661 StmtResult TopLevelCase(true);
663 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
664 // gets updated each time a new case is parsed, and whose body is unset so
665 // far. When parsing 'case 4', this is the 'case 3' node.
666 Stmt *DeepestParsedCaseStmt = nullptr;
668 // While we have case statements, eat and stack them.
669 SourceLocation ColonLoc;
671 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
672 ConsumeToken(); // eat the 'case'.
673 ColonLoc = SourceLocation();
675 if (Tok.is(tok::code_completion)) {
676 Actions.CodeCompleteCase(getCurScope());
681 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
682 /// Disable this form of error recovery while we're parsing the case
684 ColonProtectionRAIIObject ColonProtection(*this);
688 LHS = ParseConstantExpression();
689 if (!getLangOpts().CPlusPlus11) {
690 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
691 return Actions.VerifyIntegerConstantExpression(E);
694 if (LHS.isInvalid()) {
695 // If constant-expression is parsed unsuccessfully, recover by skipping
696 // current case statement (moving to the colon that ends it).
697 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
698 TryConsumeToken(tok::colon, ColonLoc);
708 // GNU case range extension.
709 SourceLocation DotDotDotLoc;
711 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
712 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
713 RHS = ParseConstantExpression();
714 if (RHS.isInvalid()) {
715 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
716 TryConsumeToken(tok::colon, ColonLoc);
723 ColonProtection.restore();
725 if (TryConsumeToken(tok::colon, ColonLoc)) {
726 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
727 TryConsumeToken(tok::coloncolon, ColonLoc)) {
728 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
729 Diag(ColonLoc, diag::err_expected_after)
730 << "'case'" << tok::colon
731 << FixItHint::CreateReplacement(ColonLoc, ":");
733 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
734 Diag(ExpectedLoc, diag::err_expected_after)
735 << "'case'" << tok::colon
736 << FixItHint::CreateInsertion(ExpectedLoc, ":");
737 ColonLoc = ExpectedLoc;
741 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
742 RHS.get(), ColonLoc);
744 // If we had a sema error parsing this case, then just ignore it and
745 // continue parsing the sub-stmt.
746 if (Case.isInvalid()) {
747 if (TopLevelCase.isInvalid()) // No parsed case stmts.
748 return ParseStatement(/*TrailingElseLoc=*/nullptr,
749 /*AllowOpenMPStandalone=*/true);
750 // Otherwise, just don't add it as a nested case.
752 // If this is the first case statement we parsed, it becomes TopLevelCase.
753 // Otherwise we link it into the current chain.
754 Stmt *NextDeepest = Case.get();
755 if (TopLevelCase.isInvalid())
758 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
759 DeepestParsedCaseStmt = NextDeepest;
762 // Handle all case statements.
763 } while (Tok.is(tok::kw_case));
765 // If we found a non-case statement, start by parsing it.
768 if (Tok.isNot(tok::r_brace)) {
769 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
770 /*AllowOpenMPStandalone=*/true);
772 // Nicely diagnose the common error "switch (X) { case 4: }", which is
773 // not valid. If ColonLoc doesn't point to a valid text location, there was
774 // another parsing error, so avoid producing extra diagnostics.
775 if (ColonLoc.isValid()) {
776 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
777 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
778 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
780 SubStmt = StmtError();
783 // Install the body into the most deeply-nested case.
784 if (DeepestParsedCaseStmt) {
785 // Broken sub-stmt shouldn't prevent forming the case statement properly.
786 if (SubStmt.isInvalid())
787 SubStmt = Actions.ActOnNullStmt(SourceLocation());
788 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
791 // Return the top level parsed statement tree.
795 /// ParseDefaultStatement
796 /// labeled-statement:
797 /// 'default' ':' statement
798 /// Note that this does not parse the 'statement' at the end.
800 StmtResult Parser::ParseDefaultStatement() {
801 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
802 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
804 SourceLocation ColonLoc;
805 if (TryConsumeToken(tok::colon, ColonLoc)) {
806 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
807 // Treat "default;" as a typo for "default:".
808 Diag(ColonLoc, diag::err_expected_after)
809 << "'default'" << tok::colon
810 << FixItHint::CreateReplacement(ColonLoc, ":");
812 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
813 Diag(ExpectedLoc, diag::err_expected_after)
814 << "'default'" << tok::colon
815 << FixItHint::CreateInsertion(ExpectedLoc, ":");
816 ColonLoc = ExpectedLoc;
821 if (Tok.isNot(tok::r_brace)) {
822 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
823 /*AllowOpenMPStandalone=*/true);
825 // Diagnose the common error "switch (X) {... default: }", which is
827 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
828 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
829 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
833 // Broken sub-stmt shouldn't prevent forming the case statement properly.
834 if (SubStmt.isInvalid())
835 SubStmt = Actions.ActOnNullStmt(ColonLoc);
837 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
838 SubStmt.get(), getCurScope());
841 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
842 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
845 /// ParseCompoundStatement - Parse a "{}" block.
847 /// compound-statement: [C99 6.8.2]
848 /// { block-item-list[opt] }
849 /// [GNU] { label-declarations block-item-list } [TODO]
853 /// block-item-list block-item
857 /// [GNU] '__extension__' declaration
860 /// [GNU] label-declarations:
861 /// [GNU] label-declaration
862 /// [GNU] label-declarations label-declaration
864 /// [GNU] label-declaration:
865 /// [GNU] '__label__' identifier-list ';'
867 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
868 unsigned ScopeFlags) {
869 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
871 // Enter a scope to hold everything within the compound stmt. Compound
872 // statements can always hold declarations.
873 ParseScope CompoundScope(this, ScopeFlags);
875 // Parse the statements in the body.
876 return ParseCompoundStatementBody(isStmtExpr);
879 /// Parse any pragmas at the start of the compound expression. We handle these
880 /// separately since some pragmas (FP_CONTRACT) must appear before any C
881 /// statement in the compound, but may be intermingled with other pragmas.
882 void Parser::ParseCompoundStatementLeadingPragmas() {
883 bool checkForPragmas = true;
884 while (checkForPragmas) {
885 switch (Tok.getKind()) {
886 case tok::annot_pragma_vis:
887 HandlePragmaVisibility();
889 case tok::annot_pragma_pack:
892 case tok::annot_pragma_msstruct:
893 HandlePragmaMSStruct();
895 case tok::annot_pragma_align:
898 case tok::annot_pragma_weak:
901 case tok::annot_pragma_weakalias:
902 HandlePragmaWeakAlias();
904 case tok::annot_pragma_redefine_extname:
905 HandlePragmaRedefineExtname();
907 case tok::annot_pragma_opencl_extension:
908 HandlePragmaOpenCLExtension();
910 case tok::annot_pragma_fp_contract:
911 HandlePragmaFPContract();
913 case tok::annot_pragma_fp:
916 case tok::annot_pragma_ms_pointers_to_members:
917 HandlePragmaMSPointersToMembers();
919 case tok::annot_pragma_ms_pragma:
920 HandlePragmaMSPragma();
922 case tok::annot_pragma_ms_vtordisp:
923 HandlePragmaMSVtorDisp();
925 case tok::annot_pragma_dump:
929 checkForPragmas = false;
936 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
937 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
938 /// consume the '}' at the end of the block. It does not manipulate the scope
940 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
941 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
943 "in compound statement ('{}')");
945 // Record the state of the FP_CONTRACT pragma, restore on leaving the
946 // compound statement.
947 Sema::FPContractStateRAII SaveFPContractState(Actions);
949 InMessageExpressionRAIIObject InMessage(*this, false);
950 BalancedDelimiterTracker T(*this, tok::l_brace);
954 Sema::CompoundScopeRAII CompoundScope(Actions);
956 // Parse any pragmas at the beginning of the compound statement.
957 ParseCompoundStatementLeadingPragmas();
961 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
962 // only allowed at the start of a compound stmt regardless of the language.
963 while (Tok.is(tok::kw___label__)) {
964 SourceLocation LabelLoc = ConsumeToken();
966 SmallVector<Decl *, 8> DeclsInGroup;
968 if (Tok.isNot(tok::identifier)) {
969 Diag(Tok, diag::err_expected) << tok::identifier;
973 IdentifierInfo *II = Tok.getIdentifierInfo();
974 SourceLocation IdLoc = ConsumeToken();
975 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
977 if (!TryConsumeToken(tok::comma))
981 DeclSpec DS(AttrFactory);
983 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
984 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
986 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
988 Stmts.push_back(R.get());
991 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
992 Tok.isNot(tok::eof)) {
993 if (Tok.is(tok::annot_pragma_unused)) {
994 HandlePragmaUnused();
999 if (Tok.isNot(tok::kw___extension__)) {
1000 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
1002 // __extension__ can start declarations and it can also be a unary
1003 // operator for expressions. Consume multiple __extension__ markers here
1004 // until we can determine which is which.
1005 // FIXME: This loses extension expressions in the AST!
1006 SourceLocation ExtLoc = ConsumeToken();
1007 while (Tok.is(tok::kw___extension__))
1010 ParsedAttributesWithRange attrs(AttrFactory);
1011 MaybeParseCXX11Attributes(attrs, nullptr,
1012 /*MightBeObjCMessageSend*/ true);
1014 // If this is the start of a declaration, parse it as such.
1015 if (isDeclarationStatement()) {
1016 // __extension__ silences extension warnings in the subdeclaration.
1017 // FIXME: Save the __extension__ on the decl as a node somehow?
1018 ExtensionRAIIObject O(Diags);
1020 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1021 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
1023 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1025 // Otherwise this was a unary __extension__ marker.
1026 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1028 if (Res.isInvalid()) {
1029 SkipUntil(tok::semi);
1033 // FIXME: Use attributes?
1034 // Eat the semicolon at the end of stmt and convert the expr into a
1036 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1037 R = Actions.ActOnExprStmt(Res);
1042 Stmts.push_back(R.get());
1045 SourceLocation CloseLoc = Tok.getLocation();
1047 // We broke out of the while loop because we found a '}' or EOF.
1048 if (!T.consumeClose())
1049 // Recover by creating a compound statement with what we parsed so far,
1050 // instead of dropping everything and returning StmtError();
1051 CloseLoc = T.getCloseLocation();
1053 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1057 /// ParseParenExprOrCondition:
1058 /// [C ] '(' expression ')'
1059 /// [C++] '(' condition ')'
1060 /// [C++1z] '(' init-statement[opt] condition ')'
1062 /// This function parses and performs error recovery on the specified condition
1063 /// or expression (depending on whether we're in C++ or C mode). This function
1064 /// goes out of its way to recover well. It returns true if there was a parser
1065 /// error (the right paren couldn't be found), which indicates that the caller
1066 /// should try to recover harder. It returns false if the condition is
1067 /// successfully parsed. Note that a successful parse can still have semantic
1068 /// errors in the condition.
1069 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1070 Sema::ConditionResult &Cond,
1072 Sema::ConditionKind CK) {
1073 BalancedDelimiterTracker T(*this, tok::l_paren);
1076 if (getLangOpts().CPlusPlus)
1077 Cond = ParseCXXCondition(InitStmt, Loc, CK);
1079 ExprResult CondExpr = ParseExpression();
1081 // If required, convert to a boolean value.
1082 if (CondExpr.isInvalid())
1083 Cond = Sema::ConditionError();
1085 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1088 // If the parser was confused by the condition and we don't have a ')', try to
1089 // recover by skipping ahead to a semi and bailing out. If condexp is
1090 // semantically invalid but we have well formed code, keep going.
1091 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1092 SkipUntil(tok::semi);
1093 // Skipping may have stopped if it found the containing ')'. If so, we can
1094 // continue parsing the if statement.
1095 if (Tok.isNot(tok::r_paren))
1099 // Otherwise the condition is valid or the rparen is present.
1102 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1103 // that all callers are looking for a statement after the condition, so ")"
1105 while (Tok.is(tok::r_paren)) {
1106 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1107 << FixItHint::CreateRemoval(Tok.getLocation());
1115 /// ParseIfStatement
1116 /// if-statement: [C99 6.8.4.1]
1117 /// 'if' '(' expression ')' statement
1118 /// 'if' '(' expression ')' statement 'else' statement
1119 /// [C++] 'if' '(' condition ')' statement
1120 /// [C++] 'if' '(' condition ')' statement 'else' statement
1122 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1123 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1124 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1126 bool IsConstexpr = false;
1127 if (Tok.is(tok::kw_constexpr)) {
1128 Diag(Tok, getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_constexpr_if
1129 : diag::ext_constexpr_if);
1134 if (Tok.isNot(tok::l_paren)) {
1135 Diag(Tok, diag::err_expected_lparen_after) << "if";
1136 SkipUntil(tok::semi);
1140 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1142 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1143 // the case for C90.
1146 // A name introduced by a declaration in a condition is in scope from its
1147 // point of declaration until the end of the substatements controlled by the
1150 // Names declared in the for-init-statement, and in the condition of if,
1151 // while, for, and switch statements are local to the if, while, for, or
1152 // switch statement (including the controlled statement).
1154 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1156 // Parse the condition.
1157 StmtResult InitStmt;
1158 Sema::ConditionResult Cond;
1159 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1160 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1161 : Sema::ConditionKind::Boolean))
1164 llvm::Optional<bool> ConstexprCondition;
1166 ConstexprCondition = Cond.getKnownValue();
1168 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1169 // there is no compound stmt. C90 does not have this clause. We only do this
1170 // if the body isn't a compound statement to avoid push/pop in common cases.
1173 // The substatement in a selection-statement (each substatement, in the else
1174 // form of the if statement) implicitly defines a local scope.
1176 // For C++ we create a scope for the condition and a new scope for
1177 // substatements because:
1178 // -When the 'then' scope exits, we want the condition declaration to still be
1179 // active for the 'else' scope too.
1180 // -Sema will detect name clashes by considering declarations of a
1181 // 'ControlScope' as part of its direct subscope.
1182 // -If we wanted the condition and substatement to be in the same scope, we
1183 // would have to notify ParseStatement not to create a new scope. It's
1184 // simpler to let it create a new scope.
1186 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1188 // Read the 'then' stmt.
1189 SourceLocation ThenStmtLoc = Tok.getLocation();
1191 SourceLocation InnerStatementTrailingElseLoc;
1192 StmtResult ThenStmt;
1194 EnterExpressionEvaluationContext PotentiallyDiscarded(
1195 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1197 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1198 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1201 // Pop the 'if' scope if needed.
1204 // If it has an else, parse it.
1205 SourceLocation ElseLoc;
1206 SourceLocation ElseStmtLoc;
1207 StmtResult ElseStmt;
1209 if (Tok.is(tok::kw_else)) {
1210 if (TrailingElseLoc)
1211 *TrailingElseLoc = Tok.getLocation();
1213 ElseLoc = ConsumeToken();
1214 ElseStmtLoc = Tok.getLocation();
1216 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1217 // there is no compound stmt. C90 does not have this clause. We only do
1218 // this if the body isn't a compound statement to avoid push/pop in common
1222 // The substatement in a selection-statement (each substatement, in the else
1223 // form of the if statement) implicitly defines a local scope.
1225 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1226 Tok.is(tok::l_brace));
1228 EnterExpressionEvaluationContext PotentiallyDiscarded(
1229 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1231 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1232 ElseStmt = ParseStatement();
1234 // Pop the 'else' scope if needed.
1236 } else if (Tok.is(tok::code_completion)) {
1237 Actions.CodeCompleteAfterIf(getCurScope());
1240 } else if (InnerStatementTrailingElseLoc.isValid()) {
1241 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1246 // If the then or else stmt is invalid and the other is valid (and present),
1247 // make turn the invalid one into a null stmt to avoid dropping the other
1248 // part. If both are invalid, return error.
1249 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1250 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1251 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1252 // Both invalid, or one is invalid and other is non-present: return error.
1256 // Now if either are invalid, replace with a ';'.
1257 if (ThenStmt.isInvalid())
1258 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1259 if (ElseStmt.isInvalid())
1260 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1262 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1263 ThenStmt.get(), ElseLoc, ElseStmt.get());
1266 /// ParseSwitchStatement
1267 /// switch-statement:
1268 /// 'switch' '(' expression ')' statement
1269 /// [C++] 'switch' '(' condition ')' statement
1270 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1271 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1272 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1274 if (Tok.isNot(tok::l_paren)) {
1275 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1276 SkipUntil(tok::semi);
1280 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1282 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1283 // not the case for C90. Start the switch scope.
1286 // A name introduced by a declaration in a condition is in scope from its
1287 // point of declaration until the end of the substatements controlled by the
1290 // Names declared in the for-init-statement, and in the condition of if,
1291 // while, for, and switch statements are local to the if, while, for, or
1292 // switch statement (including the controlled statement).
1294 unsigned ScopeFlags = Scope::SwitchScope;
1296 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1297 ParseScope SwitchScope(this, ScopeFlags);
1299 // Parse the condition.
1300 StmtResult InitStmt;
1301 Sema::ConditionResult Cond;
1302 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1303 Sema::ConditionKind::Switch))
1307 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1309 if (Switch.isInvalid()) {
1310 // Skip the switch body.
1311 // FIXME: This is not optimal recovery, but parsing the body is more
1312 // dangerous due to the presence of case and default statements, which
1313 // will have no place to connect back with the switch.
1314 if (Tok.is(tok::l_brace)) {
1316 SkipUntil(tok::r_brace);
1318 SkipUntil(tok::semi);
1322 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1323 // there is no compound stmt. C90 does not have this clause. We only do this
1324 // if the body isn't a compound statement to avoid push/pop in common cases.
1327 // The substatement in a selection-statement (each substatement, in the else
1328 // form of the if statement) implicitly defines a local scope.
1330 // See comments in ParseIfStatement for why we create a scope for the
1331 // condition and a new scope for substatement in C++.
1333 getCurScope()->AddFlags(Scope::BreakScope);
1334 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1336 // We have incremented the mangling number for the SwitchScope and the
1337 // InnerScope, which is one too many.
1339 getCurScope()->decrementMSManglingNumber();
1341 // Read the body statement.
1342 StmtResult Body(ParseStatement(TrailingElseLoc));
1348 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1351 /// ParseWhileStatement
1352 /// while-statement: [C99 6.8.5.1]
1353 /// 'while' '(' expression ')' statement
1354 /// [C++] 'while' '(' condition ')' statement
1355 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1356 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1357 SourceLocation WhileLoc = Tok.getLocation();
1358 ConsumeToken(); // eat the 'while'.
1360 if (Tok.isNot(tok::l_paren)) {
1361 Diag(Tok, diag::err_expected_lparen_after) << "while";
1362 SkipUntil(tok::semi);
1366 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1368 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1369 // the case for C90. Start the loop scope.
1372 // A name introduced by a declaration in a condition is in scope from its
1373 // point of declaration until the end of the substatements controlled by the
1376 // Names declared in the for-init-statement, and in the condition of if,
1377 // while, for, and switch statements are local to the if, while, for, or
1378 // switch statement (including the controlled statement).
1380 unsigned ScopeFlags;
1382 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1383 Scope::DeclScope | Scope::ControlScope;
1385 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1386 ParseScope WhileScope(this, ScopeFlags);
1388 // Parse the condition.
1389 Sema::ConditionResult Cond;
1390 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1391 Sema::ConditionKind::Boolean))
1394 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1395 // there is no compound stmt. C90 does not have this clause. We only do this
1396 // if the body isn't a compound statement to avoid push/pop in common cases.
1399 // The substatement in an iteration-statement implicitly defines a local scope
1400 // which is entered and exited each time through the loop.
1402 // See comments in ParseIfStatement for why we create a scope for the
1403 // condition and a new scope for substatement in C++.
1405 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1407 // Read the body statement.
1408 StmtResult Body(ParseStatement(TrailingElseLoc));
1410 // Pop the body scope if needed.
1414 if (Cond.isInvalid() || Body.isInvalid())
1417 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1420 /// ParseDoStatement
1421 /// do-statement: [C99 6.8.5.2]
1422 /// 'do' statement 'while' '(' expression ')' ';'
1423 /// Note: this lets the caller parse the end ';'.
1424 StmtResult Parser::ParseDoStatement() {
1425 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1426 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1428 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1429 // the case for C90. Start the loop scope.
1430 unsigned ScopeFlags;
1431 if (getLangOpts().C99)
1432 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1434 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1436 ParseScope DoScope(this, ScopeFlags);
1438 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1439 // there is no compound stmt. C90 does not have this clause. We only do this
1440 // if the body isn't a compound statement to avoid push/pop in common cases.
1443 // The substatement in an iteration-statement implicitly defines a local scope
1444 // which is entered and exited each time through the loop.
1446 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1447 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1449 // Read the body statement.
1450 StmtResult Body(ParseStatement());
1452 // Pop the body scope if needed.
1455 if (Tok.isNot(tok::kw_while)) {
1456 if (!Body.isInvalid()) {
1457 Diag(Tok, diag::err_expected_while);
1458 Diag(DoLoc, diag::note_matching) << "'do'";
1459 SkipUntil(tok::semi, StopBeforeMatch);
1463 SourceLocation WhileLoc = ConsumeToken();
1465 if (Tok.isNot(tok::l_paren)) {
1466 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1467 SkipUntil(tok::semi, StopBeforeMatch);
1471 // Parse the parenthesized expression.
1472 BalancedDelimiterTracker T(*this, tok::l_paren);
1475 // A do-while expression is not a condition, so can't have attributes.
1476 DiagnoseAndSkipCXX11Attributes();
1478 ExprResult Cond = ParseExpression();
1482 if (Cond.isInvalid() || Body.isInvalid())
1485 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1486 Cond.get(), T.getCloseLocation());
1489 bool Parser::isForRangeIdentifier() {
1490 assert(Tok.is(tok::identifier));
1492 const Token &Next = NextToken();
1493 if (Next.is(tok::colon))
1496 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1497 TentativeParsingAction PA(*this);
1499 SkipCXX11Attributes();
1500 bool Result = Tok.is(tok::colon);
1508 /// ParseForStatement
1509 /// for-statement: [C99 6.8.5.3]
1510 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1511 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1512 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1515 /// 'co_await'[opt] [Coroutines]
1516 /// '(' for-range-declaration ':' for-range-initializer ')'
1518 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1519 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1521 /// [C++] for-init-statement:
1522 /// [C++] expression-statement
1523 /// [C++] simple-declaration
1525 /// [C++0x] for-range-declaration:
1526 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1527 /// [C++0x] for-range-initializer:
1528 /// [C++0x] expression
1529 /// [C++0x] braced-init-list [TODO]
1530 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1531 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1532 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1534 SourceLocation CoawaitLoc;
1535 if (Tok.is(tok::kw_co_await))
1536 CoawaitLoc = ConsumeToken();
1538 if (Tok.isNot(tok::l_paren)) {
1539 Diag(Tok, diag::err_expected_lparen_after) << "for";
1540 SkipUntil(tok::semi);
1544 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1545 getLangOpts().ObjC1;
1547 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1548 // the case for C90. Start the loop scope.
1551 // A name introduced by a declaration in a condition is in scope from its
1552 // point of declaration until the end of the substatements controlled by the
1555 // Names declared in the for-init-statement, and in the condition of if,
1556 // while, for, and switch statements are local to the if, while, for, or
1557 // switch statement (including the controlled statement).
1559 // Names declared in the for-init-statement are in the same declarative-region
1560 // as those declared in the condition.
1562 unsigned ScopeFlags = 0;
1564 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1566 ParseScope ForScope(this, ScopeFlags);
1568 BalancedDelimiterTracker T(*this, tok::l_paren);
1573 bool ForEach = false, ForRange = false;
1574 StmtResult FirstPart;
1575 Sema::ConditionResult SecondPart;
1576 ExprResult Collection;
1577 ForRangeInit ForRangeInit;
1578 FullExprArg ThirdPart(Actions);
1580 if (Tok.is(tok::code_completion)) {
1581 Actions.CodeCompleteOrdinaryName(getCurScope(),
1582 C99orCXXorObjC? Sema::PCC_ForInit
1583 : Sema::PCC_Expression);
1588 ParsedAttributesWithRange attrs(AttrFactory);
1589 MaybeParseCXX11Attributes(attrs);
1591 // Parse the first part of the for specifier.
1592 if (Tok.is(tok::semi)) { // for (;
1593 ProhibitAttributes(attrs);
1594 // no first part, eat the ';'.
1596 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1597 isForRangeIdentifier()) {
1598 ProhibitAttributes(attrs);
1599 IdentifierInfo *Name = Tok.getIdentifierInfo();
1600 SourceLocation Loc = ConsumeToken();
1601 MaybeParseCXX11Attributes(attrs);
1603 ForRangeInit.ColonLoc = ConsumeToken();
1604 if (Tok.is(tok::l_brace))
1605 ForRangeInit.RangeExpr = ParseBraceInitializer();
1607 ForRangeInit.RangeExpr = ParseExpression();
1609 Diag(Loc, diag::err_for_range_identifier)
1610 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1611 ? FixItHint::CreateInsertion(Loc, "auto &&")
1614 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1615 attrs, attrs.Range.getEnd());
1617 } else if (isForInitDeclaration()) { // for (int X = 4;
1618 // Parse declaration, which eats the ';'.
1619 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1620 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1622 // In C++0x, "for (T NS:a" might not be a typo for ::
1623 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1624 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1626 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1627 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1628 Declarator::ForContext, DeclEnd, attrs, false,
1629 MightBeForRangeStmt ? &ForRangeInit : nullptr);
1630 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1631 if (ForRangeInit.ParsedForRangeDecl()) {
1632 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1633 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1636 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1638 } else if ((ForEach = isTokIdentifier_in())) {
1639 Actions.ActOnForEachDeclStmt(DG);
1640 // ObjC: for (id x in expr)
1641 ConsumeToken(); // consume 'in'
1643 if (Tok.is(tok::code_completion)) {
1644 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1648 Collection = ParseExpression();
1650 Diag(Tok, diag::err_expected_semi_for);
1653 ProhibitAttributes(attrs);
1654 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1656 ForEach = isTokIdentifier_in();
1658 // Turn the expression into a stmt.
1659 if (!Value.isInvalid()) {
1661 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1663 FirstPart = Actions.ActOnExprStmt(Value);
1666 if (Tok.is(tok::semi)) {
1668 } else if (ForEach) {
1669 ConsumeToken(); // consume 'in'
1671 if (Tok.is(tok::code_completion)) {
1672 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1676 Collection = ParseExpression();
1677 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1678 // User tried to write the reasonable, but ill-formed, for-range-statement
1679 // for (expr : expr) { ... }
1680 Diag(Tok, diag::err_for_range_expected_decl)
1681 << FirstPart.get()->getSourceRange();
1682 SkipUntil(tok::r_paren, StopBeforeMatch);
1683 SecondPart = Sema::ConditionError();
1685 if (!Value.isInvalid()) {
1686 Diag(Tok, diag::err_expected_semi_for);
1688 // Skip until semicolon or rparen, don't consume it.
1689 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1690 if (Tok.is(tok::semi))
1696 // Parse the second part of the for specifier.
1697 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1698 if (!ForEach && !ForRange && !SecondPart.isInvalid()) {
1699 // Parse the second part of the for specifier.
1700 if (Tok.is(tok::semi)) { // for (...;;
1702 } else if (Tok.is(tok::r_paren)) {
1703 // missing both semicolons.
1705 if (getLangOpts().CPlusPlus)
1707 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean);
1709 ExprResult SecondExpr = ParseExpression();
1710 if (SecondExpr.isInvalid())
1711 SecondPart = Sema::ConditionError();
1714 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1715 Sema::ConditionKind::Boolean);
1719 if (Tok.isNot(tok::semi)) {
1720 if (!SecondPart.isInvalid())
1721 Diag(Tok, diag::err_expected_semi_for);
1723 // Skip until semicolon or rparen, don't consume it.
1724 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1727 if (Tok.is(tok::semi)) {
1731 // Parse the third part of the for specifier.
1732 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1733 ExprResult Third = ParseExpression();
1734 // FIXME: The C++11 standard doesn't actually say that this is a
1735 // discarded-value expression, but it clearly should be.
1736 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1742 // C++ Coroutines [stmt.iter]:
1743 // 'co_await' can only be used for a range-based for statement.
1744 if (CoawaitLoc.isValid() && !ForRange) {
1745 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1746 CoawaitLoc = SourceLocation();
1749 // We need to perform most of the semantic analysis for a C++0x for-range
1750 // statememt before parsing the body, in order to be able to deduce the type
1751 // of an auto-typed loop variable.
1752 StmtResult ForRangeStmt;
1753 StmtResult ForEachStmt;
1756 ExprResult CorrectedRange =
1757 Actions.CorrectDelayedTyposInExpr(ForRangeInit.RangeExpr.get());
1758 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1759 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1760 ForRangeInit.ColonLoc, CorrectedRange.get(),
1761 T.getCloseLocation(), Sema::BFRK_Build);
1763 // Similarly, we need to do the semantic analysis for a for-range
1764 // statement immediately in order to close over temporaries correctly.
1765 } else if (ForEach) {
1766 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1769 T.getCloseLocation());
1771 // In OpenMP loop region loop control variable must be captured and be
1772 // private. Perform analysis of first part (if any).
1773 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1774 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1778 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1779 // there is no compound stmt. C90 does not have this clause. We only do this
1780 // if the body isn't a compound statement to avoid push/pop in common cases.
1783 // The substatement in an iteration-statement implicitly defines a local scope
1784 // which is entered and exited each time through the loop.
1786 // See comments in ParseIfStatement for why we create a scope for
1787 // for-init-statement/condition and a new scope for substatement in C++.
1789 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1790 Tok.is(tok::l_brace));
1792 // The body of the for loop has the same local mangling number as the
1793 // for-init-statement.
1794 // It will only be incremented if the body contains other things that would
1795 // normally increment the mangling number (like a compound statement).
1797 getCurScope()->decrementMSManglingNumber();
1799 // Read the body statement.
1800 StmtResult Body(ParseStatement(TrailingElseLoc));
1802 // Pop the body scope if needed.
1805 // Leave the for-scope.
1808 if (Body.isInvalid())
1812 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1816 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1818 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1819 SecondPart, ThirdPart, T.getCloseLocation(),
1823 /// ParseGotoStatement
1825 /// 'goto' identifier ';'
1826 /// [GNU] 'goto' '*' expression ';'
1828 /// Note: this lets the caller parse the end ';'.
1830 StmtResult Parser::ParseGotoStatement() {
1831 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1832 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1835 if (Tok.is(tok::identifier)) {
1836 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1838 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1840 } else if (Tok.is(tok::star)) {
1841 // GNU indirect goto extension.
1842 Diag(Tok, diag::ext_gnu_indirect_goto);
1843 SourceLocation StarLoc = ConsumeToken();
1844 ExprResult R(ParseExpression());
1845 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1846 SkipUntil(tok::semi, StopBeforeMatch);
1849 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1851 Diag(Tok, diag::err_expected) << tok::identifier;
1858 /// ParseContinueStatement
1862 /// Note: this lets the caller parse the end ';'.
1864 StmtResult Parser::ParseContinueStatement() {
1865 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1866 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1869 /// ParseBreakStatement
1873 /// Note: this lets the caller parse the end ';'.
1875 StmtResult Parser::ParseBreakStatement() {
1876 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1877 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1880 /// ParseReturnStatement
1882 /// 'return' expression[opt] ';'
1883 /// 'return' braced-init-list ';'
1884 /// 'co_return' expression[opt] ';'
1885 /// 'co_return' braced-init-list ';'
1886 StmtResult Parser::ParseReturnStatement() {
1887 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1888 "Not a return stmt!");
1889 bool IsCoreturn = Tok.is(tok::kw_co_return);
1890 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1893 if (Tok.isNot(tok::semi)) {
1894 // FIXME: Code completion for co_return.
1895 if (Tok.is(tok::code_completion) && !IsCoreturn) {
1896 Actions.CodeCompleteReturn(getCurScope());
1901 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1902 R = ParseInitializer();
1904 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1905 diag::warn_cxx98_compat_generalized_initializer_lists :
1906 diag::ext_generalized_initializer_lists)
1907 << R.get()->getSourceRange();
1909 R = ParseExpression();
1910 if (R.isInvalid()) {
1911 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1916 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
1917 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1920 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1921 AllowedConstructsKind Allowed,
1922 SourceLocation *TrailingElseLoc,
1923 ParsedAttributesWithRange &Attrs) {
1924 // Create temporary attribute list.
1925 ParsedAttributesWithRange TempAttrs(AttrFactory);
1927 // Get loop hints and consume annotated token.
1928 while (Tok.is(tok::annot_pragma_loop_hint)) {
1930 if (!HandlePragmaLoopHint(Hint))
1933 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1934 ArgsUnion(Hint.ValueExpr)};
1935 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1936 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1937 AttributeList::AS_Pragma);
1940 // Get the next statement.
1941 MaybeParseCXX11Attributes(Attrs);
1943 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1944 Stmts, Allowed, TrailingElseLoc, Attrs);
1946 Attrs.takeAllFrom(TempAttrs);
1950 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1951 assert(Tok.is(tok::l_brace));
1952 SourceLocation LBraceLoc = Tok.getLocation();
1954 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1955 "parsing function body");
1957 // Save and reset current vtordisp stack if we have entered a C++ method body.
1959 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1960 Sema::PragmaStackSentinelRAII
1961 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1963 // Do not enter a scope for the brace, as the arguments are in the same scope
1964 // (the function body) as the body itself. Instead, just read the statement
1965 // list and put it into a CompoundStmt for safe keeping.
1966 StmtResult FnBody(ParseCompoundStatementBody());
1968 // If the function body could not be parsed, make a bogus compoundstmt.
1969 if (FnBody.isInvalid()) {
1970 Sema::CompoundScopeRAII CompoundScope(Actions);
1971 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1975 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1978 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1980 /// function-try-block:
1981 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1983 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1984 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1985 SourceLocation TryLoc = ConsumeToken();
1987 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1988 "parsing function try block");
1990 // Constructor initializer list?
1991 if (Tok.is(tok::colon))
1992 ParseConstructorInitializer(Decl);
1994 Actions.ActOnDefaultCtorInitializers(Decl);
1996 // Save and reset current vtordisp stack if we have entered a C++ method body.
1998 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1999 Sema::PragmaStackSentinelRAII
2000 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2002 SourceLocation LBraceLoc = Tok.getLocation();
2003 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2004 // If we failed to parse the try-catch, we just give the function an empty
2005 // compound statement as the body.
2006 if (FnBody.isInvalid()) {
2007 Sema::CompoundScopeRAII CompoundScope(Actions);
2008 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2012 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2015 bool Parser::trySkippingFunctionBody() {
2016 assert(SkipFunctionBodies &&
2017 "Should only be called when SkipFunctionBodies is enabled");
2018 if (!PP.isCodeCompletionEnabled()) {
2023 // We're in code-completion mode. Skip parsing for all function bodies unless
2024 // the body contains the code-completion point.
2025 TentativeParsingAction PA(*this);
2026 bool IsTryCatch = Tok.is(tok::kw_try);
2028 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2029 if (llvm::any_of(Toks, [](const Token &Tok) {
2030 return Tok.is(tok::code_completion);
2035 if (ErrorInPrologue) {
2037 SkipMalformedDecl();
2040 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2044 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2045 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2046 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2055 /// ParseCXXTryBlock - Parse a C++ try-block.
2058 /// 'try' compound-statement handler-seq
2060 StmtResult Parser::ParseCXXTryBlock() {
2061 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2063 SourceLocation TryLoc = ConsumeToken();
2064 return ParseCXXTryBlockCommon(TryLoc);
2067 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2068 /// function-try-block.
2071 /// 'try' compound-statement handler-seq
2073 /// function-try-block:
2074 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2077 /// handler handler-seq[opt]
2079 /// [Borland] try-block:
2080 /// 'try' compound-statement seh-except-block
2081 /// 'try' compound-statement seh-finally-block
2083 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2084 if (Tok.isNot(tok::l_brace))
2085 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2087 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2088 Scope::DeclScope | Scope::TryScope |
2089 (FnTry ? Scope::FnTryCatchScope : 0)));
2090 if (TryBlock.isInvalid())
2093 // Borland allows SEH-handlers with 'try'
2095 if ((Tok.is(tok::identifier) &&
2096 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2097 Tok.is(tok::kw___finally)) {
2098 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2100 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2101 SourceLocation Loc = ConsumeToken();
2102 Handler = ParseSEHExceptBlock(Loc);
2105 SourceLocation Loc = ConsumeToken();
2106 Handler = ParseSEHFinallyBlock(Loc);
2108 if(Handler.isInvalid())
2111 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2117 StmtVector Handlers;
2119 // C++11 attributes can't appear here, despite this context seeming
2121 DiagnoseAndSkipCXX11Attributes();
2123 if (Tok.isNot(tok::kw_catch))
2124 return StmtError(Diag(Tok, diag::err_expected_catch));
2125 while (Tok.is(tok::kw_catch)) {
2126 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2127 if (!Handler.isInvalid())
2128 Handlers.push_back(Handler.get());
2130 // Don't bother creating the full statement if we don't have any usable
2132 if (Handlers.empty())
2135 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2139 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2142 /// 'catch' '(' exception-declaration ')' compound-statement
2144 /// exception-declaration:
2145 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2146 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2149 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2150 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2152 SourceLocation CatchLoc = ConsumeToken();
2154 BalancedDelimiterTracker T(*this, tok::l_paren);
2155 if (T.expectAndConsume())
2159 // The name in a catch exception-declaration is local to the handler and
2160 // shall not be redeclared in the outermost block of the handler.
2161 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2162 (FnCatch ? Scope::FnTryCatchScope : 0));
2164 // exception-declaration is equivalent to '...' or a parameter-declaration
2165 // without default arguments.
2166 Decl *ExceptionDecl = nullptr;
2167 if (Tok.isNot(tok::ellipsis)) {
2168 ParsedAttributesWithRange Attributes(AttrFactory);
2169 MaybeParseCXX11Attributes(Attributes);
2171 DeclSpec DS(AttrFactory);
2172 DS.takeAttributesFrom(Attributes);
2174 if (ParseCXXTypeSpecifierSeq(DS))
2177 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2178 ParseDeclarator(ExDecl);
2179 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2184 if (T.getCloseLocation().isInvalid())
2187 if (Tok.isNot(tok::l_brace))
2188 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2190 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2191 StmtResult Block(ParseCompoundStatement());
2192 if (Block.isInvalid())
2195 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2198 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2199 IfExistsCondition Result;
2200 if (ParseMicrosoftIfExistsCondition(Result))
2203 // Handle dependent statements by parsing the braces as a compound statement.
2204 // This is not the same behavior as Visual C++, which don't treat this as a
2205 // compound statement, but for Clang's type checking we can't have anything
2206 // inside these braces escaping to the surrounding code.
2207 if (Result.Behavior == IEB_Dependent) {
2208 if (!Tok.is(tok::l_brace)) {
2209 Diag(Tok, diag::err_expected) << tok::l_brace;
2213 StmtResult Compound = ParseCompoundStatement();
2214 if (Compound.isInvalid())
2217 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2222 if (DepResult.isUsable())
2223 Stmts.push_back(DepResult.get());
2227 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2228 if (Braces.consumeOpen()) {
2229 Diag(Tok, diag::err_expected) << tok::l_brace;
2233 switch (Result.Behavior) {
2235 // Parse the statements below.
2239 llvm_unreachable("Dependent case handled above");
2246 // Condition is true, parse the statements.
2247 while (Tok.isNot(tok::r_brace)) {
2248 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2250 Stmts.push_back(R.get());
2252 Braces.consumeClose();
2255 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2256 MaybeParseGNUAttributes(Attrs);
2261 if (Attrs.getList()->getKind() != AttributeList::AT_OpenCLUnrollHint)
2264 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2265 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);