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) {
38 // We may get back a null statement if we found a #pragma. Keep going until
39 // we get an actual statement.
42 Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
43 } while (!Res.isInvalid() && !Res.get());
48 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
49 /// StatementOrDeclaration:
55 /// compound-statement
56 /// expression-statement
57 /// selection-statement
58 /// iteration-statement
60 /// [C++] declaration-statement
62 /// [MS] seh-try-block
63 /// [OBC] objc-throw-statement
64 /// [OBC] objc-try-catch-statement
65 /// [OBC] objc-synchronized-statement
66 /// [GNU] asm-statement
67 /// [OMP] openmp-construct [TODO]
69 /// labeled-statement:
70 /// identifier ':' statement
71 /// 'case' constant-expression ':' statement
72 /// 'default' ':' statement
74 /// selection-statement:
78 /// iteration-statement:
83 /// expression-statement:
84 /// expression[opt] ';'
87 /// 'goto' identifier ';'
90 /// 'return' expression[opt] ';'
91 /// [GNU] 'goto' '*' expression ';'
93 /// [OBC] objc-throw-statement:
94 /// [OBC] '@' 'throw' expression ';'
95 /// [OBC] '@' 'throw' ';'
98 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
99 SourceLocation *TrailingElseLoc) {
101 ParenBraceBracketBalancer BalancerRAIIObj(*this);
103 ParsedAttributesWithRange Attrs(AttrFactory);
104 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
106 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
107 OnlyStatement, TrailingElseLoc, Attrs);
109 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
110 "attributes on empty statement");
112 if (Attrs.empty() || Res.isInvalid())
115 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
119 class StatementFilterCCC : public CorrectionCandidateCallback {
121 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
122 WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
123 tok::identifier, tok::star, tok::amp);
124 WantExpressionKeywords =
125 nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
126 WantRemainingKeywords =
127 nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
128 WantCXXNamedCasts = false;
131 bool ValidateCandidate(const TypoCorrection &candidate) override {
132 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
133 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
134 if (NextToken.is(tok::equal))
135 return candidate.getCorrectionDeclAs<VarDecl>();
136 if (NextToken.is(tok::period) &&
137 candidate.getCorrectionDeclAs<NamespaceDecl>())
139 return CorrectionCandidateCallback::ValidateCandidate(candidate);
148 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
149 bool OnlyStatement, SourceLocation *TrailingElseLoc,
150 ParsedAttributesWithRange &Attrs) {
151 const char *SemiError = nullptr;
154 // Cases in this switch statement should fall through if the parser expects
155 // the token to end in a semicolon (in which case SemiError should be set),
156 // or they directly 'return;' if not.
158 tok::TokenKind Kind = Tok.getKind();
159 SourceLocation AtLoc;
161 case tok::at: // May be a @try or @throw statement
163 ProhibitAttributes(Attrs); // TODO: is it correct?
164 AtLoc = ConsumeToken(); // consume @
165 return ParseObjCAtStatement(AtLoc);
168 case tok::code_completion:
169 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
173 case tok::identifier: {
174 Token Next = NextToken();
175 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
176 // identifier ':' statement
177 return ParseLabeledStatement(Attrs);
180 // Look up the identifier, and typo-correct it to a keyword if it's not
182 if (Next.isNot(tok::coloncolon)) {
183 // Try to limit which sets of keywords should be included in typo
184 // correction based on what the next token is.
185 if (TryAnnotateName(/*IsAddressOfOperand*/ false,
186 llvm::make_unique<StatementFilterCCC>(Next)) ==
188 // Handle errors here by skipping up to the next semicolon or '}', and
189 // eat the semicolon if that's what stopped us.
190 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
191 if (Tok.is(tok::semi))
196 // If the identifier was typo-corrected, try again.
197 if (Tok.isNot(tok::identifier))
205 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
206 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
207 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
209 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
212 if (Tok.is(tok::r_brace)) {
213 Diag(Tok, diag::err_expected_statement);
217 return ParseExprStatement();
220 case tok::kw_case: // C99 6.8.1: labeled-statement
221 return ParseCaseStatement();
222 case tok::kw_default: // C99 6.8.1: labeled-statement
223 return ParseDefaultStatement();
225 case tok::l_brace: // C99 6.8.2: compound-statement
226 return ParseCompoundStatement();
227 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
228 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
229 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
232 case tok::kw_if: // C99 6.8.4.1: if-statement
233 return ParseIfStatement(TrailingElseLoc);
234 case tok::kw_switch: // C99 6.8.4.2: switch-statement
235 return ParseSwitchStatement(TrailingElseLoc);
237 case tok::kw_while: // C99 6.8.5.1: while-statement
238 return ParseWhileStatement(TrailingElseLoc);
239 case tok::kw_do: // C99 6.8.5.2: do-statement
240 Res = ParseDoStatement();
241 SemiError = "do/while";
243 case tok::kw_for: // C99 6.8.5.3: for-statement
244 return ParseForStatement(TrailingElseLoc);
246 case tok::kw_goto: // C99 6.8.6.1: goto-statement
247 Res = ParseGotoStatement();
250 case tok::kw_continue: // C99 6.8.6.2: continue-statement
251 Res = ParseContinueStatement();
252 SemiError = "continue";
254 case tok::kw_break: // C99 6.8.6.3: break-statement
255 Res = ParseBreakStatement();
258 case tok::kw_return: // C99 6.8.6.4: return-statement
259 Res = ParseReturnStatement();
260 SemiError = "return";
264 ProhibitAttributes(Attrs);
266 Res = ParseAsmStatement(msAsm);
267 Res = Actions.ActOnFinishFullStmt(Res.get());
268 if (msAsm) return Res;
273 case tok::kw___if_exists:
274 case tok::kw___if_not_exists:
275 ProhibitAttributes(Attrs);
276 ParseMicrosoftIfExistsStatement(Stmts);
277 // An __if_exists block is like a compound statement, but it doesn't create
281 case tok::kw_try: // C++ 15: try-block
282 return ParseCXXTryBlock();
285 ProhibitAttributes(Attrs); // TODO: is it correct?
286 return ParseSEHTryBlock();
288 case tok::kw___leave:
289 Res = ParseSEHLeaveStatement();
290 SemiError = "__leave";
293 case tok::annot_pragma_vis:
294 ProhibitAttributes(Attrs);
295 HandlePragmaVisibility();
298 case tok::annot_pragma_pack:
299 ProhibitAttributes(Attrs);
303 case tok::annot_pragma_msstruct:
304 ProhibitAttributes(Attrs);
305 HandlePragmaMSStruct();
308 case tok::annot_pragma_align:
309 ProhibitAttributes(Attrs);
313 case tok::annot_pragma_weak:
314 ProhibitAttributes(Attrs);
318 case tok::annot_pragma_weakalias:
319 ProhibitAttributes(Attrs);
320 HandlePragmaWeakAlias();
323 case tok::annot_pragma_redefine_extname:
324 ProhibitAttributes(Attrs);
325 HandlePragmaRedefineExtname();
328 case tok::annot_pragma_fp_contract:
329 ProhibitAttributes(Attrs);
330 Diag(Tok, diag::err_pragma_fp_contract_scope);
334 case tok::annot_pragma_opencl_extension:
335 ProhibitAttributes(Attrs);
336 HandlePragmaOpenCLExtension();
339 case tok::annot_pragma_captured:
340 ProhibitAttributes(Attrs);
341 return HandlePragmaCaptured();
343 case tok::annot_pragma_openmp:
344 ProhibitAttributes(Attrs);
345 return ParseOpenMPDeclarativeOrExecutableDirective(!OnlyStatement);
347 case tok::annot_pragma_ms_pointers_to_members:
348 ProhibitAttributes(Attrs);
349 HandlePragmaMSPointersToMembers();
352 case tok::annot_pragma_ms_pragma:
353 ProhibitAttributes(Attrs);
354 HandlePragmaMSPragma();
357 case tok::annot_pragma_loop_hint:
358 ProhibitAttributes(Attrs);
359 return ParsePragmaLoopHint(Stmts, OnlyStatement, TrailingElseLoc, Attrs);
362 // If we reached this code, the statement must end in a semicolon.
363 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
364 // If the result was valid, then we do want to diagnose this. Use
365 // ExpectAndConsume to emit the diagnostic, even though we know it won't
367 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
368 // Skip until we see a } or ;, but don't eat it.
369 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
375 /// \brief Parse an expression statement.
376 StmtResult Parser::ParseExprStatement() {
377 // If a case keyword is missing, this is where it should be inserted.
378 Token OldToken = Tok;
380 // expression[opt] ';'
381 ExprResult Expr(ParseExpression());
382 if (Expr.isInvalid()) {
383 // If the expression is invalid, skip ahead to the next semicolon or '}'.
384 // Not doing this opens us up to the possibility of infinite loops if
385 // ParseExpression does not consume any tokens.
386 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
387 if (Tok.is(tok::semi))
389 return Actions.ActOnExprStmtError();
392 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
393 Actions.CheckCaseExpression(Expr.get())) {
394 // If a constant expression is followed by a colon inside a switch block,
395 // suggest a missing case keyword.
396 Diag(OldToken, diag::err_expected_case_before_expression)
397 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
399 // Recover parsing as a case statement.
400 return ParseCaseStatement(/*MissingCase=*/true, Expr);
403 // Otherwise, eat the semicolon.
404 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
405 return Actions.ActOnExprStmt(Expr);
408 /// ParseSEHTryBlockCommon
411 /// '__try' compound-statement seh-handler
415 /// seh-finally-block
417 StmtResult Parser::ParseSEHTryBlock() {
418 assert(Tok.is(tok::kw___try) && "Expected '__try'");
419 SourceLocation TryLoc = ConsumeToken();
421 if (Tok.isNot(tok::l_brace))
422 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
424 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
425 Scope::DeclScope | Scope::SEHTryScope));
426 if(TryBlock.isInvalid())
430 if (Tok.is(tok::identifier) &&
431 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
432 SourceLocation Loc = ConsumeToken();
433 Handler = ParseSEHExceptBlock(Loc);
434 } else if (Tok.is(tok::kw___finally)) {
435 SourceLocation Loc = ConsumeToken();
436 Handler = ParseSEHFinallyBlock(Loc);
438 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
441 if(Handler.isInvalid())
444 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
450 /// ParseSEHExceptBlock - Handle __except
452 /// seh-except-block:
453 /// '__except' '(' seh-filter-expression ')' compound-statement
455 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
456 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
457 raii2(Ident___exception_code, false),
458 raii3(Ident_GetExceptionCode, false);
460 if (ExpectAndConsume(tok::l_paren))
463 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
464 Scope::SEHExceptScope);
466 if (getLangOpts().Borland) {
467 Ident__exception_info->setIsPoisoned(false);
468 Ident___exception_info->setIsPoisoned(false);
469 Ident_GetExceptionInfo->setIsPoisoned(false);
472 ExprResult FilterExpr;
474 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
475 Scope::SEHFilterScope);
476 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
479 if (getLangOpts().Borland) {
480 Ident__exception_info->setIsPoisoned(true);
481 Ident___exception_info->setIsPoisoned(true);
482 Ident_GetExceptionInfo->setIsPoisoned(true);
485 if(FilterExpr.isInvalid())
488 if (ExpectAndConsume(tok::r_paren))
491 if (Tok.isNot(tok::l_brace))
492 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
494 StmtResult Block(ParseCompoundStatement());
496 if(Block.isInvalid())
499 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
502 /// ParseSEHFinallyBlock - Handle __finally
504 /// seh-finally-block:
505 /// '__finally' compound-statement
507 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
508 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
509 raii2(Ident___abnormal_termination, false),
510 raii3(Ident_AbnormalTermination, false);
512 if (Tok.isNot(tok::l_brace))
513 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
515 ParseScope FinallyScope(this, 0);
516 Actions.ActOnStartSEHFinallyBlock();
518 StmtResult Block(ParseCompoundStatement());
519 if(Block.isInvalid()) {
520 Actions.ActOnAbortSEHFinallyBlock();
524 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
529 /// seh-leave-statement:
532 StmtResult Parser::ParseSEHLeaveStatement() {
533 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
534 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
537 /// ParseLabeledStatement - We have an identifier and a ':' after it.
539 /// labeled-statement:
540 /// identifier ':' statement
541 /// [GNU] identifier ':' attributes[opt] statement
543 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
544 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
545 "Not an identifier!");
547 Token IdentTok = Tok; // Save the whole token.
548 ConsumeToken(); // eat the identifier.
550 assert(Tok.is(tok::colon) && "Not a label!");
552 // identifier ':' statement
553 SourceLocation ColonLoc = ConsumeToken();
555 // Read label attributes, if present.
557 if (Tok.is(tok::kw___attribute)) {
558 ParsedAttributesWithRange TempAttrs(AttrFactory);
559 ParseGNUAttributes(TempAttrs);
561 // In C++, GNU attributes only apply to the label if they are followed by a
562 // semicolon, to disambiguate label attributes from attributes on a labeled
565 // This doesn't quite match what GCC does; if the attribute list is empty
566 // and followed by a semicolon, GCC will reject (it appears to parse the
567 // attributes as part of a statement in that case). That looks like a bug.
568 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
569 attrs.takeAllFrom(TempAttrs);
570 else if (isDeclarationStatement()) {
572 // FIXME: We should do this whether or not we have a declaration
573 // statement, but that doesn't work correctly (because ProhibitAttributes
574 // can't handle GNU attributes), so only call it in the one case where
575 // GNU attributes are allowed.
576 SubStmt = ParseStatementOrDeclarationAfterAttributes(
577 Stmts, /*OnlyStmts*/ true, nullptr, TempAttrs);
578 if (!TempAttrs.empty() && !SubStmt.isInvalid())
579 SubStmt = Actions.ProcessStmtAttributes(
580 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
582 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
586 // If we've not parsed a statement yet, parse one now.
587 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
588 SubStmt = ParseStatement();
590 // Broken substmt shouldn't prevent the label from being added to the AST.
591 if (SubStmt.isInvalid())
592 SubStmt = Actions.ActOnNullStmt(ColonLoc);
594 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
595 IdentTok.getLocation());
596 if (AttributeList *Attrs = attrs.getList()) {
597 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
601 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
605 /// ParseCaseStatement
606 /// labeled-statement:
607 /// 'case' constant-expression ':' statement
608 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
610 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
611 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
613 // It is very very common for code to contain many case statements recursively
614 // nested, as in (but usually without indentation):
621 // Parsing this naively works, but is both inefficient and can cause us to run
622 // out of stack space in our recursive descent parser. As a special case,
623 // flatten this recursion into an iterative loop. This is complex and gross,
624 // but all the grossness is constrained to ParseCaseStatement (and some
625 // weirdness in the actions), so this is just local grossness :).
627 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
629 StmtResult TopLevelCase(true);
631 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
632 // gets updated each time a new case is parsed, and whose body is unset so
633 // far. When parsing 'case 4', this is the 'case 3' node.
634 Stmt *DeepestParsedCaseStmt = nullptr;
636 // While we have case statements, eat and stack them.
637 SourceLocation ColonLoc;
639 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
640 ConsumeToken(); // eat the 'case'.
641 ColonLoc = SourceLocation();
643 if (Tok.is(tok::code_completion)) {
644 Actions.CodeCompleteCase(getCurScope());
649 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
650 /// Disable this form of error recovery while we're parsing the case
652 ColonProtectionRAIIObject ColonProtection(*this);
656 LHS = ParseConstantExpression();
657 if (!getLangOpts().CPlusPlus11) {
658 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
659 return Actions.VerifyIntegerConstantExpression(E);
662 if (LHS.isInvalid()) {
663 // If constant-expression is parsed unsuccessfully, recover by skipping
664 // current case statement (moving to the colon that ends it).
665 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
666 TryConsumeToken(tok::colon, ColonLoc);
676 // GNU case range extension.
677 SourceLocation DotDotDotLoc;
679 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
680 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
681 RHS = ParseConstantExpression();
682 if (RHS.isInvalid()) {
683 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
684 TryConsumeToken(tok::colon, ColonLoc);
691 ColonProtection.restore();
693 if (TryConsumeToken(tok::colon, ColonLoc)) {
694 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
695 TryConsumeToken(tok::coloncolon, ColonLoc)) {
696 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
697 Diag(ColonLoc, diag::err_expected_after)
698 << "'case'" << tok::colon
699 << FixItHint::CreateReplacement(ColonLoc, ":");
701 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
702 Diag(ExpectedLoc, diag::err_expected_after)
703 << "'case'" << tok::colon
704 << FixItHint::CreateInsertion(ExpectedLoc, ":");
705 ColonLoc = ExpectedLoc;
709 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
710 RHS.get(), ColonLoc);
712 // If we had a sema error parsing this case, then just ignore it and
713 // continue parsing the sub-stmt.
714 if (Case.isInvalid()) {
715 if (TopLevelCase.isInvalid()) // No parsed case stmts.
716 return ParseStatement();
717 // Otherwise, just don't add it as a nested case.
719 // If this is the first case statement we parsed, it becomes TopLevelCase.
720 // Otherwise we link it into the current chain.
721 Stmt *NextDeepest = Case.get();
722 if (TopLevelCase.isInvalid())
725 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
726 DeepestParsedCaseStmt = NextDeepest;
729 // Handle all case statements.
730 } while (Tok.is(tok::kw_case));
732 // If we found a non-case statement, start by parsing it.
735 if (Tok.isNot(tok::r_brace)) {
736 SubStmt = ParseStatement();
738 // Nicely diagnose the common error "switch (X) { case 4: }", which is
739 // not valid. If ColonLoc doesn't point to a valid text location, there was
740 // another parsing error, so avoid producing extra diagnostics.
741 if (ColonLoc.isValid()) {
742 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
743 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
744 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
746 SubStmt = StmtError();
749 // Install the body into the most deeply-nested case.
750 if (DeepestParsedCaseStmt) {
751 // Broken sub-stmt shouldn't prevent forming the case statement properly.
752 if (SubStmt.isInvalid())
753 SubStmt = Actions.ActOnNullStmt(SourceLocation());
754 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
757 // Return the top level parsed statement tree.
761 /// ParseDefaultStatement
762 /// labeled-statement:
763 /// 'default' ':' statement
764 /// Note that this does not parse the 'statement' at the end.
766 StmtResult Parser::ParseDefaultStatement() {
767 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
768 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
770 SourceLocation ColonLoc;
771 if (TryConsumeToken(tok::colon, ColonLoc)) {
772 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
773 // Treat "default;" as a typo for "default:".
774 Diag(ColonLoc, diag::err_expected_after)
775 << "'default'" << tok::colon
776 << FixItHint::CreateReplacement(ColonLoc, ":");
778 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
779 Diag(ExpectedLoc, diag::err_expected_after)
780 << "'default'" << tok::colon
781 << FixItHint::CreateInsertion(ExpectedLoc, ":");
782 ColonLoc = ExpectedLoc;
787 if (Tok.isNot(tok::r_brace)) {
788 SubStmt = ParseStatement();
790 // Diagnose the common error "switch (X) {... default: }", which is
792 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
793 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
794 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
798 // Broken sub-stmt shouldn't prevent forming the case statement properly.
799 if (SubStmt.isInvalid())
800 SubStmt = Actions.ActOnNullStmt(ColonLoc);
802 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
803 SubStmt.get(), getCurScope());
806 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
807 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
810 /// ParseCompoundStatement - Parse a "{}" block.
812 /// compound-statement: [C99 6.8.2]
813 /// { block-item-list[opt] }
814 /// [GNU] { label-declarations block-item-list } [TODO]
818 /// block-item-list block-item
822 /// [GNU] '__extension__' declaration
825 /// [GNU] label-declarations:
826 /// [GNU] label-declaration
827 /// [GNU] label-declarations label-declaration
829 /// [GNU] label-declaration:
830 /// [GNU] '__label__' identifier-list ';'
832 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
833 unsigned ScopeFlags) {
834 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
836 // Enter a scope to hold everything within the compound stmt. Compound
837 // statements can always hold declarations.
838 ParseScope CompoundScope(this, ScopeFlags);
840 // Parse the statements in the body.
841 return ParseCompoundStatementBody(isStmtExpr);
844 /// Parse any pragmas at the start of the compound expression. We handle these
845 /// separately since some pragmas (FP_CONTRACT) must appear before any C
846 /// statement in the compound, but may be intermingled with other pragmas.
847 void Parser::ParseCompoundStatementLeadingPragmas() {
848 bool checkForPragmas = true;
849 while (checkForPragmas) {
850 switch (Tok.getKind()) {
851 case tok::annot_pragma_vis:
852 HandlePragmaVisibility();
854 case tok::annot_pragma_pack:
857 case tok::annot_pragma_msstruct:
858 HandlePragmaMSStruct();
860 case tok::annot_pragma_align:
863 case tok::annot_pragma_weak:
866 case tok::annot_pragma_weakalias:
867 HandlePragmaWeakAlias();
869 case tok::annot_pragma_redefine_extname:
870 HandlePragmaRedefineExtname();
872 case tok::annot_pragma_opencl_extension:
873 HandlePragmaOpenCLExtension();
875 case tok::annot_pragma_fp_contract:
876 HandlePragmaFPContract();
878 case tok::annot_pragma_ms_pointers_to_members:
879 HandlePragmaMSPointersToMembers();
881 case tok::annot_pragma_ms_pragma:
882 HandlePragmaMSPragma();
885 checkForPragmas = false;
892 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
893 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
894 /// consume the '}' at the end of the block. It does not manipulate the scope
896 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
897 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
899 "in compound statement ('{}')");
901 // Record the state of the FP_CONTRACT pragma, restore on leaving the
902 // compound statement.
903 Sema::FPContractStateRAII SaveFPContractState(Actions);
905 InMessageExpressionRAIIObject InMessage(*this, false);
906 BalancedDelimiterTracker T(*this, tok::l_brace);
910 Sema::CompoundScopeRAII CompoundScope(Actions);
912 // Parse any pragmas at the beginning of the compound statement.
913 ParseCompoundStatementLeadingPragmas();
917 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
918 // only allowed at the start of a compound stmt regardless of the language.
919 while (Tok.is(tok::kw___label__)) {
920 SourceLocation LabelLoc = ConsumeToken();
922 SmallVector<Decl *, 8> DeclsInGroup;
924 if (Tok.isNot(tok::identifier)) {
925 Diag(Tok, diag::err_expected) << tok::identifier;
929 IdentifierInfo *II = Tok.getIdentifierInfo();
930 SourceLocation IdLoc = ConsumeToken();
931 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
933 if (!TryConsumeToken(tok::comma))
937 DeclSpec DS(AttrFactory);
939 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
940 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
942 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
944 Stmts.push_back(R.get());
947 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
948 if (Tok.is(tok::annot_pragma_unused)) {
949 HandlePragmaUnused();
954 if (Tok.isNot(tok::kw___extension__)) {
955 R = ParseStatementOrDeclaration(Stmts, false);
957 // __extension__ can start declarations and it can also be a unary
958 // operator for expressions. Consume multiple __extension__ markers here
959 // until we can determine which is which.
960 // FIXME: This loses extension expressions in the AST!
961 SourceLocation ExtLoc = ConsumeToken();
962 while (Tok.is(tok::kw___extension__))
965 ParsedAttributesWithRange attrs(AttrFactory);
966 MaybeParseCXX11Attributes(attrs, nullptr,
967 /*MightBeObjCMessageSend*/ true);
969 // If this is the start of a declaration, parse it as such.
970 if (isDeclarationStatement()) {
971 // __extension__ silences extension warnings in the subdeclaration.
972 // FIXME: Save the __extension__ on the decl as a node somehow?
973 ExtensionRAIIObject O(Diags);
975 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
976 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
978 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
980 // Otherwise this was a unary __extension__ marker.
981 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
983 if (Res.isInvalid()) {
984 SkipUntil(tok::semi);
988 // FIXME: Use attributes?
989 // Eat the semicolon at the end of stmt and convert the expr into a
991 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
992 R = Actions.ActOnExprStmt(Res);
997 Stmts.push_back(R.get());
1000 SourceLocation CloseLoc = Tok.getLocation();
1002 // We broke out of the while loop because we found a '}' or EOF.
1003 if (!T.consumeClose())
1004 // Recover by creating a compound statement with what we parsed so far,
1005 // instead of dropping everything and returning StmtError();
1006 CloseLoc = T.getCloseLocation();
1008 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1012 /// ParseParenExprOrCondition:
1013 /// [C ] '(' expression ')'
1014 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
1016 /// This function parses and performs error recovery on the specified condition
1017 /// or expression (depending on whether we're in C++ or C mode). This function
1018 /// goes out of its way to recover well. It returns true if there was a parser
1019 /// error (the right paren couldn't be found), which indicates that the caller
1020 /// should try to recover harder. It returns false if the condition is
1021 /// successfully parsed. Note that a successful parse can still have semantic
1022 /// errors in the condition.
1023 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
1026 bool ConvertToBoolean) {
1027 BalancedDelimiterTracker T(*this, tok::l_paren);
1030 if (getLangOpts().CPlusPlus)
1031 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
1033 ExprResult = ParseExpression();
1034 DeclResult = nullptr;
1036 // If required, convert to a boolean value.
1037 if (!ExprResult.isInvalid() && ConvertToBoolean)
1039 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
1042 // If the parser was confused by the condition and we don't have a ')', try to
1043 // recover by skipping ahead to a semi and bailing out. If condexp is
1044 // semantically invalid but we have well formed code, keep going.
1045 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
1046 SkipUntil(tok::semi);
1047 // Skipping may have stopped if it found the containing ')'. If so, we can
1048 // continue parsing the if statement.
1049 if (Tok.isNot(tok::r_paren))
1053 // Otherwise the condition is valid or the rparen is present.
1056 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1057 // that all callers are looking for a statement after the condition, so ")"
1059 while (Tok.is(tok::r_paren)) {
1060 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1061 << FixItHint::CreateRemoval(Tok.getLocation());
1069 /// ParseIfStatement
1070 /// if-statement: [C99 6.8.4.1]
1071 /// 'if' '(' expression ')' statement
1072 /// 'if' '(' expression ')' statement 'else' statement
1073 /// [C++] 'if' '(' condition ')' statement
1074 /// [C++] 'if' '(' condition ')' statement 'else' statement
1076 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1077 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1078 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1080 if (Tok.isNot(tok::l_paren)) {
1081 Diag(Tok, diag::err_expected_lparen_after) << "if";
1082 SkipUntil(tok::semi);
1086 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1088 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1089 // the case for C90.
1092 // A name introduced by a declaration in a condition is in scope from its
1093 // point of declaration until the end of the substatements controlled by the
1096 // Names declared in the for-init-statement, and in the condition of if,
1097 // while, for, and switch statements are local to the if, while, for, or
1098 // switch statement (including the controlled statement).
1100 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1102 // Parse the condition.
1104 Decl *CondVar = nullptr;
1105 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
1108 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
1110 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1111 // there is no compound stmt. C90 does not have this clause. We only do this
1112 // if the body isn't a compound statement to avoid push/pop in common cases.
1115 // The substatement in a selection-statement (each substatement, in the else
1116 // form of the if statement) implicitly defines a local scope.
1118 // For C++ we create a scope for the condition and a new scope for
1119 // substatements because:
1120 // -When the 'then' scope exits, we want the condition declaration to still be
1121 // active for the 'else' scope too.
1122 // -Sema will detect name clashes by considering declarations of a
1123 // 'ControlScope' as part of its direct subscope.
1124 // -If we wanted the condition and substatement to be in the same scope, we
1125 // would have to notify ParseStatement not to create a new scope. It's
1126 // simpler to let it create a new scope.
1128 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1130 // Read the 'then' stmt.
1131 SourceLocation ThenStmtLoc = Tok.getLocation();
1133 SourceLocation InnerStatementTrailingElseLoc;
1134 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
1136 // Pop the 'if' scope if needed.
1139 // If it has an else, parse it.
1140 SourceLocation ElseLoc;
1141 SourceLocation ElseStmtLoc;
1142 StmtResult ElseStmt;
1144 if (Tok.is(tok::kw_else)) {
1145 if (TrailingElseLoc)
1146 *TrailingElseLoc = Tok.getLocation();
1148 ElseLoc = ConsumeToken();
1149 ElseStmtLoc = Tok.getLocation();
1151 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1152 // there is no compound stmt. C90 does not have this clause. We only do
1153 // this if the body isn't a compound statement to avoid push/pop in common
1157 // The substatement in a selection-statement (each substatement, in the else
1158 // form of the if statement) implicitly defines a local scope.
1160 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1162 ElseStmt = ParseStatement();
1164 // Pop the 'else' scope if needed.
1166 } else if (Tok.is(tok::code_completion)) {
1167 Actions.CodeCompleteAfterIf(getCurScope());
1170 } else if (InnerStatementTrailingElseLoc.isValid()) {
1171 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1176 // If the then or else stmt is invalid and the other is valid (and present),
1177 // make turn the invalid one into a null stmt to avoid dropping the other
1178 // part. If both are invalid, return error.
1179 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1180 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1181 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1182 // Both invalid, or one is invalid and other is non-present: return error.
1186 // Now if either are invalid, replace with a ';'.
1187 if (ThenStmt.isInvalid())
1188 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1189 if (ElseStmt.isInvalid())
1190 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1192 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
1193 ElseLoc, ElseStmt.get());
1196 /// ParseSwitchStatement
1197 /// switch-statement:
1198 /// 'switch' '(' expression ')' statement
1199 /// [C++] 'switch' '(' condition ')' statement
1200 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1201 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1202 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1204 if (Tok.isNot(tok::l_paren)) {
1205 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1206 SkipUntil(tok::semi);
1210 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1212 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1213 // not the case for C90. Start the switch scope.
1216 // A name introduced by a declaration in a condition is in scope from its
1217 // point of declaration until the end of the substatements controlled by the
1220 // Names declared in the for-init-statement, and in the condition of if,
1221 // while, for, and switch statements are local to the if, while, for, or
1222 // switch statement (including the controlled statement).
1224 unsigned ScopeFlags = Scope::SwitchScope;
1226 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1227 ParseScope SwitchScope(this, ScopeFlags);
1229 // Parse the condition.
1231 Decl *CondVar = nullptr;
1232 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1236 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1238 if (Switch.isInvalid()) {
1239 // Skip the switch body.
1240 // FIXME: This is not optimal recovery, but parsing the body is more
1241 // dangerous due to the presence of case and default statements, which
1242 // will have no place to connect back with the switch.
1243 if (Tok.is(tok::l_brace)) {
1245 SkipUntil(tok::r_brace);
1247 SkipUntil(tok::semi);
1251 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1252 // there is no compound stmt. C90 does not have this clause. We only do this
1253 // if the body isn't a compound statement to avoid push/pop in common cases.
1256 // The substatement in a selection-statement (each substatement, in the else
1257 // form of the if statement) implicitly defines a local scope.
1259 // See comments in ParseIfStatement for why we create a scope for the
1260 // condition and a new scope for substatement in C++.
1262 getCurScope()->AddFlags(Scope::BreakScope);
1263 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1265 // We have incremented the mangling number for the SwitchScope and the
1266 // InnerScope, which is one too many.
1268 getCurScope()->decrementMSManglingNumber();
1270 // Read the body statement.
1271 StmtResult Body(ParseStatement(TrailingElseLoc));
1277 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1280 /// ParseWhileStatement
1281 /// while-statement: [C99 6.8.5.1]
1282 /// 'while' '(' expression ')' statement
1283 /// [C++] 'while' '(' condition ')' statement
1284 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1285 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1286 SourceLocation WhileLoc = Tok.getLocation();
1287 ConsumeToken(); // eat the 'while'.
1289 if (Tok.isNot(tok::l_paren)) {
1290 Diag(Tok, diag::err_expected_lparen_after) << "while";
1291 SkipUntil(tok::semi);
1295 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1297 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1298 // the case for C90. Start the loop scope.
1301 // A name introduced by a declaration in a condition is in scope from its
1302 // point of declaration until the end of the substatements controlled by the
1305 // Names declared in the for-init-statement, and in the condition of if,
1306 // while, for, and switch statements are local to the if, while, for, or
1307 // switch statement (including the controlled statement).
1309 unsigned ScopeFlags;
1311 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1312 Scope::DeclScope | Scope::ControlScope;
1314 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1315 ParseScope WhileScope(this, ScopeFlags);
1317 // Parse the condition.
1319 Decl *CondVar = nullptr;
1320 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1323 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
1325 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1326 // there is no compound stmt. C90 does not have this clause. We only do this
1327 // if the body isn't a compound statement to avoid push/pop in common cases.
1330 // The substatement in an iteration-statement implicitly defines a local scope
1331 // which is entered and exited each time through the loop.
1333 // See comments in ParseIfStatement for why we create a scope for the
1334 // condition and a new scope for substatement in C++.
1336 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1338 // Read the body statement.
1339 StmtResult Body(ParseStatement(TrailingElseLoc));
1341 // Pop the body scope if needed.
1345 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1348 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1351 /// ParseDoStatement
1352 /// do-statement: [C99 6.8.5.2]
1353 /// 'do' statement 'while' '(' expression ')' ';'
1354 /// Note: this lets the caller parse the end ';'.
1355 StmtResult Parser::ParseDoStatement() {
1356 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1357 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1359 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1360 // the case for C90. Start the loop scope.
1361 unsigned ScopeFlags;
1362 if (getLangOpts().C99)
1363 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1365 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1367 ParseScope DoScope(this, ScopeFlags);
1369 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1370 // there is no compound stmt. C90 does not have this clause. We only do this
1371 // if the body isn't a compound statement to avoid push/pop in common cases.
1374 // The substatement in an iteration-statement implicitly defines a local scope
1375 // which is entered and exited each time through the loop.
1377 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1378 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1380 // Read the body statement.
1381 StmtResult Body(ParseStatement());
1383 // Pop the body scope if needed.
1386 if (Tok.isNot(tok::kw_while)) {
1387 if (!Body.isInvalid()) {
1388 Diag(Tok, diag::err_expected_while);
1389 Diag(DoLoc, diag::note_matching) << "'do'";
1390 SkipUntil(tok::semi, StopBeforeMatch);
1394 SourceLocation WhileLoc = ConsumeToken();
1396 if (Tok.isNot(tok::l_paren)) {
1397 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1398 SkipUntil(tok::semi, StopBeforeMatch);
1402 // Parse the parenthesized expression.
1403 BalancedDelimiterTracker T(*this, tok::l_paren);
1406 // A do-while expression is not a condition, so can't have attributes.
1407 DiagnoseAndSkipCXX11Attributes();
1409 ExprResult Cond = ParseExpression();
1413 if (Cond.isInvalid() || Body.isInvalid())
1416 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1417 Cond.get(), T.getCloseLocation());
1420 bool Parser::isForRangeIdentifier() {
1421 assert(Tok.is(tok::identifier));
1423 const Token &Next = NextToken();
1424 if (Next.is(tok::colon))
1427 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1428 TentativeParsingAction PA(*this);
1430 SkipCXX11Attributes();
1431 bool Result = Tok.is(tok::colon);
1439 /// ParseForStatement
1440 /// for-statement: [C99 6.8.5.3]
1441 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1442 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1443 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1445 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
1446 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1447 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1449 /// [C++] for-init-statement:
1450 /// [C++] expression-statement
1451 /// [C++] simple-declaration
1453 /// [C++0x] for-range-declaration:
1454 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1455 /// [C++0x] for-range-initializer:
1456 /// [C++0x] expression
1457 /// [C++0x] braced-init-list [TODO]
1458 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1459 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1460 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1462 if (Tok.isNot(tok::l_paren)) {
1463 Diag(Tok, diag::err_expected_lparen_after) << "for";
1464 SkipUntil(tok::semi);
1468 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1469 getLangOpts().ObjC1;
1471 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1472 // the case for C90. Start the loop scope.
1475 // A name introduced by a declaration in a condition is in scope from its
1476 // point of declaration until the end of the substatements controlled by the
1479 // Names declared in the for-init-statement, and in the condition of if,
1480 // while, for, and switch statements are local to the if, while, for, or
1481 // switch statement (including the controlled statement).
1483 // Names declared in the for-init-statement are in the same declarative-region
1484 // as those declared in the condition.
1486 unsigned ScopeFlags = 0;
1488 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1490 ParseScope ForScope(this, ScopeFlags);
1492 BalancedDelimiterTracker T(*this, tok::l_paren);
1497 bool ForEach = false, ForRange = false;
1498 StmtResult FirstPart;
1499 bool SecondPartIsInvalid = false;
1500 FullExprArg SecondPart(Actions);
1501 ExprResult Collection;
1502 ForRangeInit ForRangeInit;
1503 FullExprArg ThirdPart(Actions);
1504 Decl *SecondVar = nullptr;
1506 if (Tok.is(tok::code_completion)) {
1507 Actions.CodeCompleteOrdinaryName(getCurScope(),
1508 C99orCXXorObjC? Sema::PCC_ForInit
1509 : Sema::PCC_Expression);
1514 ParsedAttributesWithRange attrs(AttrFactory);
1515 MaybeParseCXX11Attributes(attrs);
1517 // Parse the first part of the for specifier.
1518 if (Tok.is(tok::semi)) { // for (;
1519 ProhibitAttributes(attrs);
1520 // no first part, eat the ';'.
1522 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1523 isForRangeIdentifier()) {
1524 ProhibitAttributes(attrs);
1525 IdentifierInfo *Name = Tok.getIdentifierInfo();
1526 SourceLocation Loc = ConsumeToken();
1527 MaybeParseCXX11Attributes(attrs);
1529 ForRangeInit.ColonLoc = ConsumeToken();
1530 if (Tok.is(tok::l_brace))
1531 ForRangeInit.RangeExpr = ParseBraceInitializer();
1533 ForRangeInit.RangeExpr = ParseExpression();
1535 Diag(Loc, diag::err_for_range_identifier)
1536 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1537 ? FixItHint::CreateInsertion(Loc, "auto &&")
1540 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1541 attrs, attrs.Range.getEnd());
1543 } else if (isForInitDeclaration()) { // for (int X = 4;
1544 // Parse declaration, which eats the ';'.
1545 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1546 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1548 // In C++0x, "for (T NS:a" might not be a typo for ::
1549 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1550 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1552 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1553 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1554 Declarator::ForContext, DeclEnd, attrs, false,
1555 MightBeForRangeStmt ? &ForRangeInit : nullptr);
1556 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1557 if (ForRangeInit.ParsedForRangeDecl()) {
1558 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1559 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1562 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1564 } else if ((ForEach = isTokIdentifier_in())) {
1565 Actions.ActOnForEachDeclStmt(DG);
1566 // ObjC: for (id x in expr)
1567 ConsumeToken(); // consume 'in'
1569 if (Tok.is(tok::code_completion)) {
1570 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1574 Collection = ParseExpression();
1576 Diag(Tok, diag::err_expected_semi_for);
1579 ProhibitAttributes(attrs);
1580 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1582 ForEach = isTokIdentifier_in();
1584 // Turn the expression into a stmt.
1585 if (!Value.isInvalid()) {
1587 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1589 FirstPart = Actions.ActOnExprStmt(Value);
1592 if (Tok.is(tok::semi)) {
1594 } else if (ForEach) {
1595 ConsumeToken(); // consume 'in'
1597 if (Tok.is(tok::code_completion)) {
1598 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1602 Collection = ParseExpression();
1603 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1604 // User tried to write the reasonable, but ill-formed, for-range-statement
1605 // for (expr : expr) { ... }
1606 Diag(Tok, diag::err_for_range_expected_decl)
1607 << FirstPart.get()->getSourceRange();
1608 SkipUntil(tok::r_paren, StopBeforeMatch);
1609 SecondPartIsInvalid = true;
1611 if (!Value.isInvalid()) {
1612 Diag(Tok, diag::err_expected_semi_for);
1614 // Skip until semicolon or rparen, don't consume it.
1615 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1616 if (Tok.is(tok::semi))
1622 // Parse the second part of the for specifier.
1623 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1624 if (!ForEach && !ForRange) {
1625 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1626 // Parse the second part of the for specifier.
1627 if (Tok.is(tok::semi)) { // for (...;;
1629 } else if (Tok.is(tok::r_paren)) {
1630 // missing both semicolons.
1633 if (getLangOpts().CPlusPlus)
1634 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1636 Second = ParseExpression();
1637 if (!Second.isInvalid())
1638 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1641 SecondPartIsInvalid = Second.isInvalid();
1642 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
1645 if (Tok.isNot(tok::semi)) {
1646 if (!SecondPartIsInvalid || SecondVar)
1647 Diag(Tok, diag::err_expected_semi_for);
1649 // Skip until semicolon or rparen, don't consume it.
1650 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1653 if (Tok.is(tok::semi)) {
1657 // Parse the third part of the for specifier.
1658 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1659 ExprResult Third = ParseExpression();
1660 // FIXME: The C++11 standard doesn't actually say that this is a
1661 // discarded-value expression, but it clearly should be.
1662 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1668 // We need to perform most of the semantic analysis for a C++0x for-range
1669 // statememt before parsing the body, in order to be able to deduce the type
1670 // of an auto-typed loop variable.
1671 StmtResult ForRangeStmt;
1672 StmtResult ForEachStmt;
1675 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.get(),
1676 ForRangeInit.ColonLoc,
1677 ForRangeInit.RangeExpr.get(),
1678 T.getCloseLocation(),
1682 // Similarly, we need to do the semantic analysis for a for-range
1683 // statement immediately in order to close over temporaries correctly.
1684 } else if (ForEach) {
1685 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1688 T.getCloseLocation());
1690 // In OpenMP loop region loop control variable must be captured and be
1691 // private. Perform analysis of first part (if any).
1692 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1693 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1697 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1698 // there is no compound stmt. C90 does not have this clause. We only do this
1699 // if the body isn't a compound statement to avoid push/pop in common cases.
1702 // The substatement in an iteration-statement implicitly defines a local scope
1703 // which is entered and exited each time through the loop.
1705 // See comments in ParseIfStatement for why we create a scope for
1706 // for-init-statement/condition and a new scope for substatement in C++.
1708 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1709 Tok.is(tok::l_brace));
1711 // The body of the for loop has the same local mangling number as the
1712 // for-init-statement.
1713 // It will only be incremented if the body contains other things that would
1714 // normally increment the mangling number (like a compound statement).
1716 getCurScope()->decrementMSManglingNumber();
1718 // Read the body statement.
1719 StmtResult Body(ParseStatement(TrailingElseLoc));
1721 // Pop the body scope if needed.
1724 // Leave the for-scope.
1727 if (Body.isInvalid())
1731 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1735 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1737 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1738 SecondPart, SecondVar, ThirdPart,
1739 T.getCloseLocation(), Body.get());
1742 /// ParseGotoStatement
1744 /// 'goto' identifier ';'
1745 /// [GNU] 'goto' '*' expression ';'
1747 /// Note: this lets the caller parse the end ';'.
1749 StmtResult Parser::ParseGotoStatement() {
1750 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1751 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1754 if (Tok.is(tok::identifier)) {
1755 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1757 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1759 } else if (Tok.is(tok::star)) {
1760 // GNU indirect goto extension.
1761 Diag(Tok, diag::ext_gnu_indirect_goto);
1762 SourceLocation StarLoc = ConsumeToken();
1763 ExprResult R(ParseExpression());
1764 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1765 SkipUntil(tok::semi, StopBeforeMatch);
1768 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1770 Diag(Tok, diag::err_expected) << tok::identifier;
1777 /// ParseContinueStatement
1781 /// Note: this lets the caller parse the end ';'.
1783 StmtResult Parser::ParseContinueStatement() {
1784 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1785 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1788 /// ParseBreakStatement
1792 /// Note: this lets the caller parse the end ';'.
1794 StmtResult Parser::ParseBreakStatement() {
1795 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1796 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1799 /// ParseReturnStatement
1801 /// 'return' expression[opt] ';'
1802 StmtResult Parser::ParseReturnStatement() {
1803 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1804 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1807 if (Tok.isNot(tok::semi)) {
1808 if (Tok.is(tok::code_completion)) {
1809 Actions.CodeCompleteReturn(getCurScope());
1814 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1815 R = ParseInitializer();
1817 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1818 diag::warn_cxx98_compat_generalized_initializer_lists :
1819 diag::ext_generalized_initializer_lists)
1820 << R.get()->getSourceRange();
1822 R = ParseExpression();
1823 if (R.isInvalid()) {
1824 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1828 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1831 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts, bool OnlyStatement,
1832 SourceLocation *TrailingElseLoc,
1833 ParsedAttributesWithRange &Attrs) {
1834 // Create temporary attribute list.
1835 ParsedAttributesWithRange TempAttrs(AttrFactory);
1837 // Get loop hints and consume annotated token.
1838 while (Tok.is(tok::annot_pragma_loop_hint)) {
1840 if (!HandlePragmaLoopHint(Hint))
1843 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1844 ArgsUnion(Hint.ValueExpr)};
1845 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1846 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1847 AttributeList::AS_Pragma);
1850 // Get the next statement.
1851 MaybeParseCXX11Attributes(Attrs);
1853 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1854 Stmts, OnlyStatement, TrailingElseLoc, Attrs);
1856 Attrs.takeAllFrom(TempAttrs);
1860 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1861 assert(Tok.is(tok::l_brace));
1862 SourceLocation LBraceLoc = Tok.getLocation();
1864 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
1865 trySkippingFunctionBody()) {
1867 return Actions.ActOnSkippedFunctionBody(Decl);
1870 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1871 "parsing function body");
1873 // Do not enter a scope for the brace, as the arguments are in the same scope
1874 // (the function body) as the body itself. Instead, just read the statement
1875 // list and put it into a CompoundStmt for safe keeping.
1876 StmtResult FnBody(ParseCompoundStatementBody());
1878 // If the function body could not be parsed, make a bogus compoundstmt.
1879 if (FnBody.isInvalid()) {
1880 Sema::CompoundScopeRAII CompoundScope(Actions);
1881 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1885 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1888 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1890 /// function-try-block:
1891 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1893 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1894 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1895 SourceLocation TryLoc = ConsumeToken();
1897 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1898 "parsing function try block");
1900 // Constructor initializer list?
1901 if (Tok.is(tok::colon))
1902 ParseConstructorInitializer(Decl);
1904 Actions.ActOnDefaultCtorInitializers(Decl);
1906 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
1907 trySkippingFunctionBody()) {
1909 return Actions.ActOnSkippedFunctionBody(Decl);
1912 SourceLocation LBraceLoc = Tok.getLocation();
1913 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
1914 // If we failed to parse the try-catch, we just give the function an empty
1915 // compound statement as the body.
1916 if (FnBody.isInvalid()) {
1917 Sema::CompoundScopeRAII CompoundScope(Actions);
1918 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1922 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1925 bool Parser::trySkippingFunctionBody() {
1926 assert(Tok.is(tok::l_brace));
1927 assert(SkipFunctionBodies &&
1928 "Should only be called when SkipFunctionBodies is enabled");
1930 if (!PP.isCodeCompletionEnabled()) {
1932 SkipUntil(tok::r_brace);
1936 // We're in code-completion mode. Skip parsing for all function bodies unless
1937 // the body contains the code-completion point.
1938 TentativeParsingAction PA(*this);
1940 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
1949 /// ParseCXXTryBlock - Parse a C++ try-block.
1952 /// 'try' compound-statement handler-seq
1954 StmtResult Parser::ParseCXXTryBlock() {
1955 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1957 SourceLocation TryLoc = ConsumeToken();
1958 return ParseCXXTryBlockCommon(TryLoc);
1961 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1962 /// function-try-block.
1965 /// 'try' compound-statement handler-seq
1967 /// function-try-block:
1968 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1971 /// handler handler-seq[opt]
1973 /// [Borland] try-block:
1974 /// 'try' compound-statement seh-except-block
1975 /// 'try' compound-statement seh-finally-block
1977 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
1978 if (Tok.isNot(tok::l_brace))
1979 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
1981 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
1982 Scope::DeclScope | Scope::TryScope |
1983 (FnTry ? Scope::FnTryCatchScope : 0)));
1984 if (TryBlock.isInvalid())
1987 // Borland allows SEH-handlers with 'try'
1989 if ((Tok.is(tok::identifier) &&
1990 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
1991 Tok.is(tok::kw___finally)) {
1992 // TODO: Factor into common return ParseSEHHandlerCommon(...)
1994 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
1995 SourceLocation Loc = ConsumeToken();
1996 Handler = ParseSEHExceptBlock(Loc);
1999 SourceLocation Loc = ConsumeToken();
2000 Handler = ParseSEHFinallyBlock(Loc);
2002 if(Handler.isInvalid())
2005 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2011 StmtVector Handlers;
2013 // C++11 attributes can't appear here, despite this context seeming
2015 DiagnoseAndSkipCXX11Attributes();
2017 if (Tok.isNot(tok::kw_catch))
2018 return StmtError(Diag(Tok, diag::err_expected_catch));
2019 while (Tok.is(tok::kw_catch)) {
2020 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2021 if (!Handler.isInvalid())
2022 Handlers.push_back(Handler.get());
2024 // Don't bother creating the full statement if we don't have any usable
2026 if (Handlers.empty())
2029 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2033 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2036 /// 'catch' '(' exception-declaration ')' compound-statement
2038 /// exception-declaration:
2039 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2040 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2043 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2044 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2046 SourceLocation CatchLoc = ConsumeToken();
2048 BalancedDelimiterTracker T(*this, tok::l_paren);
2049 if (T.expectAndConsume())
2053 // The name in a catch exception-declaration is local to the handler and
2054 // shall not be redeclared in the outermost block of the handler.
2055 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2056 (FnCatch ? Scope::FnTryCatchScope : 0));
2058 // exception-declaration is equivalent to '...' or a parameter-declaration
2059 // without default arguments.
2060 Decl *ExceptionDecl = nullptr;
2061 if (Tok.isNot(tok::ellipsis)) {
2062 ParsedAttributesWithRange Attributes(AttrFactory);
2063 MaybeParseCXX11Attributes(Attributes);
2065 DeclSpec DS(AttrFactory);
2066 DS.takeAttributesFrom(Attributes);
2068 if (ParseCXXTypeSpecifierSeq(DS))
2071 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2072 ParseDeclarator(ExDecl);
2073 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2078 if (T.getCloseLocation().isInvalid())
2081 if (Tok.isNot(tok::l_brace))
2082 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2084 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2085 StmtResult Block(ParseCompoundStatement());
2086 if (Block.isInvalid())
2089 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2092 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2093 IfExistsCondition Result;
2094 if (ParseMicrosoftIfExistsCondition(Result))
2097 // Handle dependent statements by parsing the braces as a compound statement.
2098 // This is not the same behavior as Visual C++, which don't treat this as a
2099 // compound statement, but for Clang's type checking we can't have anything
2100 // inside these braces escaping to the surrounding code.
2101 if (Result.Behavior == IEB_Dependent) {
2102 if (!Tok.is(tok::l_brace)) {
2103 Diag(Tok, diag::err_expected) << tok::l_brace;
2107 StmtResult Compound = ParseCompoundStatement();
2108 if (Compound.isInvalid())
2111 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2116 if (DepResult.isUsable())
2117 Stmts.push_back(DepResult.get());
2121 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2122 if (Braces.consumeOpen()) {
2123 Diag(Tok, diag::err_expected) << tok::l_brace;
2127 switch (Result.Behavior) {
2129 // Parse the statements below.
2133 llvm_unreachable("Dependent case handled above");
2140 // Condition is true, parse the statements.
2141 while (Tok.isNot(tok::r_brace)) {
2142 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2144 Stmts.push_back(R.get());
2146 Braces.consumeClose();