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/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/Basic/Attributes.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/PrettyStackTrace.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/LoopHint.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Scope.h"
25 #include "clang/Sema/TypoCorrection.h"
26 #include "llvm/ADT/SmallString.h"
27 using namespace clang;
29 //===----------------------------------------------------------------------===//
30 // C99 6.8: Statements and Blocks.
31 //===----------------------------------------------------------------------===//
33 /// \brief Parse a standalone statement (for instance, as the body of an 'if',
34 /// 'while', or 'for').
35 StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
36 bool AllowOpenMPStandalone) {
39 // We may get back a null statement if we found a #pragma. Keep going until
40 // we get an actual statement.
43 Res = ParseStatementOrDeclaration(
44 Stmts, AllowOpenMPStandalone ? ACK_StatementsOpenMPAnyExecutable
45 : ACK_StatementsOpenMPNonStandalone,
47 } while (!Res.isInvalid() && !Res.get());
52 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
53 /// StatementOrDeclaration:
59 /// compound-statement
60 /// expression-statement
61 /// selection-statement
62 /// iteration-statement
64 /// [C++] declaration-statement
66 /// [MS] seh-try-block
67 /// [OBC] objc-throw-statement
68 /// [OBC] objc-try-catch-statement
69 /// [OBC] objc-synchronized-statement
70 /// [GNU] asm-statement
71 /// [OMP] openmp-construct [TODO]
73 /// labeled-statement:
74 /// identifier ':' statement
75 /// 'case' constant-expression ':' statement
76 /// 'default' ':' statement
78 /// selection-statement:
82 /// iteration-statement:
87 /// expression-statement:
88 /// expression[opt] ';'
91 /// 'goto' identifier ';'
94 /// 'return' expression[opt] ';'
95 /// [GNU] 'goto' '*' expression ';'
97 /// [OBC] objc-throw-statement:
98 /// [OBC] '@' 'throw' expression ';'
99 /// [OBC] '@' 'throw' ';'
102 Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
103 AllowedContsructsKind Allowed,
104 SourceLocation *TrailingElseLoc) {
106 ParenBraceBracketBalancer BalancerRAIIObj(*this);
108 ParsedAttributesWithRange Attrs(AttrFactory);
109 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
111 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
112 Stmts, Allowed, TrailingElseLoc, Attrs);
114 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
115 "attributes on empty statement");
117 if (Attrs.empty() || Res.isInvalid())
120 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
124 class StatementFilterCCC : public CorrectionCandidateCallback {
126 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
127 WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
128 tok::identifier, tok::star, tok::amp);
129 WantExpressionKeywords =
130 nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
131 WantRemainingKeywords =
132 nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
133 WantCXXNamedCasts = false;
136 bool ValidateCandidate(const TypoCorrection &candidate) override {
137 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
138 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
139 if (NextToken.is(tok::equal))
140 return candidate.getCorrectionDeclAs<VarDecl>();
141 if (NextToken.is(tok::period) &&
142 candidate.getCorrectionDeclAs<NamespaceDecl>())
144 return CorrectionCandidateCallback::ValidateCandidate(candidate);
153 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
154 AllowedContsructsKind Allowed, SourceLocation *TrailingElseLoc,
155 ParsedAttributesWithRange &Attrs) {
156 const char *SemiError = nullptr;
159 // Cases in this switch statement should fall through if the parser expects
160 // the token to end in a semicolon (in which case SemiError should be set),
161 // or they directly 'return;' if not.
163 tok::TokenKind Kind = Tok.getKind();
164 SourceLocation AtLoc;
166 case tok::at: // May be a @try or @throw statement
168 ProhibitAttributes(Attrs); // TODO: is it correct?
169 AtLoc = ConsumeToken(); // consume @
170 return ParseObjCAtStatement(AtLoc);
173 case tok::code_completion:
174 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
178 case tok::identifier: {
179 Token Next = NextToken();
180 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
181 // identifier ':' statement
182 return ParseLabeledStatement(Attrs);
185 // Look up the identifier, and typo-correct it to a keyword if it's not
187 if (Next.isNot(tok::coloncolon)) {
188 // Try to limit which sets of keywords should be included in typo
189 // correction based on what the next token is.
190 if (TryAnnotateName(/*IsAddressOfOperand*/ false,
191 llvm::make_unique<StatementFilterCCC>(Next)) ==
193 // Handle errors here by skipping up to the next semicolon or '}', and
194 // eat the semicolon if that's what stopped us.
195 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
196 if (Tok.is(tok::semi))
201 // If the identifier was typo-corrected, try again.
202 if (Tok.isNot(tok::identifier))
210 if ((getLangOpts().CPlusPlus || 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 // expression[opt] ';'
400 ExprResult Expr(ParseExpression());
401 if (Expr.isInvalid()) {
402 // If the expression is invalid, skip ahead to the next semicolon or '}'.
403 // Not doing this opens us up to the possibility of infinite loops if
404 // ParseExpression does not consume any tokens.
405 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
406 if (Tok.is(tok::semi))
408 return Actions.ActOnExprStmtError();
411 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
412 Actions.CheckCaseExpression(Expr.get())) {
413 // If a constant expression is followed by a colon inside a switch block,
414 // suggest a missing case keyword.
415 Diag(OldToken, diag::err_expected_case_before_expression)
416 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
418 // Recover parsing as a case statement.
419 return ParseCaseStatement(/*MissingCase=*/true, Expr);
422 // Otherwise, eat the semicolon.
423 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
424 return Actions.ActOnExprStmt(Expr);
427 /// ParseSEHTryBlockCommon
430 /// '__try' compound-statement seh-handler
434 /// seh-finally-block
436 StmtResult Parser::ParseSEHTryBlock() {
437 assert(Tok.is(tok::kw___try) && "Expected '__try'");
438 SourceLocation TryLoc = ConsumeToken();
440 if (Tok.isNot(tok::l_brace))
441 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
443 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
444 Scope::DeclScope | Scope::SEHTryScope));
445 if(TryBlock.isInvalid())
449 if (Tok.is(tok::identifier) &&
450 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
451 SourceLocation Loc = ConsumeToken();
452 Handler = ParseSEHExceptBlock(Loc);
453 } else if (Tok.is(tok::kw___finally)) {
454 SourceLocation Loc = ConsumeToken();
455 Handler = ParseSEHFinallyBlock(Loc);
457 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
460 if(Handler.isInvalid())
463 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
469 /// ParseSEHExceptBlock - Handle __except
471 /// seh-except-block:
472 /// '__except' '(' seh-filter-expression ')' compound-statement
474 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
475 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
476 raii2(Ident___exception_code, false),
477 raii3(Ident_GetExceptionCode, false);
479 if (ExpectAndConsume(tok::l_paren))
482 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
483 Scope::SEHExceptScope);
485 if (getLangOpts().Borland) {
486 Ident__exception_info->setIsPoisoned(false);
487 Ident___exception_info->setIsPoisoned(false);
488 Ident_GetExceptionInfo->setIsPoisoned(false);
491 ExprResult FilterExpr;
493 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
494 Scope::SEHFilterScope);
495 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
498 if (getLangOpts().Borland) {
499 Ident__exception_info->setIsPoisoned(true);
500 Ident___exception_info->setIsPoisoned(true);
501 Ident_GetExceptionInfo->setIsPoisoned(true);
504 if(FilterExpr.isInvalid())
507 if (ExpectAndConsume(tok::r_paren))
510 if (Tok.isNot(tok::l_brace))
511 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
513 StmtResult Block(ParseCompoundStatement());
515 if(Block.isInvalid())
518 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
521 /// ParseSEHFinallyBlock - Handle __finally
523 /// seh-finally-block:
524 /// '__finally' compound-statement
526 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
527 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
528 raii2(Ident___abnormal_termination, false),
529 raii3(Ident_AbnormalTermination, false);
531 if (Tok.isNot(tok::l_brace))
532 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
534 ParseScope FinallyScope(this, 0);
535 Actions.ActOnStartSEHFinallyBlock();
537 StmtResult Block(ParseCompoundStatement());
538 if(Block.isInvalid()) {
539 Actions.ActOnAbortSEHFinallyBlock();
543 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
548 /// seh-leave-statement:
551 StmtResult Parser::ParseSEHLeaveStatement() {
552 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
553 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
556 /// ParseLabeledStatement - We have an identifier and a ':' after it.
558 /// labeled-statement:
559 /// identifier ':' statement
560 /// [GNU] identifier ':' attributes[opt] statement
562 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
563 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
564 "Not an identifier!");
566 Token IdentTok = Tok; // Save the whole token.
567 ConsumeToken(); // eat the identifier.
569 assert(Tok.is(tok::colon) && "Not a label!");
571 // identifier ':' statement
572 SourceLocation ColonLoc = ConsumeToken();
574 // Read label attributes, if present.
576 if (Tok.is(tok::kw___attribute)) {
577 ParsedAttributesWithRange TempAttrs(AttrFactory);
578 ParseGNUAttributes(TempAttrs);
580 // In C++, GNU attributes only apply to the label if they are followed by a
581 // semicolon, to disambiguate label attributes from attributes on a labeled
584 // This doesn't quite match what GCC does; if the attribute list is empty
585 // and followed by a semicolon, GCC will reject (it appears to parse the
586 // attributes as part of a statement in that case). That looks like a bug.
587 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
588 attrs.takeAllFrom(TempAttrs);
589 else if (isDeclarationStatement()) {
591 // FIXME: We should do this whether or not we have a declaration
592 // statement, but that doesn't work correctly (because ProhibitAttributes
593 // can't handle GNU attributes), so only call it in the one case where
594 // GNU attributes are allowed.
595 SubStmt = ParseStatementOrDeclarationAfterAttributes(
596 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
598 if (!TempAttrs.empty() && !SubStmt.isInvalid())
599 SubStmt = Actions.ProcessStmtAttributes(
600 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
602 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
606 // If we've not parsed a statement yet, parse one now.
607 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
608 SubStmt = ParseStatement();
610 // Broken substmt shouldn't prevent the label from being added to the AST.
611 if (SubStmt.isInvalid())
612 SubStmt = Actions.ActOnNullStmt(ColonLoc);
614 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
615 IdentTok.getLocation());
616 if (AttributeList *Attrs = attrs.getList()) {
617 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
621 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
625 /// ParseCaseStatement
626 /// labeled-statement:
627 /// 'case' constant-expression ':' statement
628 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
630 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
631 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
633 // It is very very common for code to contain many case statements recursively
634 // nested, as in (but usually without indentation):
641 // Parsing this naively works, but is both inefficient and can cause us to run
642 // out of stack space in our recursive descent parser. As a special case,
643 // flatten this recursion into an iterative loop. This is complex and gross,
644 // but all the grossness is constrained to ParseCaseStatement (and some
645 // weirdness in the actions), so this is just local grossness :).
647 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
649 StmtResult TopLevelCase(true);
651 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
652 // gets updated each time a new case is parsed, and whose body is unset so
653 // far. When parsing 'case 4', this is the 'case 3' node.
654 Stmt *DeepestParsedCaseStmt = nullptr;
656 // While we have case statements, eat and stack them.
657 SourceLocation ColonLoc;
659 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
660 ConsumeToken(); // eat the 'case'.
661 ColonLoc = SourceLocation();
663 if (Tok.is(tok::code_completion)) {
664 Actions.CodeCompleteCase(getCurScope());
669 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
670 /// Disable this form of error recovery while we're parsing the case
672 ColonProtectionRAIIObject ColonProtection(*this);
676 LHS = ParseConstantExpression();
677 if (!getLangOpts().CPlusPlus11) {
678 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
679 return Actions.VerifyIntegerConstantExpression(E);
682 if (LHS.isInvalid()) {
683 // If constant-expression is parsed unsuccessfully, recover by skipping
684 // current case statement (moving to the colon that ends it).
685 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
686 TryConsumeToken(tok::colon, ColonLoc);
696 // GNU case range extension.
697 SourceLocation DotDotDotLoc;
699 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
700 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
701 RHS = ParseConstantExpression();
702 if (RHS.isInvalid()) {
703 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
704 TryConsumeToken(tok::colon, ColonLoc);
711 ColonProtection.restore();
713 if (TryConsumeToken(tok::colon, ColonLoc)) {
714 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
715 TryConsumeToken(tok::coloncolon, ColonLoc)) {
716 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
717 Diag(ColonLoc, diag::err_expected_after)
718 << "'case'" << tok::colon
719 << FixItHint::CreateReplacement(ColonLoc, ":");
721 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
722 Diag(ExpectedLoc, diag::err_expected_after)
723 << "'case'" << tok::colon
724 << FixItHint::CreateInsertion(ExpectedLoc, ":");
725 ColonLoc = ExpectedLoc;
729 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
730 RHS.get(), ColonLoc);
732 // If we had a sema error parsing this case, then just ignore it and
733 // continue parsing the sub-stmt.
734 if (Case.isInvalid()) {
735 if (TopLevelCase.isInvalid()) // No parsed case stmts.
736 return ParseStatement(/*TrailingElseLoc=*/nullptr,
737 /*AllowOpenMPStandalone=*/true);
738 // Otherwise, just don't add it as a nested case.
740 // If this is the first case statement we parsed, it becomes TopLevelCase.
741 // Otherwise we link it into the current chain.
742 Stmt *NextDeepest = Case.get();
743 if (TopLevelCase.isInvalid())
746 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
747 DeepestParsedCaseStmt = NextDeepest;
750 // Handle all case statements.
751 } while (Tok.is(tok::kw_case));
753 // If we found a non-case statement, start by parsing it.
756 if (Tok.isNot(tok::r_brace)) {
757 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
758 /*AllowOpenMPStandalone=*/true);
760 // Nicely diagnose the common error "switch (X) { case 4: }", which is
761 // not valid. If ColonLoc doesn't point to a valid text location, there was
762 // another parsing error, so avoid producing extra diagnostics.
763 if (ColonLoc.isValid()) {
764 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
765 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
766 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
768 SubStmt = StmtError();
771 // Install the body into the most deeply-nested case.
772 if (DeepestParsedCaseStmt) {
773 // Broken sub-stmt shouldn't prevent forming the case statement properly.
774 if (SubStmt.isInvalid())
775 SubStmt = Actions.ActOnNullStmt(SourceLocation());
776 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
779 // Return the top level parsed statement tree.
783 /// ParseDefaultStatement
784 /// labeled-statement:
785 /// 'default' ':' statement
786 /// Note that this does not parse the 'statement' at the end.
788 StmtResult Parser::ParseDefaultStatement() {
789 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
790 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
792 SourceLocation ColonLoc;
793 if (TryConsumeToken(tok::colon, ColonLoc)) {
794 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
795 // Treat "default;" as a typo for "default:".
796 Diag(ColonLoc, diag::err_expected_after)
797 << "'default'" << tok::colon
798 << FixItHint::CreateReplacement(ColonLoc, ":");
800 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
801 Diag(ExpectedLoc, diag::err_expected_after)
802 << "'default'" << tok::colon
803 << FixItHint::CreateInsertion(ExpectedLoc, ":");
804 ColonLoc = ExpectedLoc;
809 if (Tok.isNot(tok::r_brace)) {
810 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
811 /*AllowOpenMPStandalone=*/true);
813 // Diagnose the common error "switch (X) {... default: }", which is
815 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
816 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
817 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
821 // Broken sub-stmt shouldn't prevent forming the case statement properly.
822 if (SubStmt.isInvalid())
823 SubStmt = Actions.ActOnNullStmt(ColonLoc);
825 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
826 SubStmt.get(), getCurScope());
829 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
830 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
833 /// ParseCompoundStatement - Parse a "{}" block.
835 /// compound-statement: [C99 6.8.2]
836 /// { block-item-list[opt] }
837 /// [GNU] { label-declarations block-item-list } [TODO]
841 /// block-item-list block-item
845 /// [GNU] '__extension__' declaration
848 /// [GNU] label-declarations:
849 /// [GNU] label-declaration
850 /// [GNU] label-declarations label-declaration
852 /// [GNU] label-declaration:
853 /// [GNU] '__label__' identifier-list ';'
855 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
856 unsigned ScopeFlags) {
857 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
859 // Enter a scope to hold everything within the compound stmt. Compound
860 // statements can always hold declarations.
861 ParseScope CompoundScope(this, ScopeFlags);
863 // Parse the statements in the body.
864 return ParseCompoundStatementBody(isStmtExpr);
867 /// Parse any pragmas at the start of the compound expression. We handle these
868 /// separately since some pragmas (FP_CONTRACT) must appear before any C
869 /// statement in the compound, but may be intermingled with other pragmas.
870 void Parser::ParseCompoundStatementLeadingPragmas() {
871 bool checkForPragmas = true;
872 while (checkForPragmas) {
873 switch (Tok.getKind()) {
874 case tok::annot_pragma_vis:
875 HandlePragmaVisibility();
877 case tok::annot_pragma_pack:
880 case tok::annot_pragma_msstruct:
881 HandlePragmaMSStruct();
883 case tok::annot_pragma_align:
886 case tok::annot_pragma_weak:
889 case tok::annot_pragma_weakalias:
890 HandlePragmaWeakAlias();
892 case tok::annot_pragma_redefine_extname:
893 HandlePragmaRedefineExtname();
895 case tok::annot_pragma_opencl_extension:
896 HandlePragmaOpenCLExtension();
898 case tok::annot_pragma_fp_contract:
899 HandlePragmaFPContract();
901 case tok::annot_pragma_ms_pointers_to_members:
902 HandlePragmaMSPointersToMembers();
904 case tok::annot_pragma_ms_pragma:
905 HandlePragmaMSPragma();
907 case tok::annot_pragma_ms_vtordisp:
908 HandlePragmaMSVtorDisp();
910 case tok::annot_pragma_dump:
914 checkForPragmas = false;
921 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
922 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
923 /// consume the '}' at the end of the block. It does not manipulate the scope
925 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
926 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
928 "in compound statement ('{}')");
930 // Record the state of the FP_CONTRACT pragma, restore on leaving the
931 // compound statement.
932 Sema::FPContractStateRAII SaveFPContractState(Actions);
934 InMessageExpressionRAIIObject InMessage(*this, false);
935 BalancedDelimiterTracker T(*this, tok::l_brace);
939 Sema::CompoundScopeRAII CompoundScope(Actions);
941 // Parse any pragmas at the beginning of the compound statement.
942 ParseCompoundStatementLeadingPragmas();
946 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
947 // only allowed at the start of a compound stmt regardless of the language.
948 while (Tok.is(tok::kw___label__)) {
949 SourceLocation LabelLoc = ConsumeToken();
951 SmallVector<Decl *, 8> DeclsInGroup;
953 if (Tok.isNot(tok::identifier)) {
954 Diag(Tok, diag::err_expected) << tok::identifier;
958 IdentifierInfo *II = Tok.getIdentifierInfo();
959 SourceLocation IdLoc = ConsumeToken();
960 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
962 if (!TryConsumeToken(tok::comma))
966 DeclSpec DS(AttrFactory);
968 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
969 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
971 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
973 Stmts.push_back(R.get());
976 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
977 Tok.isNot(tok::eof)) {
978 if (Tok.is(tok::annot_pragma_unused)) {
979 HandlePragmaUnused();
984 if (Tok.isNot(tok::kw___extension__)) {
985 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
987 // __extension__ can start declarations and it can also be a unary
988 // operator for expressions. Consume multiple __extension__ markers here
989 // until we can determine which is which.
990 // FIXME: This loses extension expressions in the AST!
991 SourceLocation ExtLoc = ConsumeToken();
992 while (Tok.is(tok::kw___extension__))
995 ParsedAttributesWithRange attrs(AttrFactory);
996 MaybeParseCXX11Attributes(attrs, nullptr,
997 /*MightBeObjCMessageSend*/ true);
999 // If this is the start of a declaration, parse it as such.
1000 if (isDeclarationStatement()) {
1001 // __extension__ silences extension warnings in the subdeclaration.
1002 // FIXME: Save the __extension__ on the decl as a node somehow?
1003 ExtensionRAIIObject O(Diags);
1005 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1006 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
1008 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1010 // Otherwise this was a unary __extension__ marker.
1011 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1013 if (Res.isInvalid()) {
1014 SkipUntil(tok::semi);
1018 // FIXME: Use attributes?
1019 // Eat the semicolon at the end of stmt and convert the expr into a
1021 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1022 R = Actions.ActOnExprStmt(Res);
1027 Stmts.push_back(R.get());
1030 SourceLocation CloseLoc = Tok.getLocation();
1032 // We broke out of the while loop because we found a '}' or EOF.
1033 if (!T.consumeClose())
1034 // Recover by creating a compound statement with what we parsed so far,
1035 // instead of dropping everything and returning StmtError();
1036 CloseLoc = T.getCloseLocation();
1038 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1042 /// ParseParenExprOrCondition:
1043 /// [C ] '(' expression ')'
1044 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
1046 /// This function parses and performs error recovery on the specified condition
1047 /// or expression (depending on whether we're in C++ or C mode). This function
1048 /// goes out of its way to recover well. It returns true if there was a parser
1049 /// error (the right paren couldn't be found), which indicates that the caller
1050 /// should try to recover harder. It returns false if the condition is
1051 /// successfully parsed. Note that a successful parse can still have semantic
1052 /// errors in the condition.
1053 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
1056 bool ConvertToBoolean) {
1057 BalancedDelimiterTracker T(*this, tok::l_paren);
1060 if (getLangOpts().CPlusPlus)
1061 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
1063 ExprResult = ParseExpression();
1064 DeclResult = nullptr;
1066 // If required, convert to a boolean value.
1067 if (!ExprResult.isInvalid() && ConvertToBoolean)
1069 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
1072 // If the parser was confused by the condition and we don't have a ')', try to
1073 // recover by skipping ahead to a semi and bailing out. If condexp is
1074 // semantically invalid but we have well formed code, keep going.
1075 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
1076 SkipUntil(tok::semi);
1077 // Skipping may have stopped if it found the containing ')'. If so, we can
1078 // continue parsing the if statement.
1079 if (Tok.isNot(tok::r_paren))
1083 // Otherwise the condition is valid or the rparen is present.
1086 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1087 // that all callers are looking for a statement after the condition, so ")"
1089 while (Tok.is(tok::r_paren)) {
1090 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1091 << FixItHint::CreateRemoval(Tok.getLocation());
1099 /// ParseIfStatement
1100 /// if-statement: [C99 6.8.4.1]
1101 /// 'if' '(' expression ')' statement
1102 /// 'if' '(' expression ')' statement 'else' statement
1103 /// [C++] 'if' '(' condition ')' statement
1104 /// [C++] 'if' '(' condition ')' statement 'else' statement
1106 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1107 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1108 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1110 if (Tok.isNot(tok::l_paren)) {
1111 Diag(Tok, diag::err_expected_lparen_after) << "if";
1112 SkipUntil(tok::semi);
1116 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1118 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1119 // the case for C90.
1122 // A name introduced by a declaration in a condition is in scope from its
1123 // point of declaration until the end of the substatements controlled by the
1126 // Names declared in the for-init-statement, and in the condition of if,
1127 // while, for, and switch statements are local to the if, while, for, or
1128 // switch statement (including the controlled statement).
1130 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1132 // Parse the condition.
1134 Decl *CondVar = nullptr;
1135 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
1138 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
1140 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1141 // there is no compound stmt. C90 does not have this clause. We only do this
1142 // if the body isn't a compound statement to avoid push/pop in common cases.
1145 // The substatement in a selection-statement (each substatement, in the else
1146 // form of the if statement) implicitly defines a local scope.
1148 // For C++ we create a scope for the condition and a new scope for
1149 // substatements because:
1150 // -When the 'then' scope exits, we want the condition declaration to still be
1151 // active for the 'else' scope too.
1152 // -Sema will detect name clashes by considering declarations of a
1153 // 'ControlScope' as part of its direct subscope.
1154 // -If we wanted the condition and substatement to be in the same scope, we
1155 // would have to notify ParseStatement not to create a new scope. It's
1156 // simpler to let it create a new scope.
1158 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1160 // Read the 'then' stmt.
1161 SourceLocation ThenStmtLoc = Tok.getLocation();
1163 SourceLocation InnerStatementTrailingElseLoc;
1164 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
1166 // Pop the 'if' scope if needed.
1169 // If it has an else, parse it.
1170 SourceLocation ElseLoc;
1171 SourceLocation ElseStmtLoc;
1172 StmtResult ElseStmt;
1174 if (Tok.is(tok::kw_else)) {
1175 if (TrailingElseLoc)
1176 *TrailingElseLoc = Tok.getLocation();
1178 ElseLoc = ConsumeToken();
1179 ElseStmtLoc = Tok.getLocation();
1181 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1182 // there is no compound stmt. C90 does not have this clause. We only do
1183 // this if the body isn't a compound statement to avoid push/pop in common
1187 // The substatement in a selection-statement (each substatement, in the else
1188 // form of the if statement) implicitly defines a local scope.
1190 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1192 ElseStmt = ParseStatement();
1194 // Pop the 'else' scope if needed.
1196 } else if (Tok.is(tok::code_completion)) {
1197 Actions.CodeCompleteAfterIf(getCurScope());
1200 } else if (InnerStatementTrailingElseLoc.isValid()) {
1201 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1206 // If the then or else stmt is invalid and the other is valid (and present),
1207 // make turn the invalid one into a null stmt to avoid dropping the other
1208 // part. If both are invalid, return error.
1209 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1210 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1211 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1212 // Both invalid, or one is invalid and other is non-present: return error.
1216 // Now if either are invalid, replace with a ';'.
1217 if (ThenStmt.isInvalid())
1218 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1219 if (ElseStmt.isInvalid())
1220 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1222 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
1223 ElseLoc, ElseStmt.get());
1226 /// ParseSwitchStatement
1227 /// switch-statement:
1228 /// 'switch' '(' expression ')' statement
1229 /// [C++] 'switch' '(' condition ')' statement
1230 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1231 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1232 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1234 if (Tok.isNot(tok::l_paren)) {
1235 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1236 SkipUntil(tok::semi);
1240 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1242 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1243 // not the case for C90. Start the switch scope.
1246 // A name introduced by a declaration in a condition is in scope from its
1247 // point of declaration until the end of the substatements controlled by the
1250 // Names declared in the for-init-statement, and in the condition of if,
1251 // while, for, and switch statements are local to the if, while, for, or
1252 // switch statement (including the controlled statement).
1254 unsigned ScopeFlags = Scope::SwitchScope;
1256 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1257 ParseScope SwitchScope(this, ScopeFlags);
1259 // Parse the condition.
1261 Decl *CondVar = nullptr;
1262 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1266 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1268 if (Switch.isInvalid()) {
1269 // Skip the switch body.
1270 // FIXME: This is not optimal recovery, but parsing the body is more
1271 // dangerous due to the presence of case and default statements, which
1272 // will have no place to connect back with the switch.
1273 if (Tok.is(tok::l_brace)) {
1275 SkipUntil(tok::r_brace);
1277 SkipUntil(tok::semi);
1281 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1282 // there is no compound stmt. C90 does not have this clause. We only do this
1283 // if the body isn't a compound statement to avoid push/pop in common cases.
1286 // The substatement in a selection-statement (each substatement, in the else
1287 // form of the if statement) implicitly defines a local scope.
1289 // See comments in ParseIfStatement for why we create a scope for the
1290 // condition and a new scope for substatement in C++.
1292 getCurScope()->AddFlags(Scope::BreakScope);
1293 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1295 // We have incremented the mangling number for the SwitchScope and the
1296 // InnerScope, which is one too many.
1298 getCurScope()->decrementMSManglingNumber();
1300 // Read the body statement.
1301 StmtResult Body(ParseStatement(TrailingElseLoc));
1307 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1310 /// ParseWhileStatement
1311 /// while-statement: [C99 6.8.5.1]
1312 /// 'while' '(' expression ')' statement
1313 /// [C++] 'while' '(' condition ')' statement
1314 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1315 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1316 SourceLocation WhileLoc = Tok.getLocation();
1317 ConsumeToken(); // eat the 'while'.
1319 if (Tok.isNot(tok::l_paren)) {
1320 Diag(Tok, diag::err_expected_lparen_after) << "while";
1321 SkipUntil(tok::semi);
1325 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1327 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1328 // the case for C90. Start the loop scope.
1331 // A name introduced by a declaration in a condition is in scope from its
1332 // point of declaration until the end of the substatements controlled by the
1335 // Names declared in the for-init-statement, and in the condition of if,
1336 // while, for, and switch statements are local to the if, while, for, or
1337 // switch statement (including the controlled statement).
1339 unsigned ScopeFlags;
1341 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1342 Scope::DeclScope | Scope::ControlScope;
1344 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1345 ParseScope WhileScope(this, ScopeFlags);
1347 // Parse the condition.
1349 Decl *CondVar = nullptr;
1350 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1353 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
1355 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1356 // there is no compound stmt. C90 does not have this clause. We only do this
1357 // if the body isn't a compound statement to avoid push/pop in common cases.
1360 // The substatement in an iteration-statement implicitly defines a local scope
1361 // which is entered and exited each time through the loop.
1363 // See comments in ParseIfStatement for why we create a scope for the
1364 // condition and a new scope for substatement in C++.
1366 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1368 // Read the body statement.
1369 StmtResult Body(ParseStatement(TrailingElseLoc));
1371 // Pop the body scope if needed.
1375 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1378 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1381 /// ParseDoStatement
1382 /// do-statement: [C99 6.8.5.2]
1383 /// 'do' statement 'while' '(' expression ')' ';'
1384 /// Note: this lets the caller parse the end ';'.
1385 StmtResult Parser::ParseDoStatement() {
1386 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1387 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1389 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1390 // the case for C90. Start the loop scope.
1391 unsigned ScopeFlags;
1392 if (getLangOpts().C99)
1393 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1395 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1397 ParseScope DoScope(this, ScopeFlags);
1399 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1400 // there is no compound stmt. C90 does not have this clause. We only do this
1401 // if the body isn't a compound statement to avoid push/pop in common cases.
1404 // The substatement in an iteration-statement implicitly defines a local scope
1405 // which is entered and exited each time through the loop.
1407 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1408 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1410 // Read the body statement.
1411 StmtResult Body(ParseStatement());
1413 // Pop the body scope if needed.
1416 if (Tok.isNot(tok::kw_while)) {
1417 if (!Body.isInvalid()) {
1418 Diag(Tok, diag::err_expected_while);
1419 Diag(DoLoc, diag::note_matching) << "'do'";
1420 SkipUntil(tok::semi, StopBeforeMatch);
1424 SourceLocation WhileLoc = ConsumeToken();
1426 if (Tok.isNot(tok::l_paren)) {
1427 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1428 SkipUntil(tok::semi, StopBeforeMatch);
1432 // Parse the parenthesized expression.
1433 BalancedDelimiterTracker T(*this, tok::l_paren);
1436 // A do-while expression is not a condition, so can't have attributes.
1437 DiagnoseAndSkipCXX11Attributes();
1439 ExprResult Cond = ParseExpression();
1443 if (Cond.isInvalid() || Body.isInvalid())
1446 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1447 Cond.get(), T.getCloseLocation());
1450 bool Parser::isForRangeIdentifier() {
1451 assert(Tok.is(tok::identifier));
1453 const Token &Next = NextToken();
1454 if (Next.is(tok::colon))
1457 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1458 TentativeParsingAction PA(*this);
1460 SkipCXX11Attributes();
1461 bool Result = Tok.is(tok::colon);
1469 /// ParseForStatement
1470 /// for-statement: [C99 6.8.5.3]
1471 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1472 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1473 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1476 /// 'co_await'[opt] [Coroutines]
1477 /// '(' for-range-declaration ':' for-range-initializer ')'
1479 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1480 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1482 /// [C++] for-init-statement:
1483 /// [C++] expression-statement
1484 /// [C++] simple-declaration
1486 /// [C++0x] for-range-declaration:
1487 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1488 /// [C++0x] for-range-initializer:
1489 /// [C++0x] expression
1490 /// [C++0x] braced-init-list [TODO]
1491 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1492 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1493 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1495 SourceLocation CoawaitLoc;
1496 if (Tok.is(tok::kw_co_await))
1497 CoawaitLoc = ConsumeToken();
1499 if (Tok.isNot(tok::l_paren)) {
1500 Diag(Tok, diag::err_expected_lparen_after) << "for";
1501 SkipUntil(tok::semi);
1505 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1506 getLangOpts().ObjC1;
1508 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1509 // the case for C90. Start the loop scope.
1512 // A name introduced by a declaration in a condition is in scope from its
1513 // point of declaration until the end of the substatements controlled by the
1516 // Names declared in the for-init-statement, and in the condition of if,
1517 // while, for, and switch statements are local to the if, while, for, or
1518 // switch statement (including the controlled statement).
1520 // Names declared in the for-init-statement are in the same declarative-region
1521 // as those declared in the condition.
1523 unsigned ScopeFlags = 0;
1525 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1527 ParseScope ForScope(this, ScopeFlags);
1529 BalancedDelimiterTracker T(*this, tok::l_paren);
1534 bool ForEach = false, ForRange = false;
1535 StmtResult FirstPart;
1536 bool SecondPartIsInvalid = false;
1537 FullExprArg SecondPart(Actions);
1538 ExprResult Collection;
1539 ForRangeInit ForRangeInit;
1540 FullExprArg ThirdPart(Actions);
1541 Decl *SecondVar = nullptr;
1543 if (Tok.is(tok::code_completion)) {
1544 Actions.CodeCompleteOrdinaryName(getCurScope(),
1545 C99orCXXorObjC? Sema::PCC_ForInit
1546 : Sema::PCC_Expression);
1551 ParsedAttributesWithRange attrs(AttrFactory);
1552 MaybeParseCXX11Attributes(attrs);
1554 // Parse the first part of the for specifier.
1555 if (Tok.is(tok::semi)) { // for (;
1556 ProhibitAttributes(attrs);
1557 // no first part, eat the ';'.
1559 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1560 isForRangeIdentifier()) {
1561 ProhibitAttributes(attrs);
1562 IdentifierInfo *Name = Tok.getIdentifierInfo();
1563 SourceLocation Loc = ConsumeToken();
1564 MaybeParseCXX11Attributes(attrs);
1566 ForRangeInit.ColonLoc = ConsumeToken();
1567 if (Tok.is(tok::l_brace))
1568 ForRangeInit.RangeExpr = ParseBraceInitializer();
1570 ForRangeInit.RangeExpr = ParseExpression();
1572 Diag(Loc, diag::err_for_range_identifier)
1573 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1574 ? FixItHint::CreateInsertion(Loc, "auto &&")
1577 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1578 attrs, attrs.Range.getEnd());
1580 } else if (isForInitDeclaration()) { // for (int X = 4;
1581 // Parse declaration, which eats the ';'.
1582 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1583 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1585 // In C++0x, "for (T NS:a" might not be a typo for ::
1586 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1587 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1589 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1590 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1591 Declarator::ForContext, DeclEnd, attrs, false,
1592 MightBeForRangeStmt ? &ForRangeInit : nullptr);
1593 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1594 if (ForRangeInit.ParsedForRangeDecl()) {
1595 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1596 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1599 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1601 } else if ((ForEach = isTokIdentifier_in())) {
1602 Actions.ActOnForEachDeclStmt(DG);
1603 // ObjC: for (id x in expr)
1604 ConsumeToken(); // consume 'in'
1606 if (Tok.is(tok::code_completion)) {
1607 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1611 Collection = ParseExpression();
1613 Diag(Tok, diag::err_expected_semi_for);
1616 ProhibitAttributes(attrs);
1617 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1619 ForEach = isTokIdentifier_in();
1621 // Turn the expression into a stmt.
1622 if (!Value.isInvalid()) {
1624 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1626 FirstPart = Actions.ActOnExprStmt(Value);
1629 if (Tok.is(tok::semi)) {
1631 } else if (ForEach) {
1632 ConsumeToken(); // consume 'in'
1634 if (Tok.is(tok::code_completion)) {
1635 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1639 Collection = ParseExpression();
1640 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1641 // User tried to write the reasonable, but ill-formed, for-range-statement
1642 // for (expr : expr) { ... }
1643 Diag(Tok, diag::err_for_range_expected_decl)
1644 << FirstPart.get()->getSourceRange();
1645 SkipUntil(tok::r_paren, StopBeforeMatch);
1646 SecondPartIsInvalid = true;
1648 if (!Value.isInvalid()) {
1649 Diag(Tok, diag::err_expected_semi_for);
1651 // Skip until semicolon or rparen, don't consume it.
1652 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1653 if (Tok.is(tok::semi))
1659 // Parse the second part of the for specifier.
1660 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1661 if (!ForEach && !ForRange) {
1662 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1663 // Parse the second part of the for specifier.
1664 if (Tok.is(tok::semi)) { // for (...;;
1666 } else if (Tok.is(tok::r_paren)) {
1667 // missing both semicolons.
1670 if (getLangOpts().CPlusPlus)
1671 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1673 Second = ParseExpression();
1674 if (!Second.isInvalid())
1675 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1678 SecondPartIsInvalid = Second.isInvalid();
1679 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
1682 if (Tok.isNot(tok::semi)) {
1683 if (!SecondPartIsInvalid || SecondVar)
1684 Diag(Tok, diag::err_expected_semi_for);
1686 // Skip until semicolon or rparen, don't consume it.
1687 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1690 if (Tok.is(tok::semi)) {
1694 // Parse the third part of the for specifier.
1695 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1696 ExprResult Third = ParseExpression();
1697 // FIXME: The C++11 standard doesn't actually say that this is a
1698 // discarded-value expression, but it clearly should be.
1699 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1705 // C++ Coroutines [stmt.iter]:
1706 // 'co_await' can only be used for a range-based for statement.
1707 if (CoawaitLoc.isValid() && !ForRange) {
1708 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1709 CoawaitLoc = SourceLocation();
1712 // We need to perform most of the semantic analysis for a C++0x for-range
1713 // statememt before parsing the body, in order to be able to deduce the type
1714 // of an auto-typed loop variable.
1715 StmtResult ForRangeStmt;
1716 StmtResult ForEachStmt;
1719 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1720 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1721 ForRangeInit.ColonLoc, ForRangeInit.RangeExpr.get(),
1722 T.getCloseLocation(), Sema::BFRK_Build);
1724 // Similarly, we need to do the semantic analysis for a for-range
1725 // statement immediately in order to close over temporaries correctly.
1726 } else if (ForEach) {
1727 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1730 T.getCloseLocation());
1732 // In OpenMP loop region loop control variable must be captured and be
1733 // private. Perform analysis of first part (if any).
1734 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1735 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1739 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1740 // there is no compound stmt. C90 does not have this clause. We only do this
1741 // if the body isn't a compound statement to avoid push/pop in common cases.
1744 // The substatement in an iteration-statement implicitly defines a local scope
1745 // which is entered and exited each time through the loop.
1747 // See comments in ParseIfStatement for why we create a scope for
1748 // for-init-statement/condition and a new scope for substatement in C++.
1750 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1751 Tok.is(tok::l_brace));
1753 // The body of the for loop has the same local mangling number as the
1754 // for-init-statement.
1755 // It will only be incremented if the body contains other things that would
1756 // normally increment the mangling number (like a compound statement).
1758 getCurScope()->decrementMSManglingNumber();
1760 // Read the body statement.
1761 StmtResult Body(ParseStatement(TrailingElseLoc));
1763 // Pop the body scope if needed.
1766 // Leave the for-scope.
1769 if (Body.isInvalid())
1773 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1777 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1779 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1780 SecondPart, SecondVar, ThirdPart,
1781 T.getCloseLocation(), Body.get());
1784 /// ParseGotoStatement
1786 /// 'goto' identifier ';'
1787 /// [GNU] 'goto' '*' expression ';'
1789 /// Note: this lets the caller parse the end ';'.
1791 StmtResult Parser::ParseGotoStatement() {
1792 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1793 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1796 if (Tok.is(tok::identifier)) {
1797 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1799 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1801 } else if (Tok.is(tok::star)) {
1802 // GNU indirect goto extension.
1803 Diag(Tok, diag::ext_gnu_indirect_goto);
1804 SourceLocation StarLoc = ConsumeToken();
1805 ExprResult R(ParseExpression());
1806 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1807 SkipUntil(tok::semi, StopBeforeMatch);
1810 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1812 Diag(Tok, diag::err_expected) << tok::identifier;
1819 /// ParseContinueStatement
1823 /// Note: this lets the caller parse the end ';'.
1825 StmtResult Parser::ParseContinueStatement() {
1826 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1827 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1830 /// ParseBreakStatement
1834 /// Note: this lets the caller parse the end ';'.
1836 StmtResult Parser::ParseBreakStatement() {
1837 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1838 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1841 /// ParseReturnStatement
1843 /// 'return' expression[opt] ';'
1844 /// 'return' braced-init-list ';'
1845 /// 'co_return' expression[opt] ';'
1846 /// 'co_return' braced-init-list ';'
1847 StmtResult Parser::ParseReturnStatement() {
1848 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1849 "Not a return stmt!");
1850 bool IsCoreturn = Tok.is(tok::kw_co_return);
1851 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1854 if (Tok.isNot(tok::semi)) {
1855 // FIXME: Code completion for co_return.
1856 if (Tok.is(tok::code_completion) && !IsCoreturn) {
1857 Actions.CodeCompleteReturn(getCurScope());
1862 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1863 R = ParseInitializer();
1865 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1866 diag::warn_cxx98_compat_generalized_initializer_lists :
1867 diag::ext_generalized_initializer_lists)
1868 << R.get()->getSourceRange();
1870 R = ParseExpression();
1871 if (R.isInvalid()) {
1872 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1877 return Actions.ActOnCoreturnStmt(ReturnLoc, R.get());
1878 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1881 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1882 AllowedContsructsKind Allowed,
1883 SourceLocation *TrailingElseLoc,
1884 ParsedAttributesWithRange &Attrs) {
1885 // Create temporary attribute list.
1886 ParsedAttributesWithRange TempAttrs(AttrFactory);
1888 // Get loop hints and consume annotated token.
1889 while (Tok.is(tok::annot_pragma_loop_hint)) {
1891 if (!HandlePragmaLoopHint(Hint))
1894 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1895 ArgsUnion(Hint.ValueExpr)};
1896 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1897 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1898 AttributeList::AS_Pragma);
1901 // Get the next statement.
1902 MaybeParseCXX11Attributes(Attrs);
1904 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1905 Stmts, Allowed, TrailingElseLoc, Attrs);
1907 Attrs.takeAllFrom(TempAttrs);
1911 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1912 assert(Tok.is(tok::l_brace));
1913 SourceLocation LBraceLoc = Tok.getLocation();
1915 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
1916 trySkippingFunctionBody()) {
1918 return Actions.ActOnSkippedFunctionBody(Decl);
1921 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1922 "parsing function body");
1924 // Save and reset current vtordisp stack if we have entered a C++ method body.
1926 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1927 Sema::VtorDispStackRAII SavedVtorDispStack(Actions, IsCXXMethod);
1929 // Do not enter a scope for the brace, as the arguments are in the same scope
1930 // (the function body) as the body itself. Instead, just read the statement
1931 // list and put it into a CompoundStmt for safe keeping.
1932 StmtResult FnBody(ParseCompoundStatementBody());
1934 // If the function body could not be parsed, make a bogus compoundstmt.
1935 if (FnBody.isInvalid()) {
1936 Sema::CompoundScopeRAII CompoundScope(Actions);
1937 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1941 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1944 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1946 /// function-try-block:
1947 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1949 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1950 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1951 SourceLocation TryLoc = ConsumeToken();
1953 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1954 "parsing function try block");
1956 // Constructor initializer list?
1957 if (Tok.is(tok::colon))
1958 ParseConstructorInitializer(Decl);
1960 Actions.ActOnDefaultCtorInitializers(Decl);
1962 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
1963 trySkippingFunctionBody()) {
1965 return Actions.ActOnSkippedFunctionBody(Decl);
1968 // Save and reset current vtordisp stack if we have entered a C++ method body.
1970 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1971 Sema::VtorDispStackRAII SavedVtorDispStack(Actions, IsCXXMethod);
1973 SourceLocation LBraceLoc = Tok.getLocation();
1974 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
1975 // If we failed to parse the try-catch, we just give the function an empty
1976 // compound statement as the body.
1977 if (FnBody.isInvalid()) {
1978 Sema::CompoundScopeRAII CompoundScope(Actions);
1979 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1983 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1986 bool Parser::trySkippingFunctionBody() {
1987 assert(Tok.is(tok::l_brace));
1988 assert(SkipFunctionBodies &&
1989 "Should only be called when SkipFunctionBodies is enabled");
1991 if (!PP.isCodeCompletionEnabled()) {
1993 SkipUntil(tok::r_brace);
1997 // We're in code-completion mode. Skip parsing for all function bodies unless
1998 // the body contains the code-completion point.
1999 TentativeParsingAction PA(*this);
2001 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2010 /// ParseCXXTryBlock - Parse a C++ try-block.
2013 /// 'try' compound-statement handler-seq
2015 StmtResult Parser::ParseCXXTryBlock() {
2016 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2018 SourceLocation TryLoc = ConsumeToken();
2019 return ParseCXXTryBlockCommon(TryLoc);
2022 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2023 /// function-try-block.
2026 /// 'try' compound-statement handler-seq
2028 /// function-try-block:
2029 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2032 /// handler handler-seq[opt]
2034 /// [Borland] try-block:
2035 /// 'try' compound-statement seh-except-block
2036 /// 'try' compound-statement seh-finally-block
2038 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2039 if (Tok.isNot(tok::l_brace))
2040 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2042 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2043 Scope::DeclScope | Scope::TryScope |
2044 (FnTry ? Scope::FnTryCatchScope : 0)));
2045 if (TryBlock.isInvalid())
2048 // Borland allows SEH-handlers with 'try'
2050 if ((Tok.is(tok::identifier) &&
2051 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2052 Tok.is(tok::kw___finally)) {
2053 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2055 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2056 SourceLocation Loc = ConsumeToken();
2057 Handler = ParseSEHExceptBlock(Loc);
2060 SourceLocation Loc = ConsumeToken();
2061 Handler = ParseSEHFinallyBlock(Loc);
2063 if(Handler.isInvalid())
2066 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2072 StmtVector Handlers;
2074 // C++11 attributes can't appear here, despite this context seeming
2076 DiagnoseAndSkipCXX11Attributes();
2078 if (Tok.isNot(tok::kw_catch))
2079 return StmtError(Diag(Tok, diag::err_expected_catch));
2080 while (Tok.is(tok::kw_catch)) {
2081 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2082 if (!Handler.isInvalid())
2083 Handlers.push_back(Handler.get());
2085 // Don't bother creating the full statement if we don't have any usable
2087 if (Handlers.empty())
2090 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2094 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2097 /// 'catch' '(' exception-declaration ')' compound-statement
2099 /// exception-declaration:
2100 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2101 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2104 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2105 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2107 SourceLocation CatchLoc = ConsumeToken();
2109 BalancedDelimiterTracker T(*this, tok::l_paren);
2110 if (T.expectAndConsume())
2114 // The name in a catch exception-declaration is local to the handler and
2115 // shall not be redeclared in the outermost block of the handler.
2116 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2117 (FnCatch ? Scope::FnTryCatchScope : 0));
2119 // exception-declaration is equivalent to '...' or a parameter-declaration
2120 // without default arguments.
2121 Decl *ExceptionDecl = nullptr;
2122 if (Tok.isNot(tok::ellipsis)) {
2123 ParsedAttributesWithRange Attributes(AttrFactory);
2124 MaybeParseCXX11Attributes(Attributes);
2126 DeclSpec DS(AttrFactory);
2127 DS.takeAttributesFrom(Attributes);
2129 if (ParseCXXTypeSpecifierSeq(DS))
2132 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2133 ParseDeclarator(ExDecl);
2134 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2139 if (T.getCloseLocation().isInvalid())
2142 if (Tok.isNot(tok::l_brace))
2143 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2145 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2146 StmtResult Block(ParseCompoundStatement());
2147 if (Block.isInvalid())
2150 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2153 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2154 IfExistsCondition Result;
2155 if (ParseMicrosoftIfExistsCondition(Result))
2158 // Handle dependent statements by parsing the braces as a compound statement.
2159 // This is not the same behavior as Visual C++, which don't treat this as a
2160 // compound statement, but for Clang's type checking we can't have anything
2161 // inside these braces escaping to the surrounding code.
2162 if (Result.Behavior == IEB_Dependent) {
2163 if (!Tok.is(tok::l_brace)) {
2164 Diag(Tok, diag::err_expected) << tok::l_brace;
2168 StmtResult Compound = ParseCompoundStatement();
2169 if (Compound.isInvalid())
2172 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2177 if (DepResult.isUsable())
2178 Stmts.push_back(DepResult.get());
2182 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2183 if (Braces.consumeOpen()) {
2184 Diag(Tok, diag::err_expected) << tok::l_brace;
2188 switch (Result.Behavior) {
2190 // Parse the statements below.
2194 llvm_unreachable("Dependent case handled above");
2201 // Condition is true, parse the statements.
2202 while (Tok.isNot(tok::r_brace)) {
2203 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2205 Stmts.push_back(R.get());
2207 Braces.consumeClose();