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(DeclaratorContext::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(
457 /*isStmtExpr=*/false,
458 Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
459 if (TryBlock.isInvalid())
463 if (Tok.is(tok::identifier) &&
464 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
465 SourceLocation Loc = ConsumeToken();
466 Handler = ParseSEHExceptBlock(Loc);
467 } else if (Tok.is(tok::kw___finally)) {
468 SourceLocation Loc = ConsumeToken();
469 Handler = ParseSEHFinallyBlock(Loc);
471 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
474 if(Handler.isInvalid())
477 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
483 /// ParseSEHExceptBlock - Handle __except
485 /// seh-except-block:
486 /// '__except' '(' seh-filter-expression ')' compound-statement
488 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
489 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
490 raii2(Ident___exception_code, false),
491 raii3(Ident_GetExceptionCode, false);
493 if (ExpectAndConsume(tok::l_paren))
496 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
497 Scope::SEHExceptScope);
499 if (getLangOpts().Borland) {
500 Ident__exception_info->setIsPoisoned(false);
501 Ident___exception_info->setIsPoisoned(false);
502 Ident_GetExceptionInfo->setIsPoisoned(false);
505 ExprResult FilterExpr;
507 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
508 Scope::SEHFilterScope);
509 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
512 if (getLangOpts().Borland) {
513 Ident__exception_info->setIsPoisoned(true);
514 Ident___exception_info->setIsPoisoned(true);
515 Ident_GetExceptionInfo->setIsPoisoned(true);
518 if(FilterExpr.isInvalid())
521 if (ExpectAndConsume(tok::r_paren))
524 if (Tok.isNot(tok::l_brace))
525 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
527 StmtResult Block(ParseCompoundStatement());
529 if(Block.isInvalid())
532 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
535 /// ParseSEHFinallyBlock - Handle __finally
537 /// seh-finally-block:
538 /// '__finally' compound-statement
540 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
541 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
542 raii2(Ident___abnormal_termination, false),
543 raii3(Ident_AbnormalTermination, false);
545 if (Tok.isNot(tok::l_brace))
546 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
548 ParseScope FinallyScope(this, 0);
549 Actions.ActOnStartSEHFinallyBlock();
551 StmtResult Block(ParseCompoundStatement());
552 if(Block.isInvalid()) {
553 Actions.ActOnAbortSEHFinallyBlock();
557 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
562 /// seh-leave-statement:
565 StmtResult Parser::ParseSEHLeaveStatement() {
566 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
567 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
570 /// ParseLabeledStatement - We have an identifier and a ':' after it.
572 /// labeled-statement:
573 /// identifier ':' statement
574 /// [GNU] identifier ':' attributes[opt] statement
576 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
577 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
578 "Not an identifier!");
580 Token IdentTok = Tok; // Save the whole token.
581 ConsumeToken(); // eat the identifier.
583 assert(Tok.is(tok::colon) && "Not a label!");
585 // identifier ':' statement
586 SourceLocation ColonLoc = ConsumeToken();
588 // Read label attributes, if present.
590 if (Tok.is(tok::kw___attribute)) {
591 ParsedAttributesWithRange TempAttrs(AttrFactory);
592 ParseGNUAttributes(TempAttrs);
594 // In C++, GNU attributes only apply to the label if they are followed by a
595 // semicolon, to disambiguate label attributes from attributes on a labeled
598 // This doesn't quite match what GCC does; if the attribute list is empty
599 // and followed by a semicolon, GCC will reject (it appears to parse the
600 // attributes as part of a statement in that case). That looks like a bug.
601 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
602 attrs.takeAllFrom(TempAttrs);
603 else if (isDeclarationStatement()) {
605 // FIXME: We should do this whether or not we have a declaration
606 // statement, but that doesn't work correctly (because ProhibitAttributes
607 // can't handle GNU attributes), so only call it in the one case where
608 // GNU attributes are allowed.
609 SubStmt = ParseStatementOrDeclarationAfterAttributes(
610 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
612 if (!TempAttrs.empty() && !SubStmt.isInvalid())
613 SubStmt = Actions.ProcessStmtAttributes(
614 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
616 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
620 // If we've not parsed a statement yet, parse one now.
621 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
622 SubStmt = ParseStatement();
624 // Broken substmt shouldn't prevent the label from being added to the AST.
625 if (SubStmt.isInvalid())
626 SubStmt = Actions.ActOnNullStmt(ColonLoc);
628 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
629 IdentTok.getLocation());
630 if (AttributeList *Attrs = attrs.getList()) {
631 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
635 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
639 /// ParseCaseStatement
640 /// labeled-statement:
641 /// 'case' constant-expression ':' statement
642 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
644 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
645 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
647 // It is very very common for code to contain many case statements recursively
648 // nested, as in (but usually without indentation):
655 // Parsing this naively works, but is both inefficient and can cause us to run
656 // out of stack space in our recursive descent parser. As a special case,
657 // flatten this recursion into an iterative loop. This is complex and gross,
658 // but all the grossness is constrained to ParseCaseStatement (and some
659 // weirdness in the actions), so this is just local grossness :).
661 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
663 StmtResult TopLevelCase(true);
665 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
666 // gets updated each time a new case is parsed, and whose body is unset so
667 // far. When parsing 'case 4', this is the 'case 3' node.
668 Stmt *DeepestParsedCaseStmt = nullptr;
670 // While we have case statements, eat and stack them.
671 SourceLocation ColonLoc;
673 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
674 ConsumeToken(); // eat the 'case'.
675 ColonLoc = SourceLocation();
677 if (Tok.is(tok::code_completion)) {
678 Actions.CodeCompleteCase(getCurScope());
683 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
684 /// Disable this form of error recovery while we're parsing the case
686 ColonProtectionRAIIObject ColonProtection(*this);
690 LHS = ParseConstantExpression();
691 if (!getLangOpts().CPlusPlus11) {
692 LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) {
693 return Actions.VerifyIntegerConstantExpression(E);
696 if (LHS.isInvalid()) {
697 // If constant-expression is parsed unsuccessfully, recover by skipping
698 // current case statement (moving to the colon that ends it).
699 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
700 TryConsumeToken(tok::colon, ColonLoc);
710 // GNU case range extension.
711 SourceLocation DotDotDotLoc;
713 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
714 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
715 RHS = ParseConstantExpression();
716 if (RHS.isInvalid()) {
717 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) {
718 TryConsumeToken(tok::colon, ColonLoc);
725 ColonProtection.restore();
727 if (TryConsumeToken(tok::colon, ColonLoc)) {
728 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
729 TryConsumeToken(tok::coloncolon, ColonLoc)) {
730 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
731 Diag(ColonLoc, diag::err_expected_after)
732 << "'case'" << tok::colon
733 << FixItHint::CreateReplacement(ColonLoc, ":");
735 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
736 Diag(ExpectedLoc, diag::err_expected_after)
737 << "'case'" << tok::colon
738 << FixItHint::CreateInsertion(ExpectedLoc, ":");
739 ColonLoc = ExpectedLoc;
743 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
744 RHS.get(), ColonLoc);
746 // If we had a sema error parsing this case, then just ignore it and
747 // continue parsing the sub-stmt.
748 if (Case.isInvalid()) {
749 if (TopLevelCase.isInvalid()) // No parsed case stmts.
750 return ParseStatement(/*TrailingElseLoc=*/nullptr,
751 /*AllowOpenMPStandalone=*/true);
752 // Otherwise, just don't add it as a nested case.
754 // If this is the first case statement we parsed, it becomes TopLevelCase.
755 // Otherwise we link it into the current chain.
756 Stmt *NextDeepest = Case.get();
757 if (TopLevelCase.isInvalid())
760 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
761 DeepestParsedCaseStmt = NextDeepest;
764 // Handle all case statements.
765 } while (Tok.is(tok::kw_case));
767 // If we found a non-case statement, start by parsing it.
770 if (Tok.isNot(tok::r_brace)) {
771 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
772 /*AllowOpenMPStandalone=*/true);
774 // Nicely diagnose the common error "switch (X) { case 4: }", which is
775 // not valid. If ColonLoc doesn't point to a valid text location, there was
776 // another parsing error, so avoid producing extra diagnostics.
777 if (ColonLoc.isValid()) {
778 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
779 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
780 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
782 SubStmt = StmtError();
785 // Install the body into the most deeply-nested case.
786 if (DeepestParsedCaseStmt) {
787 // Broken sub-stmt shouldn't prevent forming the case statement properly.
788 if (SubStmt.isInvalid())
789 SubStmt = Actions.ActOnNullStmt(SourceLocation());
790 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
793 // Return the top level parsed statement tree.
797 /// ParseDefaultStatement
798 /// labeled-statement:
799 /// 'default' ':' statement
800 /// Note that this does not parse the 'statement' at the end.
802 StmtResult Parser::ParseDefaultStatement() {
803 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
804 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
806 SourceLocation ColonLoc;
807 if (TryConsumeToken(tok::colon, ColonLoc)) {
808 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
809 // Treat "default;" as a typo for "default:".
810 Diag(ColonLoc, diag::err_expected_after)
811 << "'default'" << tok::colon
812 << FixItHint::CreateReplacement(ColonLoc, ":");
814 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
815 Diag(ExpectedLoc, diag::err_expected_after)
816 << "'default'" << tok::colon
817 << FixItHint::CreateInsertion(ExpectedLoc, ":");
818 ColonLoc = ExpectedLoc;
823 if (Tok.isNot(tok::r_brace)) {
824 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
825 /*AllowOpenMPStandalone=*/true);
827 // Diagnose the common error "switch (X) {... default: }", which is
829 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
830 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
831 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
835 // Broken sub-stmt shouldn't prevent forming the case statement properly.
836 if (SubStmt.isInvalid())
837 SubStmt = Actions.ActOnNullStmt(ColonLoc);
839 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
840 SubStmt.get(), getCurScope());
843 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
844 return ParseCompoundStatement(isStmtExpr,
845 Scope::DeclScope | Scope::CompoundStmtScope);
848 /// ParseCompoundStatement - Parse a "{}" block.
850 /// compound-statement: [C99 6.8.2]
851 /// { block-item-list[opt] }
852 /// [GNU] { label-declarations block-item-list } [TODO]
856 /// block-item-list block-item
860 /// [GNU] '__extension__' declaration
863 /// [GNU] label-declarations:
864 /// [GNU] label-declaration
865 /// [GNU] label-declarations label-declaration
867 /// [GNU] label-declaration:
868 /// [GNU] '__label__' identifier-list ';'
870 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
871 unsigned ScopeFlags) {
872 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
874 // Enter a scope to hold everything within the compound stmt. Compound
875 // statements can always hold declarations.
876 ParseScope CompoundScope(this, ScopeFlags);
878 // Parse the statements in the body.
879 return ParseCompoundStatementBody(isStmtExpr);
882 /// Parse any pragmas at the start of the compound expression. We handle these
883 /// separately since some pragmas (FP_CONTRACT) must appear before any C
884 /// statement in the compound, but may be intermingled with other pragmas.
885 void Parser::ParseCompoundStatementLeadingPragmas() {
886 bool checkForPragmas = true;
887 while (checkForPragmas) {
888 switch (Tok.getKind()) {
889 case tok::annot_pragma_vis:
890 HandlePragmaVisibility();
892 case tok::annot_pragma_pack:
895 case tok::annot_pragma_msstruct:
896 HandlePragmaMSStruct();
898 case tok::annot_pragma_align:
901 case tok::annot_pragma_weak:
904 case tok::annot_pragma_weakalias:
905 HandlePragmaWeakAlias();
907 case tok::annot_pragma_redefine_extname:
908 HandlePragmaRedefineExtname();
910 case tok::annot_pragma_opencl_extension:
911 HandlePragmaOpenCLExtension();
913 case tok::annot_pragma_fp_contract:
914 HandlePragmaFPContract();
916 case tok::annot_pragma_fp:
919 case tok::annot_pragma_ms_pointers_to_members:
920 HandlePragmaMSPointersToMembers();
922 case tok::annot_pragma_ms_pragma:
923 HandlePragmaMSPragma();
925 case tok::annot_pragma_ms_vtordisp:
926 HandlePragmaMSVtorDisp();
928 case tok::annot_pragma_dump:
932 checkForPragmas = false;
939 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
940 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
941 /// consume the '}' at the end of the block. It does not manipulate the scope
943 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
944 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
946 "in compound statement ('{}')");
948 // Record the state of the FP_CONTRACT pragma, restore on leaving the
949 // compound statement.
950 Sema::FPContractStateRAII SaveFPContractState(Actions);
952 InMessageExpressionRAIIObject InMessage(*this, false);
953 BalancedDelimiterTracker T(*this, tok::l_brace);
957 Sema::CompoundScopeRAII CompoundScope(Actions);
959 // Parse any pragmas at the beginning of the compound statement.
960 ParseCompoundStatementLeadingPragmas();
964 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
965 // only allowed at the start of a compound stmt regardless of the language.
966 while (Tok.is(tok::kw___label__)) {
967 SourceLocation LabelLoc = ConsumeToken();
969 SmallVector<Decl *, 8> DeclsInGroup;
971 if (Tok.isNot(tok::identifier)) {
972 Diag(Tok, diag::err_expected) << tok::identifier;
976 IdentifierInfo *II = Tok.getIdentifierInfo();
977 SourceLocation IdLoc = ConsumeToken();
978 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
980 if (!TryConsumeToken(tok::comma))
984 DeclSpec DS(AttrFactory);
986 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
987 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
989 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
991 Stmts.push_back(R.get());
994 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
995 Tok.isNot(tok::eof)) {
996 if (Tok.is(tok::annot_pragma_unused)) {
997 HandlePragmaUnused();
1002 if (Tok.isNot(tok::kw___extension__)) {
1003 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
1005 // __extension__ can start declarations and it can also be a unary
1006 // operator for expressions. Consume multiple __extension__ markers here
1007 // until we can determine which is which.
1008 // FIXME: This loses extension expressions in the AST!
1009 SourceLocation ExtLoc = ConsumeToken();
1010 while (Tok.is(tok::kw___extension__))
1013 ParsedAttributesWithRange attrs(AttrFactory);
1014 MaybeParseCXX11Attributes(attrs, nullptr,
1015 /*MightBeObjCMessageSend*/ true);
1017 // If this is the start of a declaration, parse it as such.
1018 if (isDeclarationStatement()) {
1019 // __extension__ silences extension warnings in the subdeclaration.
1020 // FIXME: Save the __extension__ on the decl as a node somehow?
1021 ExtensionRAIIObject O(Diags);
1023 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1024 DeclGroupPtrTy Res =
1025 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, attrs);
1026 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1028 // Otherwise this was a unary __extension__ marker.
1029 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1031 if (Res.isInvalid()) {
1032 SkipUntil(tok::semi);
1036 // FIXME: Use attributes?
1037 // Eat the semicolon at the end of stmt and convert the expr into a
1039 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1040 R = Actions.ActOnExprStmt(Res);
1045 Stmts.push_back(R.get());
1048 SourceLocation CloseLoc = Tok.getLocation();
1050 // We broke out of the while loop because we found a '}' or EOF.
1051 if (!T.consumeClose())
1052 // Recover by creating a compound statement with what we parsed so far,
1053 // instead of dropping everything and returning StmtError();
1054 CloseLoc = T.getCloseLocation();
1056 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1060 /// ParseParenExprOrCondition:
1061 /// [C ] '(' expression ')'
1062 /// [C++] '(' condition ')'
1063 /// [C++1z] '(' init-statement[opt] condition ')'
1065 /// This function parses and performs error recovery on the specified condition
1066 /// or expression (depending on whether we're in C++ or C mode). This function
1067 /// goes out of its way to recover well. It returns true if there was a parser
1068 /// error (the right paren couldn't be found), which indicates that the caller
1069 /// should try to recover harder. It returns false if the condition is
1070 /// successfully parsed. Note that a successful parse can still have semantic
1071 /// errors in the condition.
1072 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1073 Sema::ConditionResult &Cond,
1075 Sema::ConditionKind CK) {
1076 BalancedDelimiterTracker T(*this, tok::l_paren);
1079 if (getLangOpts().CPlusPlus)
1080 Cond = ParseCXXCondition(InitStmt, Loc, CK);
1082 ExprResult CondExpr = ParseExpression();
1084 // If required, convert to a boolean value.
1085 if (CondExpr.isInvalid())
1086 Cond = Sema::ConditionError();
1088 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1091 // If the parser was confused by the condition and we don't have a ')', try to
1092 // recover by skipping ahead to a semi and bailing out. If condexp is
1093 // semantically invalid but we have well formed code, keep going.
1094 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1095 SkipUntil(tok::semi);
1096 // Skipping may have stopped if it found the containing ')'. If so, we can
1097 // continue parsing the if statement.
1098 if (Tok.isNot(tok::r_paren))
1102 // Otherwise the condition is valid or the rparen is present.
1105 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1106 // that all callers are looking for a statement after the condition, so ")"
1108 while (Tok.is(tok::r_paren)) {
1109 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1110 << FixItHint::CreateRemoval(Tok.getLocation());
1118 /// ParseIfStatement
1119 /// if-statement: [C99 6.8.4.1]
1120 /// 'if' '(' expression ')' statement
1121 /// 'if' '(' expression ')' statement 'else' statement
1122 /// [C++] 'if' '(' condition ')' statement
1123 /// [C++] 'if' '(' condition ')' statement 'else' statement
1125 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1126 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1127 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1129 bool IsConstexpr = false;
1130 if (Tok.is(tok::kw_constexpr)) {
1131 Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
1132 : diag::ext_constexpr_if);
1137 if (Tok.isNot(tok::l_paren)) {
1138 Diag(Tok, diag::err_expected_lparen_after) << "if";
1139 SkipUntil(tok::semi);
1143 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1145 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1146 // the case for C90.
1149 // A name introduced by a declaration in a condition is in scope from its
1150 // point of declaration until the end of the substatements controlled by the
1153 // Names declared in the for-init-statement, and in the condition of if,
1154 // while, for, and switch statements are local to the if, while, for, or
1155 // switch statement (including the controlled statement).
1157 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1159 // Parse the condition.
1160 StmtResult InitStmt;
1161 Sema::ConditionResult Cond;
1162 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1163 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1164 : Sema::ConditionKind::Boolean))
1167 llvm::Optional<bool> ConstexprCondition;
1169 ConstexprCondition = Cond.getKnownValue();
1171 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1172 // there is no compound stmt. C90 does not have this clause. We only do this
1173 // if the body isn't a compound statement to avoid push/pop in common cases.
1176 // The substatement in a selection-statement (each substatement, in the else
1177 // form of the if statement) implicitly defines a local scope.
1179 // For C++ we create a scope for the condition and a new scope for
1180 // substatements because:
1181 // -When the 'then' scope exits, we want the condition declaration to still be
1182 // active for the 'else' scope too.
1183 // -Sema will detect name clashes by considering declarations of a
1184 // 'ControlScope' as part of its direct subscope.
1185 // -If we wanted the condition and substatement to be in the same scope, we
1186 // would have to notify ParseStatement not to create a new scope. It's
1187 // simpler to let it create a new scope.
1189 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1191 // Read the 'then' stmt.
1192 SourceLocation ThenStmtLoc = Tok.getLocation();
1194 SourceLocation InnerStatementTrailingElseLoc;
1195 StmtResult ThenStmt;
1197 EnterExpressionEvaluationContext PotentiallyDiscarded(
1198 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1200 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1201 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1204 // Pop the 'if' scope if needed.
1207 // If it has an else, parse it.
1208 SourceLocation ElseLoc;
1209 SourceLocation ElseStmtLoc;
1210 StmtResult ElseStmt;
1212 if (Tok.is(tok::kw_else)) {
1213 if (TrailingElseLoc)
1214 *TrailingElseLoc = Tok.getLocation();
1216 ElseLoc = ConsumeToken();
1217 ElseStmtLoc = Tok.getLocation();
1219 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1220 // there is no compound stmt. C90 does not have this clause. We only do
1221 // this if the body isn't a compound statement to avoid push/pop in common
1225 // The substatement in a selection-statement (each substatement, in the else
1226 // form of the if statement) implicitly defines a local scope.
1228 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1229 Tok.is(tok::l_brace));
1231 EnterExpressionEvaluationContext PotentiallyDiscarded(
1232 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1234 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1235 ElseStmt = ParseStatement();
1237 // Pop the 'else' scope if needed.
1239 } else if (Tok.is(tok::code_completion)) {
1240 Actions.CodeCompleteAfterIf(getCurScope());
1243 } else if (InnerStatementTrailingElseLoc.isValid()) {
1244 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1249 // If the then or else stmt is invalid and the other is valid (and present),
1250 // make turn the invalid one into a null stmt to avoid dropping the other
1251 // part. If both are invalid, return error.
1252 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1253 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1254 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1255 // Both invalid, or one is invalid and other is non-present: return error.
1259 // Now if either are invalid, replace with a ';'.
1260 if (ThenStmt.isInvalid())
1261 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1262 if (ElseStmt.isInvalid())
1263 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1265 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1266 ThenStmt.get(), ElseLoc, ElseStmt.get());
1269 /// ParseSwitchStatement
1270 /// switch-statement:
1271 /// 'switch' '(' expression ')' statement
1272 /// [C++] 'switch' '(' condition ')' statement
1273 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1274 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1275 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1277 if (Tok.isNot(tok::l_paren)) {
1278 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1279 SkipUntil(tok::semi);
1283 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1285 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1286 // not the case for C90. Start the switch scope.
1289 // A name introduced by a declaration in a condition is in scope from its
1290 // point of declaration until the end of the substatements controlled by the
1293 // Names declared in the for-init-statement, and in the condition of if,
1294 // while, for, and switch statements are local to the if, while, for, or
1295 // switch statement (including the controlled statement).
1297 unsigned ScopeFlags = Scope::SwitchScope;
1299 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1300 ParseScope SwitchScope(this, ScopeFlags);
1302 // Parse the condition.
1303 StmtResult InitStmt;
1304 Sema::ConditionResult Cond;
1305 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1306 Sema::ConditionKind::Switch))
1310 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1312 if (Switch.isInvalid()) {
1313 // Skip the switch body.
1314 // FIXME: This is not optimal recovery, but parsing the body is more
1315 // dangerous due to the presence of case and default statements, which
1316 // will have no place to connect back with the switch.
1317 if (Tok.is(tok::l_brace)) {
1319 SkipUntil(tok::r_brace);
1321 SkipUntil(tok::semi);
1325 // C99 6.8.4p3 - In C99, the body of the switch 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 a selection-statement (each substatement, in the else
1331 // form of the if statement) implicitly defines a local scope.
1333 // See comments in ParseIfStatement for why we create a scope for the
1334 // condition and a new scope for substatement in C++.
1336 getCurScope()->AddFlags(Scope::BreakScope);
1337 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1339 // We have incremented the mangling number for the SwitchScope and the
1340 // InnerScope, which is one too many.
1342 getCurScope()->decrementMSManglingNumber();
1344 // Read the body statement.
1345 StmtResult Body(ParseStatement(TrailingElseLoc));
1351 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1354 /// ParseWhileStatement
1355 /// while-statement: [C99 6.8.5.1]
1356 /// 'while' '(' expression ')' statement
1357 /// [C++] 'while' '(' condition ')' statement
1358 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1359 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1360 SourceLocation WhileLoc = Tok.getLocation();
1361 ConsumeToken(); // eat the 'while'.
1363 if (Tok.isNot(tok::l_paren)) {
1364 Diag(Tok, diag::err_expected_lparen_after) << "while";
1365 SkipUntil(tok::semi);
1369 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1371 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1372 // the case for C90. Start the loop scope.
1375 // A name introduced by a declaration in a condition is in scope from its
1376 // point of declaration until the end of the substatements controlled by the
1379 // Names declared in the for-init-statement, and in the condition of if,
1380 // while, for, and switch statements are local to the if, while, for, or
1381 // switch statement (including the controlled statement).
1383 unsigned ScopeFlags;
1385 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1386 Scope::DeclScope | Scope::ControlScope;
1388 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1389 ParseScope WhileScope(this, ScopeFlags);
1391 // Parse the condition.
1392 Sema::ConditionResult Cond;
1393 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1394 Sema::ConditionKind::Boolean))
1397 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1398 // there is no compound stmt. C90 does not have this clause. We only do this
1399 // if the body isn't a compound statement to avoid push/pop in common cases.
1402 // The substatement in an iteration-statement implicitly defines a local scope
1403 // which is entered and exited each time through the loop.
1405 // See comments in ParseIfStatement for why we create a scope for the
1406 // condition and a new scope for substatement in C++.
1408 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1410 // Read the body statement.
1411 StmtResult Body(ParseStatement(TrailingElseLoc));
1413 // Pop the body scope if needed.
1417 if (Cond.isInvalid() || Body.isInvalid())
1420 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1423 /// ParseDoStatement
1424 /// do-statement: [C99 6.8.5.2]
1425 /// 'do' statement 'while' '(' expression ')' ';'
1426 /// Note: this lets the caller parse the end ';'.
1427 StmtResult Parser::ParseDoStatement() {
1428 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1429 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1431 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1432 // the case for C90. Start the loop scope.
1433 unsigned ScopeFlags;
1434 if (getLangOpts().C99)
1435 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1437 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1439 ParseScope DoScope(this, ScopeFlags);
1441 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1442 // there is no compound stmt. C90 does not have this clause. We only do this
1443 // if the body isn't a compound statement to avoid push/pop in common cases.
1446 // The substatement in an iteration-statement implicitly defines a local scope
1447 // which is entered and exited each time through the loop.
1449 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1450 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1452 // Read the body statement.
1453 StmtResult Body(ParseStatement());
1455 // Pop the body scope if needed.
1458 if (Tok.isNot(tok::kw_while)) {
1459 if (!Body.isInvalid()) {
1460 Diag(Tok, diag::err_expected_while);
1461 Diag(DoLoc, diag::note_matching) << "'do'";
1462 SkipUntil(tok::semi, StopBeforeMatch);
1466 SourceLocation WhileLoc = ConsumeToken();
1468 if (Tok.isNot(tok::l_paren)) {
1469 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1470 SkipUntil(tok::semi, StopBeforeMatch);
1474 // Parse the parenthesized expression.
1475 BalancedDelimiterTracker T(*this, tok::l_paren);
1478 // A do-while expression is not a condition, so can't have attributes.
1479 DiagnoseAndSkipCXX11Attributes();
1481 ExprResult Cond = ParseExpression();
1482 // Correct the typos in condition before closing the scope.
1483 if (Cond.isUsable())
1484 Cond = Actions.CorrectDelayedTyposInExpr(Cond);
1488 if (Cond.isInvalid() || Body.isInvalid())
1491 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1492 Cond.get(), T.getCloseLocation());
1495 bool Parser::isForRangeIdentifier() {
1496 assert(Tok.is(tok::identifier));
1498 const Token &Next = NextToken();
1499 if (Next.is(tok::colon))
1502 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1503 TentativeParsingAction PA(*this);
1505 SkipCXX11Attributes();
1506 bool Result = Tok.is(tok::colon);
1514 /// ParseForStatement
1515 /// for-statement: [C99 6.8.5.3]
1516 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1517 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1518 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1521 /// 'co_await'[opt] [Coroutines]
1522 /// '(' for-range-declaration ':' for-range-initializer ')'
1524 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1525 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1527 /// [C++] for-init-statement:
1528 /// [C++] expression-statement
1529 /// [C++] simple-declaration
1531 /// [C++0x] for-range-declaration:
1532 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1533 /// [C++0x] for-range-initializer:
1534 /// [C++0x] expression
1535 /// [C++0x] braced-init-list [TODO]
1536 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1537 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1538 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1540 SourceLocation CoawaitLoc;
1541 if (Tok.is(tok::kw_co_await))
1542 CoawaitLoc = ConsumeToken();
1544 if (Tok.isNot(tok::l_paren)) {
1545 Diag(Tok, diag::err_expected_lparen_after) << "for";
1546 SkipUntil(tok::semi);
1550 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1551 getLangOpts().ObjC1;
1553 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1554 // the case for C90. Start the loop scope.
1557 // A name introduced by a declaration in a condition is in scope from its
1558 // point of declaration until the end of the substatements controlled by the
1561 // Names declared in the for-init-statement, and in the condition of if,
1562 // while, for, and switch statements are local to the if, while, for, or
1563 // switch statement (including the controlled statement).
1565 // Names declared in the for-init-statement are in the same declarative-region
1566 // as those declared in the condition.
1568 unsigned ScopeFlags = 0;
1570 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1572 ParseScope ForScope(this, ScopeFlags);
1574 BalancedDelimiterTracker T(*this, tok::l_paren);
1579 bool ForEach = false, ForRange = false;
1580 StmtResult FirstPart;
1581 Sema::ConditionResult SecondPart;
1582 ExprResult Collection;
1583 ForRangeInit ForRangeInit;
1584 FullExprArg ThirdPart(Actions);
1586 if (Tok.is(tok::code_completion)) {
1587 Actions.CodeCompleteOrdinaryName(getCurScope(),
1588 C99orCXXorObjC? Sema::PCC_ForInit
1589 : Sema::PCC_Expression);
1594 ParsedAttributesWithRange attrs(AttrFactory);
1595 MaybeParseCXX11Attributes(attrs);
1597 // Parse the first part of the for specifier.
1598 if (Tok.is(tok::semi)) { // for (;
1599 ProhibitAttributes(attrs);
1600 // no first part, eat the ';'.
1602 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1603 isForRangeIdentifier()) {
1604 ProhibitAttributes(attrs);
1605 IdentifierInfo *Name = Tok.getIdentifierInfo();
1606 SourceLocation Loc = ConsumeToken();
1607 MaybeParseCXX11Attributes(attrs);
1609 ForRangeInit.ColonLoc = ConsumeToken();
1610 if (Tok.is(tok::l_brace))
1611 ForRangeInit.RangeExpr = ParseBraceInitializer();
1613 ForRangeInit.RangeExpr = ParseExpression();
1615 Diag(Loc, diag::err_for_range_identifier)
1616 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
1617 ? FixItHint::CreateInsertion(Loc, "auto &&")
1620 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1621 attrs, attrs.Range.getEnd());
1623 } else if (isForInitDeclaration()) { // for (int X = 4;
1624 // Parse declaration, which eats the ';'.
1625 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1626 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1628 // In C++0x, "for (T NS:a" might not be a typo for ::
1629 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1630 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1632 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1633 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1634 DeclaratorContext::ForContext, DeclEnd, attrs, false,
1635 MightBeForRangeStmt ? &ForRangeInit : nullptr);
1636 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1637 if (ForRangeInit.ParsedForRangeDecl()) {
1638 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1639 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1642 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1644 } else if ((ForEach = isTokIdentifier_in())) {
1645 Actions.ActOnForEachDeclStmt(DG);
1646 // ObjC: for (id x in expr)
1647 ConsumeToken(); // consume 'in'
1649 if (Tok.is(tok::code_completion)) {
1650 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1654 Collection = ParseExpression();
1656 Diag(Tok, diag::err_expected_semi_for);
1659 ProhibitAttributes(attrs);
1660 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1662 ForEach = isTokIdentifier_in();
1664 // Turn the expression into a stmt.
1665 if (!Value.isInvalid()) {
1667 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1669 FirstPart = Actions.ActOnExprStmt(Value);
1672 if (Tok.is(tok::semi)) {
1674 } else if (ForEach) {
1675 ConsumeToken(); // consume 'in'
1677 if (Tok.is(tok::code_completion)) {
1678 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1682 Collection = ParseExpression();
1683 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1684 // User tried to write the reasonable, but ill-formed, for-range-statement
1685 // for (expr : expr) { ... }
1686 Diag(Tok, diag::err_for_range_expected_decl)
1687 << FirstPart.get()->getSourceRange();
1688 SkipUntil(tok::r_paren, StopBeforeMatch);
1689 SecondPart = Sema::ConditionError();
1691 if (!Value.isInvalid()) {
1692 Diag(Tok, diag::err_expected_semi_for);
1694 // Skip until semicolon or rparen, don't consume it.
1695 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1696 if (Tok.is(tok::semi))
1702 // Parse the second part of the for specifier.
1703 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1704 if (!ForEach && !ForRange && !SecondPart.isInvalid()) {
1705 // Parse the second part of the for specifier.
1706 if (Tok.is(tok::semi)) { // for (...;;
1708 } else if (Tok.is(tok::r_paren)) {
1709 // missing both semicolons.
1711 if (getLangOpts().CPlusPlus)
1713 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean);
1715 ExprResult SecondExpr = ParseExpression();
1716 if (SecondExpr.isInvalid())
1717 SecondPart = Sema::ConditionError();
1720 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1721 Sema::ConditionKind::Boolean);
1725 if (Tok.isNot(tok::semi)) {
1726 if (!SecondPart.isInvalid())
1727 Diag(Tok, diag::err_expected_semi_for);
1729 // Skip until semicolon or rparen, don't consume it.
1730 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1733 if (Tok.is(tok::semi)) {
1737 // Parse the third part of the for specifier.
1738 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1739 ExprResult Third = ParseExpression();
1740 // FIXME: The C++11 standard doesn't actually say that this is a
1741 // discarded-value expression, but it clearly should be.
1742 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1748 // C++ Coroutines [stmt.iter]:
1749 // 'co_await' can only be used for a range-based for statement.
1750 if (CoawaitLoc.isValid() && !ForRange) {
1751 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1752 CoawaitLoc = SourceLocation();
1755 // We need to perform most of the semantic analysis for a C++0x for-range
1756 // statememt before parsing the body, in order to be able to deduce the type
1757 // of an auto-typed loop variable.
1758 StmtResult ForRangeStmt;
1759 StmtResult ForEachStmt;
1762 ExprResult CorrectedRange =
1763 Actions.CorrectDelayedTyposInExpr(ForRangeInit.RangeExpr.get());
1764 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1765 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1766 ForRangeInit.ColonLoc, CorrectedRange.get(),
1767 T.getCloseLocation(), Sema::BFRK_Build);
1769 // Similarly, we need to do the semantic analysis for a for-range
1770 // statement immediately in order to close over temporaries correctly.
1771 } else if (ForEach) {
1772 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1775 T.getCloseLocation());
1777 // In OpenMP loop region loop control variable must be captured and be
1778 // private. Perform analysis of first part (if any).
1779 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1780 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1784 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1785 // there is no compound stmt. C90 does not have this clause. We only do this
1786 // if the body isn't a compound statement to avoid push/pop in common cases.
1789 // The substatement in an iteration-statement implicitly defines a local scope
1790 // which is entered and exited each time through the loop.
1792 // See comments in ParseIfStatement for why we create a scope for
1793 // for-init-statement/condition and a new scope for substatement in C++.
1795 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1796 Tok.is(tok::l_brace));
1798 // The body of the for loop has the same local mangling number as the
1799 // for-init-statement.
1800 // It will only be incremented if the body contains other things that would
1801 // normally increment the mangling number (like a compound statement).
1803 getCurScope()->decrementMSManglingNumber();
1805 // Read the body statement.
1806 StmtResult Body(ParseStatement(TrailingElseLoc));
1808 // Pop the body scope if needed.
1811 // Leave the for-scope.
1814 if (Body.isInvalid())
1818 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1822 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1824 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1825 SecondPart, ThirdPart, T.getCloseLocation(),
1829 /// ParseGotoStatement
1831 /// 'goto' identifier ';'
1832 /// [GNU] 'goto' '*' expression ';'
1834 /// Note: this lets the caller parse the end ';'.
1836 StmtResult Parser::ParseGotoStatement() {
1837 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1838 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1841 if (Tok.is(tok::identifier)) {
1842 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1844 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1846 } else if (Tok.is(tok::star)) {
1847 // GNU indirect goto extension.
1848 Diag(Tok, diag::ext_gnu_indirect_goto);
1849 SourceLocation StarLoc = ConsumeToken();
1850 ExprResult R(ParseExpression());
1851 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1852 SkipUntil(tok::semi, StopBeforeMatch);
1855 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1857 Diag(Tok, diag::err_expected) << tok::identifier;
1864 /// ParseContinueStatement
1868 /// Note: this lets the caller parse the end ';'.
1870 StmtResult Parser::ParseContinueStatement() {
1871 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1872 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1875 /// ParseBreakStatement
1879 /// Note: this lets the caller parse the end ';'.
1881 StmtResult Parser::ParseBreakStatement() {
1882 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1883 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1886 /// ParseReturnStatement
1888 /// 'return' expression[opt] ';'
1889 /// 'return' braced-init-list ';'
1890 /// 'co_return' expression[opt] ';'
1891 /// 'co_return' braced-init-list ';'
1892 StmtResult Parser::ParseReturnStatement() {
1893 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1894 "Not a return stmt!");
1895 bool IsCoreturn = Tok.is(tok::kw_co_return);
1896 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1899 if (Tok.isNot(tok::semi)) {
1900 // FIXME: Code completion for co_return.
1901 if (Tok.is(tok::code_completion) && !IsCoreturn) {
1902 Actions.CodeCompleteReturn(getCurScope());
1907 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1908 R = ParseInitializer();
1910 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1911 diag::warn_cxx98_compat_generalized_initializer_lists :
1912 diag::ext_generalized_initializer_lists)
1913 << R.get()->getSourceRange();
1915 R = ParseExpression();
1916 if (R.isInvalid()) {
1917 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1922 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
1923 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1926 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1927 AllowedConstructsKind Allowed,
1928 SourceLocation *TrailingElseLoc,
1929 ParsedAttributesWithRange &Attrs) {
1930 // Create temporary attribute list.
1931 ParsedAttributesWithRange TempAttrs(AttrFactory);
1933 // Get loop hints and consume annotated token.
1934 while (Tok.is(tok::annot_pragma_loop_hint)) {
1936 if (!HandlePragmaLoopHint(Hint))
1939 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1940 ArgsUnion(Hint.ValueExpr)};
1941 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1942 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1943 AttributeList::AS_Pragma);
1946 // Get the next statement.
1947 MaybeParseCXX11Attributes(Attrs);
1949 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1950 Stmts, Allowed, TrailingElseLoc, Attrs);
1952 Attrs.takeAllFrom(TempAttrs);
1956 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1957 assert(Tok.is(tok::l_brace));
1958 SourceLocation LBraceLoc = Tok.getLocation();
1960 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1961 "parsing function body");
1963 // Save and reset current vtordisp stack if we have entered a C++ method body.
1965 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1966 Sema::PragmaStackSentinelRAII
1967 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1969 // Do not enter a scope for the brace, as the arguments are in the same scope
1970 // (the function body) as the body itself. Instead, just read the statement
1971 // list and put it into a CompoundStmt for safe keeping.
1972 StmtResult FnBody(ParseCompoundStatementBody());
1974 // If the function body could not be parsed, make a bogus compoundstmt.
1975 if (FnBody.isInvalid()) {
1976 Sema::CompoundScopeRAII CompoundScope(Actions);
1977 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1981 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1984 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1986 /// function-try-block:
1987 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1989 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1990 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1991 SourceLocation TryLoc = ConsumeToken();
1993 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1994 "parsing function try block");
1996 // Constructor initializer list?
1997 if (Tok.is(tok::colon))
1998 ParseConstructorInitializer(Decl);
2000 Actions.ActOnDefaultCtorInitializers(Decl);
2002 // Save and reset current vtordisp stack if we have entered a C++ method body.
2004 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2005 Sema::PragmaStackSentinelRAII
2006 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2008 SourceLocation LBraceLoc = Tok.getLocation();
2009 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2010 // If we failed to parse the try-catch, we just give the function an empty
2011 // compound statement as the body.
2012 if (FnBody.isInvalid()) {
2013 Sema::CompoundScopeRAII CompoundScope(Actions);
2014 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2018 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2021 bool Parser::trySkippingFunctionBody() {
2022 assert(SkipFunctionBodies &&
2023 "Should only be called when SkipFunctionBodies is enabled");
2024 if (!PP.isCodeCompletionEnabled()) {
2029 // We're in code-completion mode. Skip parsing for all function bodies unless
2030 // the body contains the code-completion point.
2031 TentativeParsingAction PA(*this);
2032 bool IsTryCatch = Tok.is(tok::kw_try);
2034 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2035 if (llvm::any_of(Toks, [](const Token &Tok) {
2036 return Tok.is(tok::code_completion);
2041 if (ErrorInPrologue) {
2043 SkipMalformedDecl();
2046 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2050 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2051 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2052 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2061 /// ParseCXXTryBlock - Parse a C++ try-block.
2064 /// 'try' compound-statement handler-seq
2066 StmtResult Parser::ParseCXXTryBlock() {
2067 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2069 SourceLocation TryLoc = ConsumeToken();
2070 return ParseCXXTryBlockCommon(TryLoc);
2073 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2074 /// function-try-block.
2077 /// 'try' compound-statement handler-seq
2079 /// function-try-block:
2080 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2083 /// handler handler-seq[opt]
2085 /// [Borland] try-block:
2086 /// 'try' compound-statement seh-except-block
2087 /// 'try' compound-statement seh-finally-block
2089 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2090 if (Tok.isNot(tok::l_brace))
2091 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2093 StmtResult TryBlock(ParseCompoundStatement(
2094 /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2095 Scope::CompoundStmtScope |
2096 (FnTry ? Scope::FnTryCatchScope : 0)));
2097 if (TryBlock.isInvalid())
2100 // Borland allows SEH-handlers with 'try'
2102 if ((Tok.is(tok::identifier) &&
2103 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2104 Tok.is(tok::kw___finally)) {
2105 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2107 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2108 SourceLocation Loc = ConsumeToken();
2109 Handler = ParseSEHExceptBlock(Loc);
2112 SourceLocation Loc = ConsumeToken();
2113 Handler = ParseSEHFinallyBlock(Loc);
2115 if(Handler.isInvalid())
2118 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2124 StmtVector Handlers;
2126 // C++11 attributes can't appear here, despite this context seeming
2128 DiagnoseAndSkipCXX11Attributes();
2130 if (Tok.isNot(tok::kw_catch))
2131 return StmtError(Diag(Tok, diag::err_expected_catch));
2132 while (Tok.is(tok::kw_catch)) {
2133 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2134 if (!Handler.isInvalid())
2135 Handlers.push_back(Handler.get());
2137 // Don't bother creating the full statement if we don't have any usable
2139 if (Handlers.empty())
2142 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2146 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2149 /// 'catch' '(' exception-declaration ')' compound-statement
2151 /// exception-declaration:
2152 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2153 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2156 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2157 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2159 SourceLocation CatchLoc = ConsumeToken();
2161 BalancedDelimiterTracker T(*this, tok::l_paren);
2162 if (T.expectAndConsume())
2166 // The name in a catch exception-declaration is local to the handler and
2167 // shall not be redeclared in the outermost block of the handler.
2168 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2169 (FnCatch ? Scope::FnTryCatchScope : 0));
2171 // exception-declaration is equivalent to '...' or a parameter-declaration
2172 // without default arguments.
2173 Decl *ExceptionDecl = nullptr;
2174 if (Tok.isNot(tok::ellipsis)) {
2175 ParsedAttributesWithRange Attributes(AttrFactory);
2176 MaybeParseCXX11Attributes(Attributes);
2178 DeclSpec DS(AttrFactory);
2179 DS.takeAttributesFrom(Attributes);
2181 if (ParseCXXTypeSpecifierSeq(DS))
2184 Declarator ExDecl(DS, DeclaratorContext::CXXCatchContext);
2185 ParseDeclarator(ExDecl);
2186 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2191 if (T.getCloseLocation().isInvalid())
2194 if (Tok.isNot(tok::l_brace))
2195 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2197 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2198 StmtResult Block(ParseCompoundStatement());
2199 if (Block.isInvalid())
2202 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2205 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2206 IfExistsCondition Result;
2207 if (ParseMicrosoftIfExistsCondition(Result))
2210 // Handle dependent statements by parsing the braces as a compound statement.
2211 // This is not the same behavior as Visual C++, which don't treat this as a
2212 // compound statement, but for Clang's type checking we can't have anything
2213 // inside these braces escaping to the surrounding code.
2214 if (Result.Behavior == IEB_Dependent) {
2215 if (!Tok.is(tok::l_brace)) {
2216 Diag(Tok, diag::err_expected) << tok::l_brace;
2220 StmtResult Compound = ParseCompoundStatement();
2221 if (Compound.isInvalid())
2224 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2229 if (DepResult.isUsable())
2230 Stmts.push_back(DepResult.get());
2234 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2235 if (Braces.consumeOpen()) {
2236 Diag(Tok, diag::err_expected) << tok::l_brace;
2240 switch (Result.Behavior) {
2242 // Parse the statements below.
2246 llvm_unreachable("Dependent case handled above");
2253 // Condition is true, parse the statements.
2254 while (Tok.isNot(tok::r_brace)) {
2255 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2257 Stmts.push_back(R.get());
2259 Braces.consumeClose();
2262 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2263 MaybeParseGNUAttributes(Attrs);
2268 if (Attrs.getList()->getKind() != AttributeList::AT_OpenCLUnrollHint)
2271 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2272 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);