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 "RAIIObjectsForParser.h"
16 #include "clang/Basic/Attributes.h"
17 #include "clang/Basic/PrettyStackTrace.h"
18 #include "clang/Parse/Parser.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 AllowedContsructsKind 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 AllowedContsructsKind 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_opencl_extension:
345 ProhibitAttributes(Attrs);
346 HandlePragmaOpenCLExtension();
349 case tok::annot_pragma_captured:
350 ProhibitAttributes(Attrs);
351 return HandlePragmaCaptured();
353 case tok::annot_pragma_openmp:
354 ProhibitAttributes(Attrs);
355 return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
357 case tok::annot_pragma_ms_pointers_to_members:
358 ProhibitAttributes(Attrs);
359 HandlePragmaMSPointersToMembers();
362 case tok::annot_pragma_ms_pragma:
363 ProhibitAttributes(Attrs);
364 HandlePragmaMSPragma();
367 case tok::annot_pragma_ms_vtordisp:
368 ProhibitAttributes(Attrs);
369 HandlePragmaMSVtorDisp();
372 case tok::annot_pragma_loop_hint:
373 ProhibitAttributes(Attrs);
374 return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
376 case tok::annot_pragma_dump:
381 // If we reached this code, the statement must end in a semicolon.
382 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
383 // If the result was valid, then we do want to diagnose this. Use
384 // ExpectAndConsume to emit the diagnostic, even though we know it won't
386 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
387 // Skip until we see a } or ;, but don't eat it.
388 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
394 /// \brief Parse an expression statement.
395 StmtResult Parser::ParseExprStatement() {
396 // If a case keyword is missing, this is where it should be inserted.
397 Token OldToken = Tok;
399 ExprStatementTokLoc = Tok.getLocation();
401 // expression[opt] ';'
402 ExprResult Expr(ParseExpression());
403 if (Expr.isInvalid()) {
404 // If the expression is invalid, skip ahead to the next semicolon or '}'.
405 // Not doing this opens us up to the possibility of infinite loops if
406 // ParseExpression does not consume any tokens.
407 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
408 if (Tok.is(tok::semi))
410 return Actions.ActOnExprStmtError();
413 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
414 Actions.CheckCaseExpression(Expr.get())) {
415 // If a constant expression is followed by a colon inside a switch block,
416 // suggest a missing case keyword.
417 Diag(OldToken, diag::err_expected_case_before_expression)
418 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
420 // Recover parsing as a case statement.
421 return ParseCaseStatement(/*MissingCase=*/true, Expr);
424 // Otherwise, eat the semicolon.
425 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
426 return Actions.ActOnExprStmt(Expr);
429 /// ParseSEHTryBlockCommon
432 /// '__try' compound-statement seh-handler
436 /// seh-finally-block
438 StmtResult Parser::ParseSEHTryBlock() {
439 assert(Tok.is(tok::kw___try) && "Expected '__try'");
440 SourceLocation TryLoc = ConsumeToken();
442 if (Tok.isNot(tok::l_brace))
443 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
445 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
446 Scope::DeclScope | Scope::SEHTryScope));
447 if(TryBlock.isInvalid())
451 if (Tok.is(tok::identifier) &&
452 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
453 SourceLocation Loc = ConsumeToken();
454 Handler = ParseSEHExceptBlock(Loc);
455 } else if (Tok.is(tok::kw___finally)) {
456 SourceLocation Loc = ConsumeToken();
457 Handler = ParseSEHFinallyBlock(Loc);
459 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
462 if(Handler.isInvalid())
465 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
471 /// ParseSEHExceptBlock - Handle __except
473 /// seh-except-block:
474 /// '__except' '(' seh-filter-expression ')' compound-statement
476 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
477 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
478 raii2(Ident___exception_code, false),
479 raii3(Ident_GetExceptionCode, false);
481 if (ExpectAndConsume(tok::l_paren))
484 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
485 Scope::SEHExceptScope);
487 if (getLangOpts().Borland) {
488 Ident__exception_info->setIsPoisoned(false);
489 Ident___exception_info->setIsPoisoned(false);
490 Ident_GetExceptionInfo->setIsPoisoned(false);
493 ExprResult FilterExpr;
495 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
496 Scope::SEHFilterScope);
497 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
500 if (getLangOpts().Borland) {
501 Ident__exception_info->setIsPoisoned(true);
502 Ident___exception_info->setIsPoisoned(true);
503 Ident_GetExceptionInfo->setIsPoisoned(true);
506 if(FilterExpr.isInvalid())
509 if (ExpectAndConsume(tok::r_paren))
512 if (Tok.isNot(tok::l_brace))
513 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
515 StmtResult Block(ParseCompoundStatement());
517 if(Block.isInvalid())
520 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
523 /// ParseSEHFinallyBlock - Handle __finally
525 /// seh-finally-block:
526 /// '__finally' compound-statement
528 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
529 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
530 raii2(Ident___abnormal_termination, false),
531 raii3(Ident_AbnormalTermination, false);
533 if (Tok.isNot(tok::l_brace))
534 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
536 ParseScope FinallyScope(this, 0);
537 Actions.ActOnStartSEHFinallyBlock();
539 StmtResult Block(ParseCompoundStatement());
540 if(Block.isInvalid()) {
541 Actions.ActOnAbortSEHFinallyBlock();
545 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
550 /// seh-leave-statement:
553 StmtResult Parser::ParseSEHLeaveStatement() {
554 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
555 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
558 /// ParseLabeledStatement - We have an identifier and a ':' after it.
560 /// labeled-statement:
561 /// identifier ':' statement
562 /// [GNU] identifier ':' attributes[opt] statement
564 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
565 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
566 "Not an identifier!");
568 Token IdentTok = Tok; // Save the whole token.
569 ConsumeToken(); // eat the identifier.
571 assert(Tok.is(tok::colon) && "Not a label!");
573 // identifier ':' statement
574 SourceLocation ColonLoc = ConsumeToken();
576 // Read label attributes, if present.
578 if (Tok.is(tok::kw___attribute)) {
579 ParsedAttributesWithRange TempAttrs(AttrFactory);
580 ParseGNUAttributes(TempAttrs);
582 // In C++, GNU attributes only apply to the label if they are followed by a
583 // semicolon, to disambiguate label attributes from attributes on a labeled
586 // This doesn't quite match what GCC does; if the attribute list is empty
587 // and followed by a semicolon, GCC will reject (it appears to parse the
588 // attributes as part of a statement in that case). That looks like a bug.
589 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
590 attrs.takeAllFrom(TempAttrs);
591 else if (isDeclarationStatement()) {
593 // FIXME: We should do this whether or not we have a declaration
594 // statement, but that doesn't work correctly (because ProhibitAttributes
595 // can't handle GNU attributes), so only call it in the one case where
596 // GNU attributes are allowed.
597 SubStmt = ParseStatementOrDeclarationAfterAttributes(
598 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
600 if (!TempAttrs.empty() && !SubStmt.isInvalid())
601 SubStmt = Actions.ProcessStmtAttributes(
602 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
604 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
608 // If we've not parsed a statement yet, parse one now.
609 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
610 SubStmt = ParseStatement();
612 // Broken substmt shouldn't prevent the label from being added to the AST.
613 if (SubStmt.isInvalid())
614 SubStmt = Actions.ActOnNullStmt(ColonLoc);
616 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
617 IdentTok.getLocation());
618 if (AttributeList *Attrs = attrs.getList()) {
619 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
623 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
627 /// ParseCaseStatement
628 /// labeled-statement:
629 /// 'case' constant-expression ':' statement
630 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
632 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
633 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
635 // It is very very common for code to contain many case statements recursively
636 // nested, as in (but usually without indentation):
643 // Parsing this naively works, but is both inefficient and can cause us to run
644 // out of stack space in our recursive descent parser. As a special case,
645 // flatten this recursion into an iterative loop. This is complex and gross,
646 // but all the grossness is constrained to ParseCaseStatement (and some
647 // weirdness in the actions), so this is just local grossness :).
649 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
651 StmtResult TopLevelCase(true);
653 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
654 // gets updated each time a new case is parsed, and whose body is unset so
655 // far. When parsing 'case 4', this is the 'case 3' node.
656 Stmt *DeepestParsedCaseStmt = nullptr;
658 // While we have case statements, eat and stack them.
659 SourceLocation ColonLoc;
661 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
662 ConsumeToken(); // eat the 'case'.
663 ColonLoc = SourceLocation();
665 if (Tok.is(tok::code_completion)) {
666 Actions.CodeCompleteCase(getCurScope());
671 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
672 /// Disable this form of error recovery while we're parsing the case
674 ColonProtectionRAIIObject ColonProtection(*this);
678 LHS = ParseConstantExpression();
679 if (!getLangOpts().CPlusPlus11) {
680 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
681 return Actions.VerifyIntegerConstantExpression(E);
684 if (LHS.isInvalid()) {
685 // If constant-expression is parsed unsuccessfully, recover by skipping
686 // current case statement (moving to the colon that ends it).
687 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
688 TryConsumeToken(tok::colon, ColonLoc);
698 // GNU case range extension.
699 SourceLocation DotDotDotLoc;
701 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
702 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
703 RHS = ParseConstantExpression();
704 if (RHS.isInvalid()) {
705 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
706 TryConsumeToken(tok::colon, ColonLoc);
713 ColonProtection.restore();
715 if (TryConsumeToken(tok::colon, ColonLoc)) {
716 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
717 TryConsumeToken(tok::coloncolon, ColonLoc)) {
718 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
719 Diag(ColonLoc, diag::err_expected_after)
720 << "'case'" << tok::colon
721 << FixItHint::CreateReplacement(ColonLoc, ":");
723 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
724 Diag(ExpectedLoc, diag::err_expected_after)
725 << "'case'" << tok::colon
726 << FixItHint::CreateInsertion(ExpectedLoc, ":");
727 ColonLoc = ExpectedLoc;
731 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
732 RHS.get(), ColonLoc);
734 // If we had a sema error parsing this case, then just ignore it and
735 // continue parsing the sub-stmt.
736 if (Case.isInvalid()) {
737 if (TopLevelCase.isInvalid()) // No parsed case stmts.
738 return ParseStatement(/*TrailingElseLoc=*/nullptr,
739 /*AllowOpenMPStandalone=*/true);
740 // Otherwise, just don't add it as a nested case.
742 // If this is the first case statement we parsed, it becomes TopLevelCase.
743 // Otherwise we link it into the current chain.
744 Stmt *NextDeepest = Case.get();
745 if (TopLevelCase.isInvalid())
748 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
749 DeepestParsedCaseStmt = NextDeepest;
752 // Handle all case statements.
753 } while (Tok.is(tok::kw_case));
755 // If we found a non-case statement, start by parsing it.
758 if (Tok.isNot(tok::r_brace)) {
759 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
760 /*AllowOpenMPStandalone=*/true);
762 // Nicely diagnose the common error "switch (X) { case 4: }", which is
763 // not valid. If ColonLoc doesn't point to a valid text location, there was
764 // another parsing error, so avoid producing extra diagnostics.
765 if (ColonLoc.isValid()) {
766 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
767 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
768 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
770 SubStmt = StmtError();
773 // Install the body into the most deeply-nested case.
774 if (DeepestParsedCaseStmt) {
775 // Broken sub-stmt shouldn't prevent forming the case statement properly.
776 if (SubStmt.isInvalid())
777 SubStmt = Actions.ActOnNullStmt(SourceLocation());
778 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
781 // Return the top level parsed statement tree.
785 /// ParseDefaultStatement
786 /// labeled-statement:
787 /// 'default' ':' statement
788 /// Note that this does not parse the 'statement' at the end.
790 StmtResult Parser::ParseDefaultStatement() {
791 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
792 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
794 SourceLocation ColonLoc;
795 if (TryConsumeToken(tok::colon, ColonLoc)) {
796 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
797 // Treat "default;" as a typo for "default:".
798 Diag(ColonLoc, diag::err_expected_after)
799 << "'default'" << tok::colon
800 << FixItHint::CreateReplacement(ColonLoc, ":");
802 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
803 Diag(ExpectedLoc, diag::err_expected_after)
804 << "'default'" << tok::colon
805 << FixItHint::CreateInsertion(ExpectedLoc, ":");
806 ColonLoc = ExpectedLoc;
811 if (Tok.isNot(tok::r_brace)) {
812 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
813 /*AllowOpenMPStandalone=*/true);
815 // Diagnose the common error "switch (X) {... default: }", which is
817 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
818 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
819 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
823 // Broken sub-stmt shouldn't prevent forming the case statement properly.
824 if (SubStmt.isInvalid())
825 SubStmt = Actions.ActOnNullStmt(ColonLoc);
827 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
828 SubStmt.get(), getCurScope());
831 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
832 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
835 /// ParseCompoundStatement - Parse a "{}" block.
837 /// compound-statement: [C99 6.8.2]
838 /// { block-item-list[opt] }
839 /// [GNU] { label-declarations block-item-list } [TODO]
843 /// block-item-list block-item
847 /// [GNU] '__extension__' declaration
850 /// [GNU] label-declarations:
851 /// [GNU] label-declaration
852 /// [GNU] label-declarations label-declaration
854 /// [GNU] label-declaration:
855 /// [GNU] '__label__' identifier-list ';'
857 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
858 unsigned ScopeFlags) {
859 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
861 // Enter a scope to hold everything within the compound stmt. Compound
862 // statements can always hold declarations.
863 ParseScope CompoundScope(this, ScopeFlags);
865 // Parse the statements in the body.
866 return ParseCompoundStatementBody(isStmtExpr);
869 /// Parse any pragmas at the start of the compound expression. We handle these
870 /// separately since some pragmas (FP_CONTRACT) must appear before any C
871 /// statement in the compound, but may be intermingled with other pragmas.
872 void Parser::ParseCompoundStatementLeadingPragmas() {
873 bool checkForPragmas = true;
874 while (checkForPragmas) {
875 switch (Tok.getKind()) {
876 case tok::annot_pragma_vis:
877 HandlePragmaVisibility();
879 case tok::annot_pragma_pack:
882 case tok::annot_pragma_msstruct:
883 HandlePragmaMSStruct();
885 case tok::annot_pragma_align:
888 case tok::annot_pragma_weak:
891 case tok::annot_pragma_weakalias:
892 HandlePragmaWeakAlias();
894 case tok::annot_pragma_redefine_extname:
895 HandlePragmaRedefineExtname();
897 case tok::annot_pragma_opencl_extension:
898 HandlePragmaOpenCLExtension();
900 case tok::annot_pragma_fp_contract:
901 HandlePragmaFPContract();
903 case tok::annot_pragma_ms_pointers_to_members:
904 HandlePragmaMSPointersToMembers();
906 case tok::annot_pragma_ms_pragma:
907 HandlePragmaMSPragma();
909 case tok::annot_pragma_ms_vtordisp:
910 HandlePragmaMSVtorDisp();
912 case tok::annot_pragma_dump:
916 checkForPragmas = false;
923 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
924 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
925 /// consume the '}' at the end of the block. It does not manipulate the scope
927 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
928 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
930 "in compound statement ('{}')");
932 // Record the state of the FP_CONTRACT pragma, restore on leaving the
933 // compound statement.
934 Sema::FPContractStateRAII SaveFPContractState(Actions);
936 InMessageExpressionRAIIObject InMessage(*this, false);
937 BalancedDelimiterTracker T(*this, tok::l_brace);
941 Sema::CompoundScopeRAII CompoundScope(Actions);
943 // Parse any pragmas at the beginning of the compound statement.
944 ParseCompoundStatementLeadingPragmas();
948 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
949 // only allowed at the start of a compound stmt regardless of the language.
950 while (Tok.is(tok::kw___label__)) {
951 SourceLocation LabelLoc = ConsumeToken();
953 SmallVector<Decl *, 8> DeclsInGroup;
955 if (Tok.isNot(tok::identifier)) {
956 Diag(Tok, diag::err_expected) << tok::identifier;
960 IdentifierInfo *II = Tok.getIdentifierInfo();
961 SourceLocation IdLoc = ConsumeToken();
962 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
964 if (!TryConsumeToken(tok::comma))
968 DeclSpec DS(AttrFactory);
970 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
971 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
973 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
975 Stmts.push_back(R.get());
978 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
979 Tok.isNot(tok::eof)) {
980 if (Tok.is(tok::annot_pragma_unused)) {
981 HandlePragmaUnused();
986 if (Tok.isNot(tok::kw___extension__)) {
987 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
989 // __extension__ can start declarations and it can also be a unary
990 // operator for expressions. Consume multiple __extension__ markers here
991 // until we can determine which is which.
992 // FIXME: This loses extension expressions in the AST!
993 SourceLocation ExtLoc = ConsumeToken();
994 while (Tok.is(tok::kw___extension__))
997 ParsedAttributesWithRange attrs(AttrFactory);
998 MaybeParseCXX11Attributes(attrs, nullptr,
999 /*MightBeObjCMessageSend*/ true);
1001 // If this is the start of a declaration, parse it as such.
1002 if (isDeclarationStatement()) {
1003 // __extension__ silences extension warnings in the subdeclaration.
1004 // FIXME: Save the __extension__ on the decl as a node somehow?
1005 ExtensionRAIIObject O(Diags);
1007 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1008 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
1010 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1012 // Otherwise this was a unary __extension__ marker.
1013 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1015 if (Res.isInvalid()) {
1016 SkipUntil(tok::semi);
1020 // FIXME: Use attributes?
1021 // Eat the semicolon at the end of stmt and convert the expr into a
1023 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1024 R = Actions.ActOnExprStmt(Res);
1029 Stmts.push_back(R.get());
1032 SourceLocation CloseLoc = Tok.getLocation();
1034 // We broke out of the while loop because we found a '}' or EOF.
1035 if (!T.consumeClose())
1036 // Recover by creating a compound statement with what we parsed so far,
1037 // instead of dropping everything and returning StmtError();
1038 CloseLoc = T.getCloseLocation();
1040 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1044 /// ParseParenExprOrCondition:
1045 /// [C ] '(' expression ')'
1046 /// [C++] '(' condition ')'
1047 /// [C++1z] '(' init-statement[opt] condition ')'
1049 /// This function parses and performs error recovery on the specified condition
1050 /// or expression (depending on whether we're in C++ or C mode). This function
1051 /// goes out of its way to recover well. It returns true if there was a parser
1052 /// error (the right paren couldn't be found), which indicates that the caller
1053 /// should try to recover harder. It returns false if the condition is
1054 /// successfully parsed. Note that a successful parse can still have semantic
1055 /// errors in the condition.
1056 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1057 Sema::ConditionResult &Cond,
1059 Sema::ConditionKind CK) {
1060 BalancedDelimiterTracker T(*this, tok::l_paren);
1063 if (getLangOpts().CPlusPlus)
1064 Cond = ParseCXXCondition(InitStmt, Loc, CK);
1066 ExprResult CondExpr = ParseExpression();
1068 // If required, convert to a boolean value.
1069 if (CondExpr.isInvalid())
1070 Cond = Sema::ConditionError();
1072 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1075 // If the parser was confused by the condition and we don't have a ')', try to
1076 // recover by skipping ahead to a semi and bailing out. If condexp is
1077 // semantically invalid but we have well formed code, keep going.
1078 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1079 SkipUntil(tok::semi);
1080 // Skipping may have stopped if it found the containing ')'. If so, we can
1081 // continue parsing the if statement.
1082 if (Tok.isNot(tok::r_paren))
1086 // Otherwise the condition is valid or the rparen is present.
1089 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1090 // that all callers are looking for a statement after the condition, so ")"
1092 while (Tok.is(tok::r_paren)) {
1093 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1094 << FixItHint::CreateRemoval(Tok.getLocation());
1102 /// ParseIfStatement
1103 /// if-statement: [C99 6.8.4.1]
1104 /// 'if' '(' expression ')' statement
1105 /// 'if' '(' expression ')' statement 'else' statement
1106 /// [C++] 'if' '(' condition ')' statement
1107 /// [C++] 'if' '(' condition ')' statement 'else' statement
1109 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1110 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1111 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1113 bool IsConstexpr = false;
1114 if (Tok.is(tok::kw_constexpr)) {
1115 Diag(Tok, getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_constexpr_if
1116 : diag::ext_constexpr_if);
1121 if (Tok.isNot(tok::l_paren)) {
1122 Diag(Tok, diag::err_expected_lparen_after) << "if";
1123 SkipUntil(tok::semi);
1127 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1129 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1130 // the case for C90.
1133 // A name introduced by a declaration in a condition is in scope from its
1134 // point of declaration until the end of the substatements controlled by the
1137 // Names declared in the for-init-statement, and in the condition of if,
1138 // while, for, and switch statements are local to the if, while, for, or
1139 // switch statement (including the controlled statement).
1141 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1143 // Parse the condition.
1144 StmtResult InitStmt;
1145 Sema::ConditionResult Cond;
1146 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1147 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1148 : Sema::ConditionKind::Boolean))
1151 llvm::Optional<bool> ConstexprCondition;
1153 ConstexprCondition = Cond.getKnownValue();
1155 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1156 // there is no compound stmt. C90 does not have this clause. We only do this
1157 // if the body isn't a compound statement to avoid push/pop in common cases.
1160 // The substatement in a selection-statement (each substatement, in the else
1161 // form of the if statement) implicitly defines a local scope.
1163 // For C++ we create a scope for the condition and a new scope for
1164 // substatements because:
1165 // -When the 'then' scope exits, we want the condition declaration to still be
1166 // active for the 'else' scope too.
1167 // -Sema will detect name clashes by considering declarations of a
1168 // 'ControlScope' as part of its direct subscope.
1169 // -If we wanted the condition and substatement to be in the same scope, we
1170 // would have to notify ParseStatement not to create a new scope. It's
1171 // simpler to let it create a new scope.
1173 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1175 // Read the 'then' stmt.
1176 SourceLocation ThenStmtLoc = Tok.getLocation();
1178 SourceLocation InnerStatementTrailingElseLoc;
1179 StmtResult ThenStmt;
1181 EnterExpressionEvaluationContext PotentiallyDiscarded(
1182 Actions, Sema::DiscardedStatement, nullptr, false,
1183 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1184 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1187 // Pop the 'if' scope if needed.
1190 // If it has an else, parse it.
1191 SourceLocation ElseLoc;
1192 SourceLocation ElseStmtLoc;
1193 StmtResult ElseStmt;
1195 if (Tok.is(tok::kw_else)) {
1196 if (TrailingElseLoc)
1197 *TrailingElseLoc = Tok.getLocation();
1199 ElseLoc = ConsumeToken();
1200 ElseStmtLoc = Tok.getLocation();
1202 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1203 // there is no compound stmt. C90 does not have this clause. We only do
1204 // this if the body isn't a compound statement to avoid push/pop in common
1208 // The substatement in a selection-statement (each substatement, in the else
1209 // form of the if statement) implicitly defines a local scope.
1211 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1212 Tok.is(tok::l_brace));
1214 EnterExpressionEvaluationContext PotentiallyDiscarded(
1215 Actions, Sema::DiscardedStatement, nullptr, false,
1216 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1217 ElseStmt = ParseStatement();
1219 // Pop the 'else' scope if needed.
1221 } else if (Tok.is(tok::code_completion)) {
1222 Actions.CodeCompleteAfterIf(getCurScope());
1225 } else if (InnerStatementTrailingElseLoc.isValid()) {
1226 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1231 // If the then or else stmt is invalid and the other is valid (and present),
1232 // make turn the invalid one into a null stmt to avoid dropping the other
1233 // part. If both are invalid, return error.
1234 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1235 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1236 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1237 // Both invalid, or one is invalid and other is non-present: return error.
1241 // Now if either are invalid, replace with a ';'.
1242 if (ThenStmt.isInvalid())
1243 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1244 if (ElseStmt.isInvalid())
1245 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1247 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1248 ThenStmt.get(), ElseLoc, ElseStmt.get());
1251 /// ParseSwitchStatement
1252 /// switch-statement:
1253 /// 'switch' '(' expression ')' statement
1254 /// [C++] 'switch' '(' condition ')' statement
1255 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1256 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1257 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1259 if (Tok.isNot(tok::l_paren)) {
1260 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1261 SkipUntil(tok::semi);
1265 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1267 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1268 // not the case for C90. Start the switch scope.
1271 // A name introduced by a declaration in a condition is in scope from its
1272 // point of declaration until the end of the substatements controlled by the
1275 // Names declared in the for-init-statement, and in the condition of if,
1276 // while, for, and switch statements are local to the if, while, for, or
1277 // switch statement (including the controlled statement).
1279 unsigned ScopeFlags = Scope::SwitchScope;
1281 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1282 ParseScope SwitchScope(this, ScopeFlags);
1284 // Parse the condition.
1285 StmtResult InitStmt;
1286 Sema::ConditionResult Cond;
1287 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1288 Sema::ConditionKind::Switch))
1292 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1294 if (Switch.isInvalid()) {
1295 // Skip the switch body.
1296 // FIXME: This is not optimal recovery, but parsing the body is more
1297 // dangerous due to the presence of case and default statements, which
1298 // will have no place to connect back with the switch.
1299 if (Tok.is(tok::l_brace)) {
1301 SkipUntil(tok::r_brace);
1303 SkipUntil(tok::semi);
1307 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1308 // there is no compound stmt. C90 does not have this clause. We only do this
1309 // if the body isn't a compound statement to avoid push/pop in common cases.
1312 // The substatement in a selection-statement (each substatement, in the else
1313 // form of the if statement) implicitly defines a local scope.
1315 // See comments in ParseIfStatement for why we create a scope for the
1316 // condition and a new scope for substatement in C++.
1318 getCurScope()->AddFlags(Scope::BreakScope);
1319 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1321 // We have incremented the mangling number for the SwitchScope and the
1322 // InnerScope, which is one too many.
1324 getCurScope()->decrementMSManglingNumber();
1326 // Read the body statement.
1327 StmtResult Body(ParseStatement(TrailingElseLoc));
1333 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1336 /// ParseWhileStatement
1337 /// while-statement: [C99 6.8.5.1]
1338 /// 'while' '(' expression ')' statement
1339 /// [C++] 'while' '(' condition ')' statement
1340 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1341 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1342 SourceLocation WhileLoc = Tok.getLocation();
1343 ConsumeToken(); // eat the 'while'.
1345 if (Tok.isNot(tok::l_paren)) {
1346 Diag(Tok, diag::err_expected_lparen_after) << "while";
1347 SkipUntil(tok::semi);
1351 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1353 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1354 // the case for C90. Start the loop scope.
1357 // A name introduced by a declaration in a condition is in scope from its
1358 // point of declaration until the end of the substatements controlled by the
1361 // Names declared in the for-init-statement, and in the condition of if,
1362 // while, for, and switch statements are local to the if, while, for, or
1363 // switch statement (including the controlled statement).
1365 unsigned ScopeFlags;
1367 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1368 Scope::DeclScope | Scope::ControlScope;
1370 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1371 ParseScope WhileScope(this, ScopeFlags);
1373 // Parse the condition.
1374 Sema::ConditionResult Cond;
1375 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1376 Sema::ConditionKind::Boolean))
1379 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1380 // there is no compound stmt. C90 does not have this clause. We only do this
1381 // if the body isn't a compound statement to avoid push/pop in common cases.
1384 // The substatement in an iteration-statement implicitly defines a local scope
1385 // which is entered and exited each time through the loop.
1387 // See comments in ParseIfStatement for why we create a scope for the
1388 // condition and a new scope for substatement in C++.
1390 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1392 // Read the body statement.
1393 StmtResult Body(ParseStatement(TrailingElseLoc));
1395 // Pop the body scope if needed.
1399 if (Cond.isInvalid() || Body.isInvalid())
1402 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1405 /// ParseDoStatement
1406 /// do-statement: [C99 6.8.5.2]
1407 /// 'do' statement 'while' '(' expression ')' ';'
1408 /// Note: this lets the caller parse the end ';'.
1409 StmtResult Parser::ParseDoStatement() {
1410 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1411 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1413 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1414 // the case for C90. Start the loop scope.
1415 unsigned ScopeFlags;
1416 if (getLangOpts().C99)
1417 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1419 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1421 ParseScope DoScope(this, ScopeFlags);
1423 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1424 // there is no compound stmt. C90 does not have this clause. We only do this
1425 // if the body isn't a compound statement to avoid push/pop in common cases.
1428 // The substatement in an iteration-statement implicitly defines a local scope
1429 // which is entered and exited each time through the loop.
1431 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1432 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1434 // Read the body statement.
1435 StmtResult Body(ParseStatement());
1437 // Pop the body scope if needed.
1440 if (Tok.isNot(tok::kw_while)) {
1441 if (!Body.isInvalid()) {
1442 Diag(Tok, diag::err_expected_while);
1443 Diag(DoLoc, diag::note_matching) << "'do'";
1444 SkipUntil(tok::semi, StopBeforeMatch);
1448 SourceLocation WhileLoc = ConsumeToken();
1450 if (Tok.isNot(tok::l_paren)) {
1451 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1452 SkipUntil(tok::semi, StopBeforeMatch);
1456 // Parse the parenthesized expression.
1457 BalancedDelimiterTracker T(*this, tok::l_paren);
1460 // A do-while expression is not a condition, so can't have attributes.
1461 DiagnoseAndSkipCXX11Attributes();
1463 ExprResult Cond = ParseExpression();
1467 if (Cond.isInvalid() || Body.isInvalid())
1470 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1471 Cond.get(), T.getCloseLocation());
1474 bool Parser::isForRangeIdentifier() {
1475 assert(Tok.is(tok::identifier));
1477 const Token &Next = NextToken();
1478 if (Next.is(tok::colon))
1481 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1482 TentativeParsingAction PA(*this);
1484 SkipCXX11Attributes();
1485 bool Result = Tok.is(tok::colon);
1493 /// ParseForStatement
1494 /// for-statement: [C99 6.8.5.3]
1495 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1496 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1497 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1500 /// 'co_await'[opt] [Coroutines]
1501 /// '(' for-range-declaration ':' for-range-initializer ')'
1503 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1504 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1506 /// [C++] for-init-statement:
1507 /// [C++] expression-statement
1508 /// [C++] simple-declaration
1510 /// [C++0x] for-range-declaration:
1511 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1512 /// [C++0x] for-range-initializer:
1513 /// [C++0x] expression
1514 /// [C++0x] braced-init-list [TODO]
1515 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1516 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1517 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1519 SourceLocation CoawaitLoc;
1520 if (Tok.is(tok::kw_co_await))
1521 CoawaitLoc = ConsumeToken();
1523 if (Tok.isNot(tok::l_paren)) {
1524 Diag(Tok, diag::err_expected_lparen_after) << "for";
1525 SkipUntil(tok::semi);
1529 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1530 getLangOpts().ObjC1;
1532 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1533 // the case for C90. Start the loop scope.
1536 // A name introduced by a declaration in a condition is in scope from its
1537 // point of declaration until the end of the substatements controlled by the
1540 // Names declared in the for-init-statement, and in the condition of if,
1541 // while, for, and switch statements are local to the if, while, for, or
1542 // switch statement (including the controlled statement).
1544 // Names declared in the for-init-statement are in the same declarative-region
1545 // as those declared in the condition.
1547 unsigned ScopeFlags = 0;
1549 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1551 ParseScope ForScope(this, ScopeFlags);
1553 BalancedDelimiterTracker T(*this, tok::l_paren);
1558 bool ForEach = false, ForRange = false;
1559 StmtResult FirstPart;
1560 Sema::ConditionResult SecondPart;
1561 ExprResult Collection;
1562 ForRangeInit ForRangeInit;
1563 FullExprArg ThirdPart(Actions);
1565 if (Tok.is(tok::code_completion)) {
1566 Actions.CodeCompleteOrdinaryName(getCurScope(),
1567 C99orCXXorObjC? Sema::PCC_ForInit
1568 : Sema::PCC_Expression);
1573 ParsedAttributesWithRange attrs(AttrFactory);
1574 MaybeParseCXX11Attributes(attrs);
1576 // Parse the first part of the for specifier.
1577 if (Tok.is(tok::semi)) { // for (;
1578 ProhibitAttributes(attrs);
1579 // no first part, eat the ';'.
1581 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1582 isForRangeIdentifier()) {
1583 ProhibitAttributes(attrs);
1584 IdentifierInfo *Name = Tok.getIdentifierInfo();
1585 SourceLocation Loc = ConsumeToken();
1586 MaybeParseCXX11Attributes(attrs);
1588 ForRangeInit.ColonLoc = ConsumeToken();
1589 if (Tok.is(tok::l_brace))
1590 ForRangeInit.RangeExpr = ParseBraceInitializer();
1592 ForRangeInit.RangeExpr = ParseExpression();
1594 Diag(Loc, diag::err_for_range_identifier)
1595 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1596 ? FixItHint::CreateInsertion(Loc, "auto &&")
1599 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1600 attrs, attrs.Range.getEnd());
1602 } else if (isForInitDeclaration()) { // for (int X = 4;
1603 // Parse declaration, which eats the ';'.
1604 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1605 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1607 // In C++0x, "for (T NS:a" might not be a typo for ::
1608 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1609 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1611 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1612 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1613 Declarator::ForContext, DeclEnd, attrs, false,
1614 MightBeForRangeStmt ? &ForRangeInit : nullptr);
1615 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1616 if (ForRangeInit.ParsedForRangeDecl()) {
1617 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1618 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1621 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1623 } else if ((ForEach = isTokIdentifier_in())) {
1624 Actions.ActOnForEachDeclStmt(DG);
1625 // ObjC: for (id x in expr)
1626 ConsumeToken(); // consume 'in'
1628 if (Tok.is(tok::code_completion)) {
1629 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1633 Collection = ParseExpression();
1635 Diag(Tok, diag::err_expected_semi_for);
1638 ProhibitAttributes(attrs);
1639 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1641 ForEach = isTokIdentifier_in();
1643 // Turn the expression into a stmt.
1644 if (!Value.isInvalid()) {
1646 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1648 FirstPart = Actions.ActOnExprStmt(Value);
1651 if (Tok.is(tok::semi)) {
1653 } else if (ForEach) {
1654 ConsumeToken(); // consume 'in'
1656 if (Tok.is(tok::code_completion)) {
1657 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1661 Collection = ParseExpression();
1662 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1663 // User tried to write the reasonable, but ill-formed, for-range-statement
1664 // for (expr : expr) { ... }
1665 Diag(Tok, diag::err_for_range_expected_decl)
1666 << FirstPart.get()->getSourceRange();
1667 SkipUntil(tok::r_paren, StopBeforeMatch);
1668 SecondPart = Sema::ConditionError();
1670 if (!Value.isInvalid()) {
1671 Diag(Tok, diag::err_expected_semi_for);
1673 // Skip until semicolon or rparen, don't consume it.
1674 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1675 if (Tok.is(tok::semi))
1681 // Parse the second part of the for specifier.
1682 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1683 if (!ForEach && !ForRange && !SecondPart.isInvalid()) {
1684 // Parse the second part of the for specifier.
1685 if (Tok.is(tok::semi)) { // for (...;;
1687 } else if (Tok.is(tok::r_paren)) {
1688 // missing both semicolons.
1690 if (getLangOpts().CPlusPlus)
1692 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean);
1694 ExprResult SecondExpr = ParseExpression();
1695 if (SecondExpr.isInvalid())
1696 SecondPart = Sema::ConditionError();
1699 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1700 Sema::ConditionKind::Boolean);
1704 if (Tok.isNot(tok::semi)) {
1705 if (!SecondPart.isInvalid())
1706 Diag(Tok, diag::err_expected_semi_for);
1708 // Skip until semicolon or rparen, don't consume it.
1709 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1712 if (Tok.is(tok::semi)) {
1716 // Parse the third part of the for specifier.
1717 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1718 ExprResult Third = ParseExpression();
1719 // FIXME: The C++11 standard doesn't actually say that this is a
1720 // discarded-value expression, but it clearly should be.
1721 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1727 // C++ Coroutines [stmt.iter]:
1728 // 'co_await' can only be used for a range-based for statement.
1729 if (CoawaitLoc.isValid() && !ForRange) {
1730 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1731 CoawaitLoc = SourceLocation();
1734 // We need to perform most of the semantic analysis for a C++0x for-range
1735 // statememt before parsing the body, in order to be able to deduce the type
1736 // of an auto-typed loop variable.
1737 StmtResult ForRangeStmt;
1738 StmtResult ForEachStmt;
1741 ExprResult CorrectedRange =
1742 Actions.CorrectDelayedTyposInExpr(ForRangeInit.RangeExpr.get());
1743 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1744 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1745 ForRangeInit.ColonLoc, CorrectedRange.get(),
1746 T.getCloseLocation(), Sema::BFRK_Build);
1748 // Similarly, we need to do the semantic analysis for a for-range
1749 // statement immediately in order to close over temporaries correctly.
1750 } else if (ForEach) {
1751 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1754 T.getCloseLocation());
1756 // In OpenMP loop region loop control variable must be captured and be
1757 // private. Perform analysis of first part (if any).
1758 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1759 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1763 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1764 // there is no compound stmt. C90 does not have this clause. We only do this
1765 // if the body isn't a compound statement to avoid push/pop in common cases.
1768 // The substatement in an iteration-statement implicitly defines a local scope
1769 // which is entered and exited each time through the loop.
1771 // See comments in ParseIfStatement for why we create a scope for
1772 // for-init-statement/condition and a new scope for substatement in C++.
1774 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1775 Tok.is(tok::l_brace));
1777 // The body of the for loop has the same local mangling number as the
1778 // for-init-statement.
1779 // It will only be incremented if the body contains other things that would
1780 // normally increment the mangling number (like a compound statement).
1782 getCurScope()->decrementMSManglingNumber();
1784 // Read the body statement.
1785 StmtResult Body(ParseStatement(TrailingElseLoc));
1787 // Pop the body scope if needed.
1790 // Leave the for-scope.
1793 if (Body.isInvalid())
1797 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1801 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1803 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1804 SecondPart, ThirdPart, T.getCloseLocation(),
1808 /// ParseGotoStatement
1810 /// 'goto' identifier ';'
1811 /// [GNU] 'goto' '*' expression ';'
1813 /// Note: this lets the caller parse the end ';'.
1815 StmtResult Parser::ParseGotoStatement() {
1816 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1817 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1820 if (Tok.is(tok::identifier)) {
1821 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1823 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1825 } else if (Tok.is(tok::star)) {
1826 // GNU indirect goto extension.
1827 Diag(Tok, diag::ext_gnu_indirect_goto);
1828 SourceLocation StarLoc = ConsumeToken();
1829 ExprResult R(ParseExpression());
1830 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1831 SkipUntil(tok::semi, StopBeforeMatch);
1834 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1836 Diag(Tok, diag::err_expected) << tok::identifier;
1843 /// ParseContinueStatement
1847 /// Note: this lets the caller parse the end ';'.
1849 StmtResult Parser::ParseContinueStatement() {
1850 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1851 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1854 /// ParseBreakStatement
1858 /// Note: this lets the caller parse the end ';'.
1860 StmtResult Parser::ParseBreakStatement() {
1861 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1862 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1865 /// ParseReturnStatement
1867 /// 'return' expression[opt] ';'
1868 /// 'return' braced-init-list ';'
1869 /// 'co_return' expression[opt] ';'
1870 /// 'co_return' braced-init-list ';'
1871 StmtResult Parser::ParseReturnStatement() {
1872 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1873 "Not a return stmt!");
1874 bool IsCoreturn = Tok.is(tok::kw_co_return);
1875 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1878 if (Tok.isNot(tok::semi)) {
1879 // FIXME: Code completion for co_return.
1880 if (Tok.is(tok::code_completion) && !IsCoreturn) {
1881 Actions.CodeCompleteReturn(getCurScope());
1886 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1887 R = ParseInitializer();
1889 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1890 diag::warn_cxx98_compat_generalized_initializer_lists :
1891 diag::ext_generalized_initializer_lists)
1892 << R.get()->getSourceRange();
1894 R = ParseExpression();
1895 if (R.isInvalid()) {
1896 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1901 return Actions.ActOnCoreturnStmt(ReturnLoc, R.get());
1902 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1905 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1906 AllowedContsructsKind Allowed,
1907 SourceLocation *TrailingElseLoc,
1908 ParsedAttributesWithRange &Attrs) {
1909 // Create temporary attribute list.
1910 ParsedAttributesWithRange TempAttrs(AttrFactory);
1912 // Get loop hints and consume annotated token.
1913 while (Tok.is(tok::annot_pragma_loop_hint)) {
1915 if (!HandlePragmaLoopHint(Hint))
1918 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1919 ArgsUnion(Hint.ValueExpr)};
1920 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1921 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1922 AttributeList::AS_Pragma);
1925 // Get the next statement.
1926 MaybeParseCXX11Attributes(Attrs);
1928 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1929 Stmts, Allowed, TrailingElseLoc, Attrs);
1931 Attrs.takeAllFrom(TempAttrs);
1935 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1936 assert(Tok.is(tok::l_brace));
1937 SourceLocation LBraceLoc = Tok.getLocation();
1939 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1940 "parsing function body");
1942 // Save and reset current vtordisp stack if we have entered a C++ method body.
1944 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1945 Sema::PragmaStackSentinelRAII
1946 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1948 // Do not enter a scope for the brace, as the arguments are in the same scope
1949 // (the function body) as the body itself. Instead, just read the statement
1950 // list and put it into a CompoundStmt for safe keeping.
1951 StmtResult FnBody(ParseCompoundStatementBody());
1953 // If the function body could not be parsed, make a bogus compoundstmt.
1954 if (FnBody.isInvalid()) {
1955 Sema::CompoundScopeRAII CompoundScope(Actions);
1956 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1960 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1963 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1965 /// function-try-block:
1966 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1968 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1969 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1970 SourceLocation TryLoc = ConsumeToken();
1972 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1973 "parsing function try block");
1975 // Constructor initializer list?
1976 if (Tok.is(tok::colon))
1977 ParseConstructorInitializer(Decl);
1979 Actions.ActOnDefaultCtorInitializers(Decl);
1981 // Save and reset current vtordisp stack if we have entered a C++ method body.
1983 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1984 Sema::PragmaStackSentinelRAII
1985 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1987 SourceLocation LBraceLoc = Tok.getLocation();
1988 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
1989 // If we failed to parse the try-catch, we just give the function an empty
1990 // compound statement as the body.
1991 if (FnBody.isInvalid()) {
1992 Sema::CompoundScopeRAII CompoundScope(Actions);
1993 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1997 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2000 bool Parser::trySkippingFunctionBody() {
2001 assert(SkipFunctionBodies &&
2002 "Should only be called when SkipFunctionBodies is enabled");
2003 if (!PP.isCodeCompletionEnabled()) {
2008 // We're in code-completion mode. Skip parsing for all function bodies unless
2009 // the body contains the code-completion point.
2010 TentativeParsingAction PA(*this);
2011 bool IsTryCatch = Tok.is(tok::kw_try);
2013 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2014 if (llvm::any_of(Toks, [](const Token &Tok) {
2015 return Tok.is(tok::code_completion);
2020 if (ErrorInPrologue) {
2022 SkipMalformedDecl();
2025 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2029 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2030 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2031 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2040 /// ParseCXXTryBlock - Parse a C++ try-block.
2043 /// 'try' compound-statement handler-seq
2045 StmtResult Parser::ParseCXXTryBlock() {
2046 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2048 SourceLocation TryLoc = ConsumeToken();
2049 return ParseCXXTryBlockCommon(TryLoc);
2052 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2053 /// function-try-block.
2056 /// 'try' compound-statement handler-seq
2058 /// function-try-block:
2059 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2062 /// handler handler-seq[opt]
2064 /// [Borland] try-block:
2065 /// 'try' compound-statement seh-except-block
2066 /// 'try' compound-statement seh-finally-block
2068 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2069 if (Tok.isNot(tok::l_brace))
2070 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2072 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2073 Scope::DeclScope | Scope::TryScope |
2074 (FnTry ? Scope::FnTryCatchScope : 0)));
2075 if (TryBlock.isInvalid())
2078 // Borland allows SEH-handlers with 'try'
2080 if ((Tok.is(tok::identifier) &&
2081 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2082 Tok.is(tok::kw___finally)) {
2083 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2085 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2086 SourceLocation Loc = ConsumeToken();
2087 Handler = ParseSEHExceptBlock(Loc);
2090 SourceLocation Loc = ConsumeToken();
2091 Handler = ParseSEHFinallyBlock(Loc);
2093 if(Handler.isInvalid())
2096 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2102 StmtVector Handlers;
2104 // C++11 attributes can't appear here, despite this context seeming
2106 DiagnoseAndSkipCXX11Attributes();
2108 if (Tok.isNot(tok::kw_catch))
2109 return StmtError(Diag(Tok, diag::err_expected_catch));
2110 while (Tok.is(tok::kw_catch)) {
2111 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2112 if (!Handler.isInvalid())
2113 Handlers.push_back(Handler.get());
2115 // Don't bother creating the full statement if we don't have any usable
2117 if (Handlers.empty())
2120 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2124 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2127 /// 'catch' '(' exception-declaration ')' compound-statement
2129 /// exception-declaration:
2130 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2131 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2134 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2135 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2137 SourceLocation CatchLoc = ConsumeToken();
2139 BalancedDelimiterTracker T(*this, tok::l_paren);
2140 if (T.expectAndConsume())
2144 // The name in a catch exception-declaration is local to the handler and
2145 // shall not be redeclared in the outermost block of the handler.
2146 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2147 (FnCatch ? Scope::FnTryCatchScope : 0));
2149 // exception-declaration is equivalent to '...' or a parameter-declaration
2150 // without default arguments.
2151 Decl *ExceptionDecl = nullptr;
2152 if (Tok.isNot(tok::ellipsis)) {
2153 ParsedAttributesWithRange Attributes(AttrFactory);
2154 MaybeParseCXX11Attributes(Attributes);
2156 DeclSpec DS(AttrFactory);
2157 DS.takeAttributesFrom(Attributes);
2159 if (ParseCXXTypeSpecifierSeq(DS))
2162 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2163 ParseDeclarator(ExDecl);
2164 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2169 if (T.getCloseLocation().isInvalid())
2172 if (Tok.isNot(tok::l_brace))
2173 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2175 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2176 StmtResult Block(ParseCompoundStatement());
2177 if (Block.isInvalid())
2180 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2183 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2184 IfExistsCondition Result;
2185 if (ParseMicrosoftIfExistsCondition(Result))
2188 // Handle dependent statements by parsing the braces as a compound statement.
2189 // This is not the same behavior as Visual C++, which don't treat this as a
2190 // compound statement, but for Clang's type checking we can't have anything
2191 // inside these braces escaping to the surrounding code.
2192 if (Result.Behavior == IEB_Dependent) {
2193 if (!Tok.is(tok::l_brace)) {
2194 Diag(Tok, diag::err_expected) << tok::l_brace;
2198 StmtResult Compound = ParseCompoundStatement();
2199 if (Compound.isInvalid())
2202 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2207 if (DepResult.isUsable())
2208 Stmts.push_back(DepResult.get());
2212 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2213 if (Braces.consumeOpen()) {
2214 Diag(Tok, diag::err_expected) << tok::l_brace;
2218 switch (Result.Behavior) {
2220 // Parse the statements below.
2224 llvm_unreachable("Dependent case handled above");
2231 // Condition is true, parse the statements.
2232 while (Tok.isNot(tok::r_brace)) {
2233 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2235 Stmts.push_back(R.get());
2237 Braces.consumeClose();
2240 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2241 MaybeParseGNUAttributes(Attrs);
2246 if (Attrs.getList()->getKind() != AttributeList::AT_OpenCLUnrollHint)
2249 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2250 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);