1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Statement and Block portions of the Parser
13 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/Attributes.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Parse/Parser.h"
18 #include "clang/Parse/RAIIObjectsForParser.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/LoopHint.h"
21 #include "clang/Sema/PrettyDeclStackTrace.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/TypoCorrection.h"
24 using namespace clang;
26 //===----------------------------------------------------------------------===//
27 // C99 6.8: Statements and Blocks.
28 //===----------------------------------------------------------------------===//
30 /// \brief Parse a standalone statement (for instance, as the body of an 'if',
31 /// 'while', or 'for').
32 StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
33 bool AllowOpenMPStandalone) {
36 // We may get back a null statement if we found a #pragma. Keep going until
37 // we get an actual statement.
40 Res = ParseStatementOrDeclaration(
41 Stmts, AllowOpenMPStandalone ? ACK_StatementsOpenMPAnyExecutable
42 : ACK_StatementsOpenMPNonStandalone,
44 } while (!Res.isInvalid() && !Res.get());
49 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
50 /// StatementOrDeclaration:
56 /// compound-statement
57 /// expression-statement
58 /// selection-statement
59 /// iteration-statement
61 /// [C++] declaration-statement
63 /// [MS] seh-try-block
64 /// [OBC] objc-throw-statement
65 /// [OBC] objc-try-catch-statement
66 /// [OBC] objc-synchronized-statement
67 /// [GNU] asm-statement
68 /// [OMP] openmp-construct [TODO]
70 /// labeled-statement:
71 /// identifier ':' statement
72 /// 'case' constant-expression ':' statement
73 /// 'default' ':' statement
75 /// selection-statement:
79 /// iteration-statement:
84 /// expression-statement:
85 /// expression[opt] ';'
88 /// 'goto' identifier ';'
91 /// 'return' expression[opt] ';'
92 /// [GNU] 'goto' '*' expression ';'
94 /// [OBC] objc-throw-statement:
95 /// [OBC] '@' 'throw' expression ';'
96 /// [OBC] '@' 'throw' ';'
99 Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
100 AllowedConstructsKind Allowed,
101 SourceLocation *TrailingElseLoc) {
103 ParenBraceBracketBalancer BalancerRAIIObj(*this);
105 ParsedAttributesWithRange Attrs(AttrFactory);
106 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
107 if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
110 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
111 Stmts, Allowed, TrailingElseLoc, Attrs);
113 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
114 "attributes on empty statement");
116 if (Attrs.empty() || Res.isInvalid())
119 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
123 class StatementFilterCCC : public CorrectionCandidateCallback {
125 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
126 WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
127 tok::identifier, tok::star, tok::amp);
128 WantExpressionKeywords =
129 nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
130 WantRemainingKeywords =
131 nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
132 WantCXXNamedCasts = false;
135 bool ValidateCandidate(const TypoCorrection &candidate) override {
136 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
137 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
138 if (NextToken.is(tok::equal))
139 return candidate.getCorrectionDeclAs<VarDecl>();
140 if (NextToken.is(tok::period) &&
141 candidate.getCorrectionDeclAs<NamespaceDecl>())
143 return CorrectionCandidateCallback::ValidateCandidate(candidate);
152 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
153 AllowedConstructsKind Allowed, SourceLocation *TrailingElseLoc,
154 ParsedAttributesWithRange &Attrs) {
155 const char *SemiError = nullptr;
158 // Cases in this switch statement should fall through if the parser expects
159 // the token to end in a semicolon (in which case SemiError should be set),
160 // or they directly 'return;' if not.
162 tok::TokenKind Kind = Tok.getKind();
163 SourceLocation AtLoc;
165 case tok::at: // May be a @try or @throw statement
167 ProhibitAttributes(Attrs); // TODO: is it correct?
168 AtLoc = ConsumeToken(); // consume @
169 return ParseObjCAtStatement(AtLoc);
172 case tok::code_completion:
173 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
177 case tok::identifier: {
178 Token Next = NextToken();
179 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
180 // identifier ':' statement
181 return ParseLabeledStatement(Attrs);
184 // Look up the identifier, and typo-correct it to a keyword if it's not
186 if (Next.isNot(tok::coloncolon)) {
187 // Try to limit which sets of keywords should be included in typo
188 // correction based on what the next token is.
189 if (TryAnnotateName(/*IsAddressOfOperand*/ false,
190 llvm::make_unique<StatementFilterCCC>(Next)) ==
192 // Handle errors here by skipping up to the next semicolon or '}', and
193 // eat the semicolon if that's what stopped us.
194 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
195 if (Tok.is(tok::semi))
200 // If the identifier was typo-corrected, try again.
201 if (Tok.isNot(tok::identifier))
210 if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
211 Allowed == ACK_Any) &&
212 isDeclarationStatement()) {
213 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
214 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext,
216 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
219 if (Tok.is(tok::r_brace)) {
220 Diag(Tok, diag::err_expected_statement);
224 return ParseExprStatement();
227 case tok::kw_case: // C99 6.8.1: labeled-statement
228 return ParseCaseStatement();
229 case tok::kw_default: // C99 6.8.1: labeled-statement
230 return ParseDefaultStatement();
232 case tok::l_brace: // C99 6.8.2: compound-statement
233 return ParseCompoundStatement();
234 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
235 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
236 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
239 case tok::kw_if: // C99 6.8.4.1: if-statement
240 return ParseIfStatement(TrailingElseLoc);
241 case tok::kw_switch: // C99 6.8.4.2: switch-statement
242 return ParseSwitchStatement(TrailingElseLoc);
244 case tok::kw_while: // C99 6.8.5.1: while-statement
245 return ParseWhileStatement(TrailingElseLoc);
246 case tok::kw_do: // C99 6.8.5.2: do-statement
247 Res = ParseDoStatement();
248 SemiError = "do/while";
250 case tok::kw_for: // C99 6.8.5.3: for-statement
251 return ParseForStatement(TrailingElseLoc);
253 case tok::kw_goto: // C99 6.8.6.1: goto-statement
254 Res = ParseGotoStatement();
257 case tok::kw_continue: // C99 6.8.6.2: continue-statement
258 Res = ParseContinueStatement();
259 SemiError = "continue";
261 case tok::kw_break: // C99 6.8.6.3: break-statement
262 Res = ParseBreakStatement();
265 case tok::kw_return: // C99 6.8.6.4: return-statement
266 Res = ParseReturnStatement();
267 SemiError = "return";
269 case tok::kw_co_return: // C++ Coroutines: co_return statement
270 Res = ParseReturnStatement();
271 SemiError = "co_return";
275 ProhibitAttributes(Attrs);
277 Res = ParseAsmStatement(msAsm);
278 Res = Actions.ActOnFinishFullStmt(Res.get());
279 if (msAsm) return Res;
284 case tok::kw___if_exists:
285 case tok::kw___if_not_exists:
286 ProhibitAttributes(Attrs);
287 ParseMicrosoftIfExistsStatement(Stmts);
288 // An __if_exists block is like a compound statement, but it doesn't create
292 case tok::kw_try: // C++ 15: try-block
293 return ParseCXXTryBlock();
296 ProhibitAttributes(Attrs); // TODO: is it correct?
297 return ParseSEHTryBlock();
299 case tok::kw___leave:
300 Res = ParseSEHLeaveStatement();
301 SemiError = "__leave";
304 case tok::annot_pragma_vis:
305 ProhibitAttributes(Attrs);
306 HandlePragmaVisibility();
309 case tok::annot_pragma_pack:
310 ProhibitAttributes(Attrs);
314 case tok::annot_pragma_msstruct:
315 ProhibitAttributes(Attrs);
316 HandlePragmaMSStruct();
319 case tok::annot_pragma_align:
320 ProhibitAttributes(Attrs);
324 case tok::annot_pragma_weak:
325 ProhibitAttributes(Attrs);
329 case tok::annot_pragma_weakalias:
330 ProhibitAttributes(Attrs);
331 HandlePragmaWeakAlias();
334 case tok::annot_pragma_redefine_extname:
335 ProhibitAttributes(Attrs);
336 HandlePragmaRedefineExtname();
339 case tok::annot_pragma_fp_contract:
340 ProhibitAttributes(Attrs);
341 Diag(Tok, diag::err_pragma_fp_contract_scope);
342 ConsumeAnnotationToken();
345 case tok::annot_pragma_fp:
346 ProhibitAttributes(Attrs);
347 Diag(Tok, diag::err_pragma_fp_scope);
348 ConsumeAnnotationToken();
351 case tok::annot_pragma_opencl_extension:
352 ProhibitAttributes(Attrs);
353 HandlePragmaOpenCLExtension();
356 case tok::annot_pragma_captured:
357 ProhibitAttributes(Attrs);
358 return HandlePragmaCaptured();
360 case tok::annot_pragma_openmp:
361 ProhibitAttributes(Attrs);
362 return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
364 case tok::annot_pragma_ms_pointers_to_members:
365 ProhibitAttributes(Attrs);
366 HandlePragmaMSPointersToMembers();
369 case tok::annot_pragma_ms_pragma:
370 ProhibitAttributes(Attrs);
371 HandlePragmaMSPragma();
374 case tok::annot_pragma_ms_vtordisp:
375 ProhibitAttributes(Attrs);
376 HandlePragmaMSVtorDisp();
379 case tok::annot_pragma_loop_hint:
380 ProhibitAttributes(Attrs);
381 return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
383 case tok::annot_pragma_dump:
387 case tok::annot_pragma_attribute:
388 HandlePragmaAttribute();
392 // If we reached this code, the statement must end in a semicolon.
393 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
394 // If the result was valid, then we do want to diagnose this. Use
395 // ExpectAndConsume to emit the diagnostic, even though we know it won't
397 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
398 // Skip until we see a } or ;, but don't eat it.
399 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
405 /// \brief Parse an expression statement.
406 StmtResult Parser::ParseExprStatement() {
407 // If a case keyword is missing, this is where it should be inserted.
408 Token OldToken = Tok;
410 ExprStatementTokLoc = Tok.getLocation();
412 // expression[opt] ';'
413 ExprResult Expr(ParseExpression());
414 if (Expr.isInvalid()) {
415 // If the expression is invalid, skip ahead to the next semicolon or '}'.
416 // Not doing this opens us up to the possibility of infinite loops if
417 // ParseExpression does not consume any tokens.
418 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
419 if (Tok.is(tok::semi))
421 return Actions.ActOnExprStmtError();
424 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
425 Actions.CheckCaseExpression(Expr.get())) {
426 // If a constant expression is followed by a colon inside a switch block,
427 // suggest a missing case keyword.
428 Diag(OldToken, diag::err_expected_case_before_expression)
429 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
431 // Recover parsing as a case statement.
432 return ParseCaseStatement(/*MissingCase=*/true, Expr);
435 // Otherwise, eat the semicolon.
436 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
437 return Actions.ActOnExprStmt(Expr);
440 /// ParseSEHTryBlockCommon
443 /// '__try' compound-statement seh-handler
447 /// seh-finally-block
449 StmtResult Parser::ParseSEHTryBlock() {
450 assert(Tok.is(tok::kw___try) && "Expected '__try'");
451 SourceLocation TryLoc = ConsumeToken();
453 if (Tok.isNot(tok::l_brace))
454 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
456 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
457 Scope::DeclScope | Scope::SEHTryScope));
458 if(TryBlock.isInvalid())
462 if (Tok.is(tok::identifier) &&
463 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
464 SourceLocation Loc = ConsumeToken();
465 Handler = ParseSEHExceptBlock(Loc);
466 } else if (Tok.is(tok::kw___finally)) {
467 SourceLocation Loc = ConsumeToken();
468 Handler = ParseSEHFinallyBlock(Loc);
470 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
473 if(Handler.isInvalid())
476 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
482 /// ParseSEHExceptBlock - Handle __except
484 /// seh-except-block:
485 /// '__except' '(' seh-filter-expression ')' compound-statement
487 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
488 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
489 raii2(Ident___exception_code, false),
490 raii3(Ident_GetExceptionCode, false);
492 if (ExpectAndConsume(tok::l_paren))
495 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
496 Scope::SEHExceptScope);
498 if (getLangOpts().Borland) {
499 Ident__exception_info->setIsPoisoned(false);
500 Ident___exception_info->setIsPoisoned(false);
501 Ident_GetExceptionInfo->setIsPoisoned(false);
504 ExprResult FilterExpr;
506 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
507 Scope::SEHFilterScope);
508 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
511 if (getLangOpts().Borland) {
512 Ident__exception_info->setIsPoisoned(true);
513 Ident___exception_info->setIsPoisoned(true);
514 Ident_GetExceptionInfo->setIsPoisoned(true);
517 if(FilterExpr.isInvalid())
520 if (ExpectAndConsume(tok::r_paren))
523 if (Tok.isNot(tok::l_brace))
524 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
526 StmtResult Block(ParseCompoundStatement());
528 if(Block.isInvalid())
531 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
534 /// ParseSEHFinallyBlock - Handle __finally
536 /// seh-finally-block:
537 /// '__finally' compound-statement
539 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
540 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
541 raii2(Ident___abnormal_termination, false),
542 raii3(Ident_AbnormalTermination, false);
544 if (Tok.isNot(tok::l_brace))
545 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
547 ParseScope FinallyScope(this, 0);
548 Actions.ActOnStartSEHFinallyBlock();
550 StmtResult Block(ParseCompoundStatement());
551 if(Block.isInvalid()) {
552 Actions.ActOnAbortSEHFinallyBlock();
556 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
561 /// seh-leave-statement:
564 StmtResult Parser::ParseSEHLeaveStatement() {
565 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
566 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
569 /// ParseLabeledStatement - We have an identifier and a ':' after it.
571 /// labeled-statement:
572 /// identifier ':' statement
573 /// [GNU] identifier ':' attributes[opt] statement
575 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
576 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
577 "Not an identifier!");
579 Token IdentTok = Tok; // Save the whole token.
580 ConsumeToken(); // eat the identifier.
582 assert(Tok.is(tok::colon) && "Not a label!");
584 // identifier ':' statement
585 SourceLocation ColonLoc = ConsumeToken();
587 // Read label attributes, if present.
589 if (Tok.is(tok::kw___attribute)) {
590 ParsedAttributesWithRange TempAttrs(AttrFactory);
591 ParseGNUAttributes(TempAttrs);
593 // In C++, GNU attributes only apply to the label if they are followed by a
594 // semicolon, to disambiguate label attributes from attributes on a labeled
597 // This doesn't quite match what GCC does; if the attribute list is empty
598 // and followed by a semicolon, GCC will reject (it appears to parse the
599 // attributes as part of a statement in that case). That looks like a bug.
600 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
601 attrs.takeAllFrom(TempAttrs);
602 else if (isDeclarationStatement()) {
604 // FIXME: We should do this whether or not we have a declaration
605 // statement, but that doesn't work correctly (because ProhibitAttributes
606 // can't handle GNU attributes), so only call it in the one case where
607 // GNU attributes are allowed.
608 SubStmt = ParseStatementOrDeclarationAfterAttributes(
609 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
611 if (!TempAttrs.empty() && !SubStmt.isInvalid())
612 SubStmt = Actions.ProcessStmtAttributes(
613 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
615 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
619 // If we've not parsed a statement yet, parse one now.
620 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
621 SubStmt = ParseStatement();
623 // Broken substmt shouldn't prevent the label from being added to the AST.
624 if (SubStmt.isInvalid())
625 SubStmt = Actions.ActOnNullStmt(ColonLoc);
627 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
628 IdentTok.getLocation());
629 if (AttributeList *Attrs = attrs.getList()) {
630 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
634 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
638 /// ParseCaseStatement
639 /// labeled-statement:
640 /// 'case' constant-expression ':' statement
641 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
643 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
644 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
646 // It is very very common for code to contain many case statements recursively
647 // nested, as in (but usually without indentation):
654 // Parsing this naively works, but is both inefficient and can cause us to run
655 // out of stack space in our recursive descent parser. As a special case,
656 // flatten this recursion into an iterative loop. This is complex and gross,
657 // but all the grossness is constrained to ParseCaseStatement (and some
658 // weirdness in the actions), so this is just local grossness :).
660 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
662 StmtResult TopLevelCase(true);
664 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
665 // gets updated each time a new case is parsed, and whose body is unset so
666 // far. When parsing 'case 4', this is the 'case 3' node.
667 Stmt *DeepestParsedCaseStmt = nullptr;
669 // While we have case statements, eat and stack them.
670 SourceLocation ColonLoc;
672 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
673 ConsumeToken(); // eat the 'case'.
674 ColonLoc = SourceLocation();
676 if (Tok.is(tok::code_completion)) {
677 Actions.CodeCompleteCase(getCurScope());
682 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
683 /// Disable this form of error recovery while we're parsing the case
685 ColonProtectionRAIIObject ColonProtection(*this);
689 LHS = ParseConstantExpression();
690 if (!getLangOpts().CPlusPlus11) {
691 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
692 return Actions.VerifyIntegerConstantExpression(E);
695 if (LHS.isInvalid()) {
696 // If constant-expression is parsed unsuccessfully, recover by skipping
697 // current case statement (moving to the colon that ends it).
698 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
699 TryConsumeToken(tok::colon, ColonLoc);
709 // GNU case range extension.
710 SourceLocation DotDotDotLoc;
712 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
713 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
714 RHS = ParseConstantExpression();
715 if (RHS.isInvalid()) {
716 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
717 TryConsumeToken(tok::colon, ColonLoc);
724 ColonProtection.restore();
726 if (TryConsumeToken(tok::colon, ColonLoc)) {
727 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
728 TryConsumeToken(tok::coloncolon, ColonLoc)) {
729 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
730 Diag(ColonLoc, diag::err_expected_after)
731 << "'case'" << tok::colon
732 << FixItHint::CreateReplacement(ColonLoc, ":");
734 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
735 Diag(ExpectedLoc, diag::err_expected_after)
736 << "'case'" << tok::colon
737 << FixItHint::CreateInsertion(ExpectedLoc, ":");
738 ColonLoc = ExpectedLoc;
742 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
743 RHS.get(), ColonLoc);
745 // If we had a sema error parsing this case, then just ignore it and
746 // continue parsing the sub-stmt.
747 if (Case.isInvalid()) {
748 if (TopLevelCase.isInvalid()) // No parsed case stmts.
749 return ParseStatement(/*TrailingElseLoc=*/nullptr,
750 /*AllowOpenMPStandalone=*/true);
751 // Otherwise, just don't add it as a nested case.
753 // If this is the first case statement we parsed, it becomes TopLevelCase.
754 // Otherwise we link it into the current chain.
755 Stmt *NextDeepest = Case.get();
756 if (TopLevelCase.isInvalid())
759 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
760 DeepestParsedCaseStmt = NextDeepest;
763 // Handle all case statements.
764 } while (Tok.is(tok::kw_case));
766 // If we found a non-case statement, start by parsing it.
769 if (Tok.isNot(tok::r_brace)) {
770 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
771 /*AllowOpenMPStandalone=*/true);
773 // Nicely diagnose the common error "switch (X) { case 4: }", which is
774 // not valid. If ColonLoc doesn't point to a valid text location, there was
775 // another parsing error, so avoid producing extra diagnostics.
776 if (ColonLoc.isValid()) {
777 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
778 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
779 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
781 SubStmt = StmtError();
784 // Install the body into the most deeply-nested case.
785 if (DeepestParsedCaseStmt) {
786 // Broken sub-stmt shouldn't prevent forming the case statement properly.
787 if (SubStmt.isInvalid())
788 SubStmt = Actions.ActOnNullStmt(SourceLocation());
789 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
792 // Return the top level parsed statement tree.
796 /// ParseDefaultStatement
797 /// labeled-statement:
798 /// 'default' ':' statement
799 /// Note that this does not parse the 'statement' at the end.
801 StmtResult Parser::ParseDefaultStatement() {
802 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
803 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
805 SourceLocation ColonLoc;
806 if (TryConsumeToken(tok::colon, ColonLoc)) {
807 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
808 // Treat "default;" as a typo for "default:".
809 Diag(ColonLoc, diag::err_expected_after)
810 << "'default'" << tok::colon
811 << FixItHint::CreateReplacement(ColonLoc, ":");
813 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
814 Diag(ExpectedLoc, diag::err_expected_after)
815 << "'default'" << tok::colon
816 << FixItHint::CreateInsertion(ExpectedLoc, ":");
817 ColonLoc = ExpectedLoc;
822 if (Tok.isNot(tok::r_brace)) {
823 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
824 /*AllowOpenMPStandalone=*/true);
826 // Diagnose the common error "switch (X) {... default: }", which is
828 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
829 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
830 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
834 // Broken sub-stmt shouldn't prevent forming the case statement properly.
835 if (SubStmt.isInvalid())
836 SubStmt = Actions.ActOnNullStmt(ColonLoc);
838 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
839 SubStmt.get(), getCurScope());
842 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
843 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
846 /// ParseCompoundStatement - Parse a "{}" block.
848 /// compound-statement: [C99 6.8.2]
849 /// { block-item-list[opt] }
850 /// [GNU] { label-declarations block-item-list } [TODO]
854 /// block-item-list block-item
858 /// [GNU] '__extension__' declaration
861 /// [GNU] label-declarations:
862 /// [GNU] label-declaration
863 /// [GNU] label-declarations label-declaration
865 /// [GNU] label-declaration:
866 /// [GNU] '__label__' identifier-list ';'
868 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
869 unsigned ScopeFlags) {
870 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
872 // Enter a scope to hold everything within the compound stmt. Compound
873 // statements can always hold declarations.
874 ParseScope CompoundScope(this, ScopeFlags);
876 // Parse the statements in the body.
877 return ParseCompoundStatementBody(isStmtExpr);
880 /// Parse any pragmas at the start of the compound expression. We handle these
881 /// separately since some pragmas (FP_CONTRACT) must appear before any C
882 /// statement in the compound, but may be intermingled with other pragmas.
883 void Parser::ParseCompoundStatementLeadingPragmas() {
884 bool checkForPragmas = true;
885 while (checkForPragmas) {
886 switch (Tok.getKind()) {
887 case tok::annot_pragma_vis:
888 HandlePragmaVisibility();
890 case tok::annot_pragma_pack:
893 case tok::annot_pragma_msstruct:
894 HandlePragmaMSStruct();
896 case tok::annot_pragma_align:
899 case tok::annot_pragma_weak:
902 case tok::annot_pragma_weakalias:
903 HandlePragmaWeakAlias();
905 case tok::annot_pragma_redefine_extname:
906 HandlePragmaRedefineExtname();
908 case tok::annot_pragma_opencl_extension:
909 HandlePragmaOpenCLExtension();
911 case tok::annot_pragma_fp_contract:
912 HandlePragmaFPContract();
914 case tok::annot_pragma_fp:
917 case tok::annot_pragma_ms_pointers_to_members:
918 HandlePragmaMSPointersToMembers();
920 case tok::annot_pragma_ms_pragma:
921 HandlePragmaMSPragma();
923 case tok::annot_pragma_ms_vtordisp:
924 HandlePragmaMSVtorDisp();
926 case tok::annot_pragma_dump:
930 checkForPragmas = false;
937 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
938 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
939 /// consume the '}' at the end of the block. It does not manipulate the scope
941 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
942 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
944 "in compound statement ('{}')");
946 // Record the state of the FP_CONTRACT pragma, restore on leaving the
947 // compound statement.
948 Sema::FPContractStateRAII SaveFPContractState(Actions);
950 InMessageExpressionRAIIObject InMessage(*this, false);
951 BalancedDelimiterTracker T(*this, tok::l_brace);
955 Sema::CompoundScopeRAII CompoundScope(Actions);
957 // Parse any pragmas at the beginning of the compound statement.
958 ParseCompoundStatementLeadingPragmas();
962 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
963 // only allowed at the start of a compound stmt regardless of the language.
964 while (Tok.is(tok::kw___label__)) {
965 SourceLocation LabelLoc = ConsumeToken();
967 SmallVector<Decl *, 8> DeclsInGroup;
969 if (Tok.isNot(tok::identifier)) {
970 Diag(Tok, diag::err_expected) << tok::identifier;
974 IdentifierInfo *II = Tok.getIdentifierInfo();
975 SourceLocation IdLoc = ConsumeToken();
976 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
978 if (!TryConsumeToken(tok::comma))
982 DeclSpec DS(AttrFactory);
984 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
985 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
987 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
989 Stmts.push_back(R.get());
992 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
993 Tok.isNot(tok::eof)) {
994 if (Tok.is(tok::annot_pragma_unused)) {
995 HandlePragmaUnused();
1000 if (Tok.isNot(tok::kw___extension__)) {
1001 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
1003 // __extension__ can start declarations and it can also be a unary
1004 // operator for expressions. Consume multiple __extension__ markers here
1005 // until we can determine which is which.
1006 // FIXME: This loses extension expressions in the AST!
1007 SourceLocation ExtLoc = ConsumeToken();
1008 while (Tok.is(tok::kw___extension__))
1011 ParsedAttributesWithRange attrs(AttrFactory);
1012 MaybeParseCXX11Attributes(attrs, nullptr,
1013 /*MightBeObjCMessageSend*/ true);
1015 // If this is the start of a declaration, parse it as such.
1016 if (isDeclarationStatement()) {
1017 // __extension__ silences extension warnings in the subdeclaration.
1018 // FIXME: Save the __extension__ on the decl as a node somehow?
1019 ExtensionRAIIObject O(Diags);
1021 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1022 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
1024 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1026 // Otherwise this was a unary __extension__ marker.
1027 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1029 if (Res.isInvalid()) {
1030 SkipUntil(tok::semi);
1034 // FIXME: Use attributes?
1035 // Eat the semicolon at the end of stmt and convert the expr into a
1037 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1038 R = Actions.ActOnExprStmt(Res);
1043 Stmts.push_back(R.get());
1046 SourceLocation CloseLoc = Tok.getLocation();
1048 // We broke out of the while loop because we found a '}' or EOF.
1049 if (!T.consumeClose())
1050 // Recover by creating a compound statement with what we parsed so far,
1051 // instead of dropping everything and returning StmtError();
1052 CloseLoc = T.getCloseLocation();
1054 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1058 /// ParseParenExprOrCondition:
1059 /// [C ] '(' expression ')'
1060 /// [C++] '(' condition ')'
1061 /// [C++1z] '(' init-statement[opt] condition ')'
1063 /// This function parses and performs error recovery on the specified condition
1064 /// or expression (depending on whether we're in C++ or C mode). This function
1065 /// goes out of its way to recover well. It returns true if there was a parser
1066 /// error (the right paren couldn't be found), which indicates that the caller
1067 /// should try to recover harder. It returns false if the condition is
1068 /// successfully parsed. Note that a successful parse can still have semantic
1069 /// errors in the condition.
1070 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1071 Sema::ConditionResult &Cond,
1073 Sema::ConditionKind CK) {
1074 BalancedDelimiterTracker T(*this, tok::l_paren);
1077 if (getLangOpts().CPlusPlus)
1078 Cond = ParseCXXCondition(InitStmt, Loc, CK);
1080 ExprResult CondExpr = ParseExpression();
1082 // If required, convert to a boolean value.
1083 if (CondExpr.isInvalid())
1084 Cond = Sema::ConditionError();
1086 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1089 // If the parser was confused by the condition and we don't have a ')', try to
1090 // recover by skipping ahead to a semi and bailing out. If condexp is
1091 // semantically invalid but we have well formed code, keep going.
1092 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1093 SkipUntil(tok::semi);
1094 // Skipping may have stopped if it found the containing ')'. If so, we can
1095 // continue parsing the if statement.
1096 if (Tok.isNot(tok::r_paren))
1100 // Otherwise the condition is valid or the rparen is present.
1103 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1104 // that all callers are looking for a statement after the condition, so ")"
1106 while (Tok.is(tok::r_paren)) {
1107 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1108 << FixItHint::CreateRemoval(Tok.getLocation());
1116 /// ParseIfStatement
1117 /// if-statement: [C99 6.8.4.1]
1118 /// 'if' '(' expression ')' statement
1119 /// 'if' '(' expression ')' statement 'else' statement
1120 /// [C++] 'if' '(' condition ')' statement
1121 /// [C++] 'if' '(' condition ')' statement 'else' statement
1123 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1124 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1125 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1127 bool IsConstexpr = false;
1128 if (Tok.is(tok::kw_constexpr)) {
1129 Diag(Tok, getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_constexpr_if
1130 : diag::ext_constexpr_if);
1135 if (Tok.isNot(tok::l_paren)) {
1136 Diag(Tok, diag::err_expected_lparen_after) << "if";
1137 SkipUntil(tok::semi);
1141 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1143 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1144 // the case for C90.
1147 // A name introduced by a declaration in a condition is in scope from its
1148 // point of declaration until the end of the substatements controlled by the
1151 // Names declared in the for-init-statement, and in the condition of if,
1152 // while, for, and switch statements are local to the if, while, for, or
1153 // switch statement (including the controlled statement).
1155 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1157 // Parse the condition.
1158 StmtResult InitStmt;
1159 Sema::ConditionResult Cond;
1160 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1161 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1162 : Sema::ConditionKind::Boolean))
1165 llvm::Optional<bool> ConstexprCondition;
1167 ConstexprCondition = Cond.getKnownValue();
1169 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1170 // there is no compound stmt. C90 does not have this clause. We only do this
1171 // if the body isn't a compound statement to avoid push/pop in common cases.
1174 // The substatement in a selection-statement (each substatement, in the else
1175 // form of the if statement) implicitly defines a local scope.
1177 // For C++ we create a scope for the condition and a new scope for
1178 // substatements because:
1179 // -When the 'then' scope exits, we want the condition declaration to still be
1180 // active for the 'else' scope too.
1181 // -Sema will detect name clashes by considering declarations of a
1182 // 'ControlScope' as part of its direct subscope.
1183 // -If we wanted the condition and substatement to be in the same scope, we
1184 // would have to notify ParseStatement not to create a new scope. It's
1185 // simpler to let it create a new scope.
1187 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1189 // Read the 'then' stmt.
1190 SourceLocation ThenStmtLoc = Tok.getLocation();
1192 SourceLocation InnerStatementTrailingElseLoc;
1193 StmtResult ThenStmt;
1195 EnterExpressionEvaluationContext PotentiallyDiscarded(
1196 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1198 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1199 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1202 // Pop the 'if' scope if needed.
1205 // If it has an else, parse it.
1206 SourceLocation ElseLoc;
1207 SourceLocation ElseStmtLoc;
1208 StmtResult ElseStmt;
1210 if (Tok.is(tok::kw_else)) {
1211 if (TrailingElseLoc)
1212 *TrailingElseLoc = Tok.getLocation();
1214 ElseLoc = ConsumeToken();
1215 ElseStmtLoc = Tok.getLocation();
1217 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1218 // there is no compound stmt. C90 does not have this clause. We only do
1219 // this if the body isn't a compound statement to avoid push/pop in common
1223 // The substatement in a selection-statement (each substatement, in the else
1224 // form of the if statement) implicitly defines a local scope.
1226 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1227 Tok.is(tok::l_brace));
1229 EnterExpressionEvaluationContext PotentiallyDiscarded(
1230 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1232 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1233 ElseStmt = ParseStatement();
1235 // Pop the 'else' scope if needed.
1237 } else if (Tok.is(tok::code_completion)) {
1238 Actions.CodeCompleteAfterIf(getCurScope());
1241 } else if (InnerStatementTrailingElseLoc.isValid()) {
1242 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1247 // If the then or else stmt is invalid and the other is valid (and present),
1248 // make turn the invalid one into a null stmt to avoid dropping the other
1249 // part. If both are invalid, return error.
1250 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1251 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1252 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1253 // Both invalid, or one is invalid and other is non-present: return error.
1257 // Now if either are invalid, replace with a ';'.
1258 if (ThenStmt.isInvalid())
1259 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1260 if (ElseStmt.isInvalid())
1261 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1263 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1264 ThenStmt.get(), ElseLoc, ElseStmt.get());
1267 /// ParseSwitchStatement
1268 /// switch-statement:
1269 /// 'switch' '(' expression ')' statement
1270 /// [C++] 'switch' '(' condition ')' statement
1271 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1272 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1273 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1275 if (Tok.isNot(tok::l_paren)) {
1276 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1277 SkipUntil(tok::semi);
1281 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1283 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1284 // not the case for C90. Start the switch scope.
1287 // A name introduced by a declaration in a condition is in scope from its
1288 // point of declaration until the end of the substatements controlled by the
1291 // Names declared in the for-init-statement, and in the condition of if,
1292 // while, for, and switch statements are local to the if, while, for, or
1293 // switch statement (including the controlled statement).
1295 unsigned ScopeFlags = Scope::SwitchScope;
1297 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1298 ParseScope SwitchScope(this, ScopeFlags);
1300 // Parse the condition.
1301 StmtResult InitStmt;
1302 Sema::ConditionResult Cond;
1303 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1304 Sema::ConditionKind::Switch))
1308 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1310 if (Switch.isInvalid()) {
1311 // Skip the switch body.
1312 // FIXME: This is not optimal recovery, but parsing the body is more
1313 // dangerous due to the presence of case and default statements, which
1314 // will have no place to connect back with the switch.
1315 if (Tok.is(tok::l_brace)) {
1317 SkipUntil(tok::r_brace);
1319 SkipUntil(tok::semi);
1323 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1324 // there is no compound stmt. C90 does not have this clause. We only do this
1325 // if the body isn't a compound statement to avoid push/pop in common cases.
1328 // The substatement in a selection-statement (each substatement, in the else
1329 // form of the if statement) implicitly defines a local scope.
1331 // See comments in ParseIfStatement for why we create a scope for the
1332 // condition and a new scope for substatement in C++.
1334 getCurScope()->AddFlags(Scope::BreakScope);
1335 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1337 // We have incremented the mangling number for the SwitchScope and the
1338 // InnerScope, which is one too many.
1340 getCurScope()->decrementMSManglingNumber();
1342 // Read the body statement.
1343 StmtResult Body(ParseStatement(TrailingElseLoc));
1349 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1352 /// ParseWhileStatement
1353 /// while-statement: [C99 6.8.5.1]
1354 /// 'while' '(' expression ')' statement
1355 /// [C++] 'while' '(' condition ')' statement
1356 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1357 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1358 SourceLocation WhileLoc = Tok.getLocation();
1359 ConsumeToken(); // eat the 'while'.
1361 if (Tok.isNot(tok::l_paren)) {
1362 Diag(Tok, diag::err_expected_lparen_after) << "while";
1363 SkipUntil(tok::semi);
1367 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1369 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1370 // the case for C90. Start the loop scope.
1373 // A name introduced by a declaration in a condition is in scope from its
1374 // point of declaration until the end of the substatements controlled by the
1377 // Names declared in the for-init-statement, and in the condition of if,
1378 // while, for, and switch statements are local to the if, while, for, or
1379 // switch statement (including the controlled statement).
1381 unsigned ScopeFlags;
1383 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1384 Scope::DeclScope | Scope::ControlScope;
1386 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1387 ParseScope WhileScope(this, ScopeFlags);
1389 // Parse the condition.
1390 Sema::ConditionResult Cond;
1391 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1392 Sema::ConditionKind::Boolean))
1395 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1396 // there is no compound stmt. C90 does not have this clause. We only do this
1397 // if the body isn't a compound statement to avoid push/pop in common cases.
1400 // The substatement in an iteration-statement implicitly defines a local scope
1401 // which is entered and exited each time through the loop.
1403 // See comments in ParseIfStatement for why we create a scope for the
1404 // condition and a new scope for substatement in C++.
1406 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1408 // Read the body statement.
1409 StmtResult Body(ParseStatement(TrailingElseLoc));
1411 // Pop the body scope if needed.
1415 if (Cond.isInvalid() || Body.isInvalid())
1418 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1421 /// ParseDoStatement
1422 /// do-statement: [C99 6.8.5.2]
1423 /// 'do' statement 'while' '(' expression ')' ';'
1424 /// Note: this lets the caller parse the end ';'.
1425 StmtResult Parser::ParseDoStatement() {
1426 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1427 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1429 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1430 // the case for C90. Start the loop scope.
1431 unsigned ScopeFlags;
1432 if (getLangOpts().C99)
1433 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1435 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1437 ParseScope DoScope(this, ScopeFlags);
1439 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1440 // there is no compound stmt. C90 does not have this clause. We only do this
1441 // if the body isn't a compound statement to avoid push/pop in common cases.
1444 // The substatement in an iteration-statement implicitly defines a local scope
1445 // which is entered and exited each time through the loop.
1447 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1448 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1450 // Read the body statement.
1451 StmtResult Body(ParseStatement());
1453 // Pop the body scope if needed.
1456 if (Tok.isNot(tok::kw_while)) {
1457 if (!Body.isInvalid()) {
1458 Diag(Tok, diag::err_expected_while);
1459 Diag(DoLoc, diag::note_matching) << "'do'";
1460 SkipUntil(tok::semi, StopBeforeMatch);
1464 SourceLocation WhileLoc = ConsumeToken();
1466 if (Tok.isNot(tok::l_paren)) {
1467 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1468 SkipUntil(tok::semi, StopBeforeMatch);
1472 // Parse the parenthesized expression.
1473 BalancedDelimiterTracker T(*this, tok::l_paren);
1476 // A do-while expression is not a condition, so can't have attributes.
1477 DiagnoseAndSkipCXX11Attributes();
1479 ExprResult Cond = ParseExpression();
1483 if (Cond.isInvalid() || Body.isInvalid())
1486 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1487 Cond.get(), T.getCloseLocation());
1490 bool Parser::isForRangeIdentifier() {
1491 assert(Tok.is(tok::identifier));
1493 const Token &Next = NextToken();
1494 if (Next.is(tok::colon))
1497 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1498 TentativeParsingAction PA(*this);
1500 SkipCXX11Attributes();
1501 bool Result = Tok.is(tok::colon);
1509 /// ParseForStatement
1510 /// for-statement: [C99 6.8.5.3]
1511 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1512 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1513 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1516 /// 'co_await'[opt] [Coroutines]
1517 /// '(' for-range-declaration ':' for-range-initializer ')'
1519 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1520 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1522 /// [C++] for-init-statement:
1523 /// [C++] expression-statement
1524 /// [C++] simple-declaration
1526 /// [C++0x] for-range-declaration:
1527 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1528 /// [C++0x] for-range-initializer:
1529 /// [C++0x] expression
1530 /// [C++0x] braced-init-list [TODO]
1531 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1532 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1533 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1535 SourceLocation CoawaitLoc;
1536 if (Tok.is(tok::kw_co_await))
1537 CoawaitLoc = ConsumeToken();
1539 if (Tok.isNot(tok::l_paren)) {
1540 Diag(Tok, diag::err_expected_lparen_after) << "for";
1541 SkipUntil(tok::semi);
1545 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1546 getLangOpts().ObjC1;
1548 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1549 // the case for C90. Start the loop scope.
1552 // A name introduced by a declaration in a condition is in scope from its
1553 // point of declaration until the end of the substatements controlled by the
1556 // Names declared in the for-init-statement, and in the condition of if,
1557 // while, for, and switch statements are local to the if, while, for, or
1558 // switch statement (including the controlled statement).
1560 // Names declared in the for-init-statement are in the same declarative-region
1561 // as those declared in the condition.
1563 unsigned ScopeFlags = 0;
1565 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1567 ParseScope ForScope(this, ScopeFlags);
1569 BalancedDelimiterTracker T(*this, tok::l_paren);
1574 bool ForEach = false, ForRange = false;
1575 StmtResult FirstPart;
1576 Sema::ConditionResult SecondPart;
1577 ExprResult Collection;
1578 ForRangeInit ForRangeInit;
1579 FullExprArg ThirdPart(Actions);
1581 if (Tok.is(tok::code_completion)) {
1582 Actions.CodeCompleteOrdinaryName(getCurScope(),
1583 C99orCXXorObjC? Sema::PCC_ForInit
1584 : Sema::PCC_Expression);
1589 ParsedAttributesWithRange attrs(AttrFactory);
1590 MaybeParseCXX11Attributes(attrs);
1592 // Parse the first part of the for specifier.
1593 if (Tok.is(tok::semi)) { // for (;
1594 ProhibitAttributes(attrs);
1595 // no first part, eat the ';'.
1597 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1598 isForRangeIdentifier()) {
1599 ProhibitAttributes(attrs);
1600 IdentifierInfo *Name = Tok.getIdentifierInfo();
1601 SourceLocation Loc = ConsumeToken();
1602 MaybeParseCXX11Attributes(attrs);
1604 ForRangeInit.ColonLoc = ConsumeToken();
1605 if (Tok.is(tok::l_brace))
1606 ForRangeInit.RangeExpr = ParseBraceInitializer();
1608 ForRangeInit.RangeExpr = ParseExpression();
1610 Diag(Loc, diag::err_for_range_identifier)
1611 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
1612 ? FixItHint::CreateInsertion(Loc, "auto &&")
1615 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1616 attrs, attrs.Range.getEnd());
1618 } else if (isForInitDeclaration()) { // for (int X = 4;
1619 // Parse declaration, which eats the ';'.
1620 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1621 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1623 // In C++0x, "for (T NS:a" might not be a typo for ::
1624 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1625 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1627 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1628 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1629 Declarator::ForContext, DeclEnd, attrs, false,
1630 MightBeForRangeStmt ? &ForRangeInit : nullptr);
1631 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1632 if (ForRangeInit.ParsedForRangeDecl()) {
1633 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1634 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1637 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1639 } else if ((ForEach = isTokIdentifier_in())) {
1640 Actions.ActOnForEachDeclStmt(DG);
1641 // ObjC: for (id x in expr)
1642 ConsumeToken(); // consume 'in'
1644 if (Tok.is(tok::code_completion)) {
1645 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1649 Collection = ParseExpression();
1651 Diag(Tok, diag::err_expected_semi_for);
1654 ProhibitAttributes(attrs);
1655 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1657 ForEach = isTokIdentifier_in();
1659 // Turn the expression into a stmt.
1660 if (!Value.isInvalid()) {
1662 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1664 FirstPart = Actions.ActOnExprStmt(Value);
1667 if (Tok.is(tok::semi)) {
1669 } else if (ForEach) {
1670 ConsumeToken(); // consume 'in'
1672 if (Tok.is(tok::code_completion)) {
1673 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1677 Collection = ParseExpression();
1678 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1679 // User tried to write the reasonable, but ill-formed, for-range-statement
1680 // for (expr : expr) { ... }
1681 Diag(Tok, diag::err_for_range_expected_decl)
1682 << FirstPart.get()->getSourceRange();
1683 SkipUntil(tok::r_paren, StopBeforeMatch);
1684 SecondPart = Sema::ConditionError();
1686 if (!Value.isInvalid()) {
1687 Diag(Tok, diag::err_expected_semi_for);
1689 // Skip until semicolon or rparen, don't consume it.
1690 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1691 if (Tok.is(tok::semi))
1697 // Parse the second part of the for specifier.
1698 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1699 if (!ForEach && !ForRange && !SecondPart.isInvalid()) {
1700 // Parse the second part of the for specifier.
1701 if (Tok.is(tok::semi)) { // for (...;;
1703 } else if (Tok.is(tok::r_paren)) {
1704 // missing both semicolons.
1706 if (getLangOpts().CPlusPlus)
1708 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean);
1710 ExprResult SecondExpr = ParseExpression();
1711 if (SecondExpr.isInvalid())
1712 SecondPart = Sema::ConditionError();
1715 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1716 Sema::ConditionKind::Boolean);
1720 if (Tok.isNot(tok::semi)) {
1721 if (!SecondPart.isInvalid())
1722 Diag(Tok, diag::err_expected_semi_for);
1724 // Skip until semicolon or rparen, don't consume it.
1725 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1728 if (Tok.is(tok::semi)) {
1732 // Parse the third part of the for specifier.
1733 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1734 ExprResult Third = ParseExpression();
1735 // FIXME: The C++11 standard doesn't actually say that this is a
1736 // discarded-value expression, but it clearly should be.
1737 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1743 // C++ Coroutines [stmt.iter]:
1744 // 'co_await' can only be used for a range-based for statement.
1745 if (CoawaitLoc.isValid() && !ForRange) {
1746 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1747 CoawaitLoc = SourceLocation();
1750 // We need to perform most of the semantic analysis for a C++0x for-range
1751 // statememt before parsing the body, in order to be able to deduce the type
1752 // of an auto-typed loop variable.
1753 StmtResult ForRangeStmt;
1754 StmtResult ForEachStmt;
1757 ExprResult CorrectedRange =
1758 Actions.CorrectDelayedTyposInExpr(ForRangeInit.RangeExpr.get());
1759 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1760 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1761 ForRangeInit.ColonLoc, CorrectedRange.get(),
1762 T.getCloseLocation(), Sema::BFRK_Build);
1764 // Similarly, we need to do the semantic analysis for a for-range
1765 // statement immediately in order to close over temporaries correctly.
1766 } else if (ForEach) {
1767 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1770 T.getCloseLocation());
1772 // In OpenMP loop region loop control variable must be captured and be
1773 // private. Perform analysis of first part (if any).
1774 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1775 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1779 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1780 // there is no compound stmt. C90 does not have this clause. We only do this
1781 // if the body isn't a compound statement to avoid push/pop in common cases.
1784 // The substatement in an iteration-statement implicitly defines a local scope
1785 // which is entered and exited each time through the loop.
1787 // See comments in ParseIfStatement for why we create a scope for
1788 // for-init-statement/condition and a new scope for substatement in C++.
1790 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1791 Tok.is(tok::l_brace));
1793 // The body of the for loop has the same local mangling number as the
1794 // for-init-statement.
1795 // It will only be incremented if the body contains other things that would
1796 // normally increment the mangling number (like a compound statement).
1798 getCurScope()->decrementMSManglingNumber();
1800 // Read the body statement.
1801 StmtResult Body(ParseStatement(TrailingElseLoc));
1803 // Pop the body scope if needed.
1806 // Leave the for-scope.
1809 if (Body.isInvalid())
1813 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1817 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1819 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1820 SecondPart, ThirdPart, T.getCloseLocation(),
1824 /// ParseGotoStatement
1826 /// 'goto' identifier ';'
1827 /// [GNU] 'goto' '*' expression ';'
1829 /// Note: this lets the caller parse the end ';'.
1831 StmtResult Parser::ParseGotoStatement() {
1832 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1833 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1836 if (Tok.is(tok::identifier)) {
1837 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1839 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1841 } else if (Tok.is(tok::star)) {
1842 // GNU indirect goto extension.
1843 Diag(Tok, diag::ext_gnu_indirect_goto);
1844 SourceLocation StarLoc = ConsumeToken();
1845 ExprResult R(ParseExpression());
1846 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1847 SkipUntil(tok::semi, StopBeforeMatch);
1850 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1852 Diag(Tok, diag::err_expected) << tok::identifier;
1859 /// ParseContinueStatement
1863 /// Note: this lets the caller parse the end ';'.
1865 StmtResult Parser::ParseContinueStatement() {
1866 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1867 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1870 /// ParseBreakStatement
1874 /// Note: this lets the caller parse the end ';'.
1876 StmtResult Parser::ParseBreakStatement() {
1877 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1878 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1881 /// ParseReturnStatement
1883 /// 'return' expression[opt] ';'
1884 /// 'return' braced-init-list ';'
1885 /// 'co_return' expression[opt] ';'
1886 /// 'co_return' braced-init-list ';'
1887 StmtResult Parser::ParseReturnStatement() {
1888 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1889 "Not a return stmt!");
1890 bool IsCoreturn = Tok.is(tok::kw_co_return);
1891 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1894 if (Tok.isNot(tok::semi)) {
1895 // FIXME: Code completion for co_return.
1896 if (Tok.is(tok::code_completion) && !IsCoreturn) {
1897 Actions.CodeCompleteReturn(getCurScope());
1902 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1903 R = ParseInitializer();
1905 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1906 diag::warn_cxx98_compat_generalized_initializer_lists :
1907 diag::ext_generalized_initializer_lists)
1908 << R.get()->getSourceRange();
1910 R = ParseExpression();
1911 if (R.isInvalid()) {
1912 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1917 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
1918 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1921 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1922 AllowedConstructsKind Allowed,
1923 SourceLocation *TrailingElseLoc,
1924 ParsedAttributesWithRange &Attrs) {
1925 // Create temporary attribute list.
1926 ParsedAttributesWithRange TempAttrs(AttrFactory);
1928 // Get loop hints and consume annotated token.
1929 while (Tok.is(tok::annot_pragma_loop_hint)) {
1931 if (!HandlePragmaLoopHint(Hint))
1934 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1935 ArgsUnion(Hint.ValueExpr)};
1936 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1937 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1938 AttributeList::AS_Pragma);
1941 // Get the next statement.
1942 MaybeParseCXX11Attributes(Attrs);
1944 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1945 Stmts, Allowed, TrailingElseLoc, Attrs);
1947 Attrs.takeAllFrom(TempAttrs);
1951 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1952 assert(Tok.is(tok::l_brace));
1953 SourceLocation LBraceLoc = Tok.getLocation();
1955 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1956 "parsing function body");
1958 // Save and reset current vtordisp stack if we have entered a C++ method body.
1960 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1961 Sema::PragmaStackSentinelRAII
1962 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1964 // Do not enter a scope for the brace, as the arguments are in the same scope
1965 // (the function body) as the body itself. Instead, just read the statement
1966 // list and put it into a CompoundStmt for safe keeping.
1967 StmtResult FnBody(ParseCompoundStatementBody());
1969 // If the function body could not be parsed, make a bogus compoundstmt.
1970 if (FnBody.isInvalid()) {
1971 Sema::CompoundScopeRAII CompoundScope(Actions);
1972 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1976 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1979 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1981 /// function-try-block:
1982 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1984 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1985 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1986 SourceLocation TryLoc = ConsumeToken();
1988 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1989 "parsing function try block");
1991 // Constructor initializer list?
1992 if (Tok.is(tok::colon))
1993 ParseConstructorInitializer(Decl);
1995 Actions.ActOnDefaultCtorInitializers(Decl);
1997 // Save and reset current vtordisp stack if we have entered a C++ method body.
1999 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2000 Sema::PragmaStackSentinelRAII
2001 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2003 SourceLocation LBraceLoc = Tok.getLocation();
2004 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2005 // If we failed to parse the try-catch, we just give the function an empty
2006 // compound statement as the body.
2007 if (FnBody.isInvalid()) {
2008 Sema::CompoundScopeRAII CompoundScope(Actions);
2009 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2013 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2016 bool Parser::trySkippingFunctionBody() {
2017 assert(SkipFunctionBodies &&
2018 "Should only be called when SkipFunctionBodies is enabled");
2019 if (!PP.isCodeCompletionEnabled()) {
2024 // We're in code-completion mode. Skip parsing for all function bodies unless
2025 // the body contains the code-completion point.
2026 TentativeParsingAction PA(*this);
2027 bool IsTryCatch = Tok.is(tok::kw_try);
2029 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2030 if (llvm::any_of(Toks, [](const Token &Tok) {
2031 return Tok.is(tok::code_completion);
2036 if (ErrorInPrologue) {
2038 SkipMalformedDecl();
2041 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2045 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2046 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2047 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2056 /// ParseCXXTryBlock - Parse a C++ try-block.
2059 /// 'try' compound-statement handler-seq
2061 StmtResult Parser::ParseCXXTryBlock() {
2062 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2064 SourceLocation TryLoc = ConsumeToken();
2065 return ParseCXXTryBlockCommon(TryLoc);
2068 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2069 /// function-try-block.
2072 /// 'try' compound-statement handler-seq
2074 /// function-try-block:
2075 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2078 /// handler handler-seq[opt]
2080 /// [Borland] try-block:
2081 /// 'try' compound-statement seh-except-block
2082 /// 'try' compound-statement seh-finally-block
2084 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2085 if (Tok.isNot(tok::l_brace))
2086 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2088 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2089 Scope::DeclScope | Scope::TryScope |
2090 (FnTry ? Scope::FnTryCatchScope : 0)));
2091 if (TryBlock.isInvalid())
2094 // Borland allows SEH-handlers with 'try'
2096 if ((Tok.is(tok::identifier) &&
2097 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2098 Tok.is(tok::kw___finally)) {
2099 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2101 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2102 SourceLocation Loc = ConsumeToken();
2103 Handler = ParseSEHExceptBlock(Loc);
2106 SourceLocation Loc = ConsumeToken();
2107 Handler = ParseSEHFinallyBlock(Loc);
2109 if(Handler.isInvalid())
2112 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2118 StmtVector Handlers;
2120 // C++11 attributes can't appear here, despite this context seeming
2122 DiagnoseAndSkipCXX11Attributes();
2124 if (Tok.isNot(tok::kw_catch))
2125 return StmtError(Diag(Tok, diag::err_expected_catch));
2126 while (Tok.is(tok::kw_catch)) {
2127 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2128 if (!Handler.isInvalid())
2129 Handlers.push_back(Handler.get());
2131 // Don't bother creating the full statement if we don't have any usable
2133 if (Handlers.empty())
2136 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2140 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2143 /// 'catch' '(' exception-declaration ')' compound-statement
2145 /// exception-declaration:
2146 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2147 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2150 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2151 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2153 SourceLocation CatchLoc = ConsumeToken();
2155 BalancedDelimiterTracker T(*this, tok::l_paren);
2156 if (T.expectAndConsume())
2160 // The name in a catch exception-declaration is local to the handler and
2161 // shall not be redeclared in the outermost block of the handler.
2162 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2163 (FnCatch ? Scope::FnTryCatchScope : 0));
2165 // exception-declaration is equivalent to '...' or a parameter-declaration
2166 // without default arguments.
2167 Decl *ExceptionDecl = nullptr;
2168 if (Tok.isNot(tok::ellipsis)) {
2169 ParsedAttributesWithRange Attributes(AttrFactory);
2170 MaybeParseCXX11Attributes(Attributes);
2172 DeclSpec DS(AttrFactory);
2173 DS.takeAttributesFrom(Attributes);
2175 if (ParseCXXTypeSpecifierSeq(DS))
2178 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2179 ParseDeclarator(ExDecl);
2180 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2185 if (T.getCloseLocation().isInvalid())
2188 if (Tok.isNot(tok::l_brace))
2189 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2191 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2192 StmtResult Block(ParseCompoundStatement());
2193 if (Block.isInvalid())
2196 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2199 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2200 IfExistsCondition Result;
2201 if (ParseMicrosoftIfExistsCondition(Result))
2204 // Handle dependent statements by parsing the braces as a compound statement.
2205 // This is not the same behavior as Visual C++, which don't treat this as a
2206 // compound statement, but for Clang's type checking we can't have anything
2207 // inside these braces escaping to the surrounding code.
2208 if (Result.Behavior == IEB_Dependent) {
2209 if (!Tok.is(tok::l_brace)) {
2210 Diag(Tok, diag::err_expected) << tok::l_brace;
2214 StmtResult Compound = ParseCompoundStatement();
2215 if (Compound.isInvalid())
2218 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2223 if (DepResult.isUsable())
2224 Stmts.push_back(DepResult.get());
2228 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2229 if (Braces.consumeOpen()) {
2230 Diag(Tok, diag::err_expected) << tok::l_brace;
2234 switch (Result.Behavior) {
2236 // Parse the statements below.
2240 llvm_unreachable("Dependent case handled above");
2247 // Condition is true, parse the statements.
2248 while (Tok.isNot(tok::r_brace)) {
2249 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2251 Stmts.push_back(R.get());
2253 Braces.consumeClose();
2256 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2257 MaybeParseGNUAttributes(Attrs);
2262 if (Attrs.getList()->getKind() != AttributeList::AT_OpenCLUnrollHint)
2265 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2266 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);