1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Statement and Block portions of the Parser
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/PrettyDeclStackTrace.h"
15 #include "clang/Basic/Attributes.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Parse/LoopHint.h"
18 #include "clang/Parse/Parser.h"
19 #include "clang/Parse/RAIIObjectsForParser.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/Scope.h"
22 #include "clang/Sema/TypoCorrection.h"
23 using namespace clang;
25 //===----------------------------------------------------------------------===//
26 // C99 6.8: Statements and Blocks.
27 //===----------------------------------------------------------------------===//
29 /// Parse a standalone statement (for instance, as the body of an 'if',
30 /// 'while', or 'for').
31 StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
32 ParsedStmtContext StmtCtx) {
35 // We may get back a null statement if we found a #pragma. Keep going until
36 // we get an actual statement.
39 Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);
40 } while (!Res.isInvalid() && !Res.get());
45 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
46 /// StatementOrDeclaration:
52 /// compound-statement
53 /// expression-statement
54 /// selection-statement
55 /// iteration-statement
57 /// [C++] declaration-statement
59 /// [MS] seh-try-block
60 /// [OBC] objc-throw-statement
61 /// [OBC] objc-try-catch-statement
62 /// [OBC] objc-synchronized-statement
63 /// [GNU] asm-statement
64 /// [OMP] openmp-construct [TODO]
66 /// labeled-statement:
67 /// identifier ':' statement
68 /// 'case' constant-expression ':' statement
69 /// 'default' ':' statement
71 /// selection-statement:
75 /// iteration-statement:
80 /// expression-statement:
81 /// expression[opt] ';'
84 /// 'goto' identifier ';'
87 /// 'return' expression[opt] ';'
88 /// [GNU] 'goto' '*' expression ';'
90 /// [OBC] objc-throw-statement:
91 /// [OBC] '@' 'throw' expression ';'
92 /// [OBC] '@' 'throw' ';'
95 Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
96 ParsedStmtContext StmtCtx,
97 SourceLocation *TrailingElseLoc) {
99 ParenBraceBracketBalancer BalancerRAIIObj(*this);
101 ParsedAttributesWithRange Attrs(AttrFactory);
102 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
103 if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
106 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
107 Stmts, StmtCtx, TrailingElseLoc, Attrs);
109 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
110 "attributes on empty statement");
112 if (Attrs.empty() || Res.isInvalid())
115 return Actions.ProcessStmtAttributes(Res.get(), Attrs, Attrs.Range);
119 class StatementFilterCCC final : public CorrectionCandidateCallback {
121 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
122 WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
123 tok::identifier, tok::star, tok::amp);
124 WantExpressionKeywords =
125 nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
126 WantRemainingKeywords =
127 nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
128 WantCXXNamedCasts = false;
131 bool ValidateCandidate(const TypoCorrection &candidate) override {
132 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
133 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
134 if (NextToken.is(tok::equal))
135 return candidate.getCorrectionDeclAs<VarDecl>();
136 if (NextToken.is(tok::period) &&
137 candidate.getCorrectionDeclAs<NamespaceDecl>())
139 return CorrectionCandidateCallback::ValidateCandidate(candidate);
142 std::unique_ptr<CorrectionCandidateCallback> clone() override {
143 return llvm::make_unique<StatementFilterCCC>(*this);
151 StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
152 StmtVector &Stmts, ParsedStmtContext StmtCtx,
153 SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs) {
154 const char *SemiError = nullptr;
157 // Cases in this switch statement should fall through if the parser expects
158 // the token to end in a semicolon (in which case SemiError should be set),
159 // or they directly 'return;' if not.
161 tok::TokenKind Kind = Tok.getKind();
162 SourceLocation AtLoc;
164 case tok::at: // May be a @try or @throw statement
166 ProhibitAttributes(Attrs); // TODO: is it correct?
167 AtLoc = ConsumeToken(); // consume @
168 return ParseObjCAtStatement(AtLoc, StmtCtx);
171 case tok::code_completion:
172 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
176 case tok::identifier: {
177 Token Next = NextToken();
178 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
179 // identifier ':' statement
180 return ParseLabeledStatement(Attrs, StmtCtx);
183 // Look up the identifier, and typo-correct it to a keyword if it's not
185 if (Next.isNot(tok::coloncolon)) {
186 // Try to limit which sets of keywords should be included in typo
187 // correction based on what the next token is.
188 StatementFilterCCC CCC(Next);
189 if (TryAnnotateName(/*IsAddressOfOperand*/ false, &CCC) == ANK_Error) {
190 // Handle errors here by skipping up to the next semicolon or '}', and
191 // eat the semicolon if that's what stopped us.
192 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
193 if (Tok.is(tok::semi))
198 // If the identifier was typo-corrected, try again.
199 if (Tok.isNot(tok::identifier))
208 if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
209 (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
210 ParsedStmtContext()) &&
211 isDeclarationStatement()) {
212 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
213 DeclGroupPtrTy Decl = ParseDeclaration(DeclaratorContext::BlockContext,
215 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
218 if (Tok.is(tok::r_brace)) {
219 Diag(Tok, diag::err_expected_statement);
223 return ParseExprStatement(StmtCtx);
226 case tok::kw_case: // C99 6.8.1: labeled-statement
227 return ParseCaseStatement(StmtCtx);
228 case tok::kw_default: // C99 6.8.1: labeled-statement
229 return ParseDefaultStatement(StmtCtx);
231 case tok::l_brace: // C99 6.8.2: compound-statement
232 return ParseCompoundStatement();
233 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
234 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
235 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
238 case tok::kw_if: // C99 6.8.4.1: if-statement
239 return ParseIfStatement(TrailingElseLoc);
240 case tok::kw_switch: // C99 6.8.4.2: switch-statement
241 return ParseSwitchStatement(TrailingElseLoc);
243 case tok::kw_while: // C99 6.8.5.1: while-statement
244 return ParseWhileStatement(TrailingElseLoc);
245 case tok::kw_do: // C99 6.8.5.2: do-statement
246 Res = ParseDoStatement();
247 SemiError = "do/while";
249 case tok::kw_for: // C99 6.8.5.3: for-statement
250 return ParseForStatement(TrailingElseLoc);
252 case tok::kw_goto: // C99 6.8.6.1: goto-statement
253 Res = ParseGotoStatement();
256 case tok::kw_continue: // C99 6.8.6.2: continue-statement
257 Res = ParseContinueStatement();
258 SemiError = "continue";
260 case tok::kw_break: // C99 6.8.6.3: break-statement
261 Res = ParseBreakStatement();
264 case tok::kw_return: // C99 6.8.6.4: return-statement
265 Res = ParseReturnStatement();
266 SemiError = "return";
268 case tok::kw_co_return: // C++ Coroutines: co_return statement
269 Res = ParseReturnStatement();
270 SemiError = "co_return";
274 ProhibitAttributes(Attrs);
276 Res = ParseAsmStatement(msAsm);
277 Res = Actions.ActOnFinishFullStmt(Res.get());
278 if (msAsm) return Res;
283 case tok::kw___if_exists:
284 case tok::kw___if_not_exists:
285 ProhibitAttributes(Attrs);
286 ParseMicrosoftIfExistsStatement(Stmts);
287 // An __if_exists block is like a compound statement, but it doesn't create
291 case tok::kw_try: // C++ 15: try-block
292 return ParseCXXTryBlock();
295 ProhibitAttributes(Attrs); // TODO: is it correct?
296 return ParseSEHTryBlock();
298 case tok::kw___leave:
299 Res = ParseSEHLeaveStatement();
300 SemiError = "__leave";
303 case tok::annot_pragma_vis:
304 ProhibitAttributes(Attrs);
305 HandlePragmaVisibility();
308 case tok::annot_pragma_pack:
309 ProhibitAttributes(Attrs);
313 case tok::annot_pragma_msstruct:
314 ProhibitAttributes(Attrs);
315 HandlePragmaMSStruct();
318 case tok::annot_pragma_align:
319 ProhibitAttributes(Attrs);
323 case tok::annot_pragma_weak:
324 ProhibitAttributes(Attrs);
328 case tok::annot_pragma_weakalias:
329 ProhibitAttributes(Attrs);
330 HandlePragmaWeakAlias();
333 case tok::annot_pragma_redefine_extname:
334 ProhibitAttributes(Attrs);
335 HandlePragmaRedefineExtname();
338 case tok::annot_pragma_fp_contract:
339 ProhibitAttributes(Attrs);
340 Diag(Tok, diag::err_pragma_fp_contract_scope);
341 ConsumeAnnotationToken();
344 case tok::annot_pragma_fp:
345 ProhibitAttributes(Attrs);
346 Diag(Tok, diag::err_pragma_fp_scope);
347 ConsumeAnnotationToken();
350 case tok::annot_pragma_fenv_access:
351 ProhibitAttributes(Attrs);
352 HandlePragmaFEnvAccess();
355 case tok::annot_pragma_opencl_extension:
356 ProhibitAttributes(Attrs);
357 HandlePragmaOpenCLExtension();
360 case tok::annot_pragma_captured:
361 ProhibitAttributes(Attrs);
362 return HandlePragmaCaptured();
364 case tok::annot_pragma_openmp:
365 ProhibitAttributes(Attrs);
366 return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
368 case tok::annot_pragma_ms_pointers_to_members:
369 ProhibitAttributes(Attrs);
370 HandlePragmaMSPointersToMembers();
373 case tok::annot_pragma_ms_pragma:
374 ProhibitAttributes(Attrs);
375 HandlePragmaMSPragma();
378 case tok::annot_pragma_ms_vtordisp:
379 ProhibitAttributes(Attrs);
380 HandlePragmaMSVtorDisp();
383 case tok::annot_pragma_loop_hint:
384 ProhibitAttributes(Attrs);
385 return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, Attrs);
387 case tok::annot_pragma_dump:
391 case tok::annot_pragma_attribute:
392 HandlePragmaAttribute();
396 // If we reached this code, the statement must end in a semicolon.
397 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
398 // If the result was valid, then we do want to diagnose this. Use
399 // ExpectAndConsume to emit the diagnostic, even though we know it won't
401 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
402 // Skip until we see a } or ;, but don't eat it.
403 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
409 /// Parse an expression statement.
410 StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
411 // If a case keyword is missing, this is where it should be inserted.
412 Token OldToken = Tok;
414 ExprStatementTokLoc = Tok.getLocation();
416 // expression[opt] ';'
417 ExprResult Expr(ParseExpression());
418 if (Expr.isInvalid()) {
419 // If the expression is invalid, skip ahead to the next semicolon or '}'.
420 // Not doing this opens us up to the possibility of infinite loops if
421 // ParseExpression does not consume any tokens.
422 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
423 if (Tok.is(tok::semi))
425 return Actions.ActOnExprStmtError();
428 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
429 Actions.CheckCaseExpression(Expr.get())) {
430 // If a constant expression is followed by a colon inside a switch block,
431 // suggest a missing case keyword.
432 Diag(OldToken, diag::err_expected_case_before_expression)
433 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
435 // Recover parsing as a case statement.
436 return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
439 // Otherwise, eat the semicolon.
440 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
441 return handleExprStmt(Expr, StmtCtx);
444 /// ParseSEHTryBlockCommon
447 /// '__try' compound-statement seh-handler
451 /// seh-finally-block
453 StmtResult Parser::ParseSEHTryBlock() {
454 assert(Tok.is(tok::kw___try) && "Expected '__try'");
455 SourceLocation TryLoc = ConsumeToken();
457 if (Tok.isNot(tok::l_brace))
458 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
460 StmtResult TryBlock(ParseCompoundStatement(
461 /*isStmtExpr=*/false,
462 Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
463 if (TryBlock.isInvalid())
467 if (Tok.is(tok::identifier) &&
468 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
469 SourceLocation Loc = ConsumeToken();
470 Handler = ParseSEHExceptBlock(Loc);
471 } else if (Tok.is(tok::kw___finally)) {
472 SourceLocation Loc = ConsumeToken();
473 Handler = ParseSEHFinallyBlock(Loc);
475 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
478 if(Handler.isInvalid())
481 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
487 /// ParseSEHExceptBlock - Handle __except
489 /// seh-except-block:
490 /// '__except' '(' seh-filter-expression ')' compound-statement
492 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
493 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
494 raii2(Ident___exception_code, false),
495 raii3(Ident_GetExceptionCode, false);
497 if (ExpectAndConsume(tok::l_paren))
500 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
501 Scope::SEHExceptScope);
503 if (getLangOpts().Borland) {
504 Ident__exception_info->setIsPoisoned(false);
505 Ident___exception_info->setIsPoisoned(false);
506 Ident_GetExceptionInfo->setIsPoisoned(false);
509 ExprResult FilterExpr;
511 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
512 Scope::SEHFilterScope);
513 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
516 if (getLangOpts().Borland) {
517 Ident__exception_info->setIsPoisoned(true);
518 Ident___exception_info->setIsPoisoned(true);
519 Ident_GetExceptionInfo->setIsPoisoned(true);
522 if(FilterExpr.isInvalid())
525 if (ExpectAndConsume(tok::r_paren))
528 if (Tok.isNot(tok::l_brace))
529 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
531 StmtResult Block(ParseCompoundStatement());
533 if(Block.isInvalid())
536 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
539 /// ParseSEHFinallyBlock - Handle __finally
541 /// seh-finally-block:
542 /// '__finally' compound-statement
544 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
545 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
546 raii2(Ident___abnormal_termination, false),
547 raii3(Ident_AbnormalTermination, false);
549 if (Tok.isNot(tok::l_brace))
550 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
552 ParseScope FinallyScope(this, 0);
553 Actions.ActOnStartSEHFinallyBlock();
555 StmtResult Block(ParseCompoundStatement());
556 if(Block.isInvalid()) {
557 Actions.ActOnAbortSEHFinallyBlock();
561 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
566 /// seh-leave-statement:
569 StmtResult Parser::ParseSEHLeaveStatement() {
570 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
571 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
574 /// ParseLabeledStatement - We have an identifier and a ':' after it.
576 /// labeled-statement:
577 /// identifier ':' statement
578 /// [GNU] identifier ':' attributes[opt] statement
580 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs,
581 ParsedStmtContext StmtCtx) {
582 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
583 "Not an identifier!");
585 // The substatement is always a 'statement', not a 'declaration', but is
586 // otherwise in the same context as the labeled-statement.
587 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
589 Token IdentTok = Tok; // Save the whole token.
590 ConsumeToken(); // eat the identifier.
592 assert(Tok.is(tok::colon) && "Not a label!");
594 // identifier ':' statement
595 SourceLocation ColonLoc = ConsumeToken();
597 // Read label attributes, if present.
599 if (Tok.is(tok::kw___attribute)) {
600 ParsedAttributesWithRange TempAttrs(AttrFactory);
601 ParseGNUAttributes(TempAttrs);
603 // In C++, GNU attributes only apply to the label if they are followed by a
604 // semicolon, to disambiguate label attributes from attributes on a labeled
607 // This doesn't quite match what GCC does; if the attribute list is empty
608 // and followed by a semicolon, GCC will reject (it appears to parse the
609 // attributes as part of a statement in that case). That looks like a bug.
610 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
611 attrs.takeAllFrom(TempAttrs);
612 else if (isDeclarationStatement()) {
614 // FIXME: We should do this whether or not we have a declaration
615 // statement, but that doesn't work correctly (because ProhibitAttributes
616 // can't handle GNU attributes), so only call it in the one case where
617 // GNU attributes are allowed.
618 SubStmt = ParseStatementOrDeclarationAfterAttributes(Stmts, StmtCtx,
620 if (!TempAttrs.empty() && !SubStmt.isInvalid())
621 SubStmt = Actions.ProcessStmtAttributes(SubStmt.get(), TempAttrs,
624 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
628 // If we've not parsed a statement yet, parse one now.
629 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
630 SubStmt = ParseStatement(nullptr, StmtCtx);
632 // Broken substmt shouldn't prevent the label from being added to the AST.
633 if (SubStmt.isInvalid())
634 SubStmt = Actions.ActOnNullStmt(ColonLoc);
636 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
637 IdentTok.getLocation());
638 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, attrs);
641 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
645 /// ParseCaseStatement
646 /// labeled-statement:
647 /// 'case' constant-expression ':' statement
648 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
650 StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
651 bool MissingCase, ExprResult Expr) {
652 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
654 // The substatement is always a 'statement', not a 'declaration', but is
655 // otherwise in the same context as the labeled-statement.
656 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
658 // It is very very common for code to contain many case statements recursively
659 // nested, as in (but usually without indentation):
666 // Parsing this naively works, but is both inefficient and can cause us to run
667 // out of stack space in our recursive descent parser. As a special case,
668 // flatten this recursion into an iterative loop. This is complex and gross,
669 // but all the grossness is constrained to ParseCaseStatement (and some
670 // weirdness in the actions), so this is just local grossness :).
672 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
674 StmtResult TopLevelCase(true);
676 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
677 // gets updated each time a new case is parsed, and whose body is unset so
678 // far. When parsing 'case 4', this is the 'case 3' node.
679 Stmt *DeepestParsedCaseStmt = nullptr;
681 // While we have case statements, eat and stack them.
682 SourceLocation ColonLoc;
684 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
685 ConsumeToken(); // eat the 'case'.
686 ColonLoc = SourceLocation();
688 if (Tok.is(tok::code_completion)) {
689 Actions.CodeCompleteCase(getCurScope());
694 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
695 /// Disable this form of error recovery while we're parsing the case
697 ColonProtectionRAIIObject ColonProtection(*this);
701 LHS = ParseCaseExpression(CaseLoc);
702 if (LHS.isInvalid()) {
703 // If constant-expression is parsed unsuccessfully, recover by skipping
704 // current case statement (moving to the colon that ends it).
705 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
713 // GNU case range extension.
714 SourceLocation DotDotDotLoc;
716 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
717 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
718 RHS = ParseCaseExpression(CaseLoc);
719 if (RHS.isInvalid()) {
720 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
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, DotDotDotLoc, RHS, 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, StmtCtx);
750 // Otherwise, just don't add it as a nested case.
752 // If this is the first case statement we parsed, it becomes TopLevelCase.
753 // Otherwise we link it into the current chain.
754 Stmt *NextDeepest = Case.get();
755 if (TopLevelCase.isInvalid())
758 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
759 DeepestParsedCaseStmt = NextDeepest;
762 // Handle all case statements.
763 } while (Tok.is(tok::kw_case));
765 // If we found a non-case statement, start by parsing it.
768 if (Tok.isNot(tok::r_brace)) {
769 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
771 // Nicely diagnose the common error "switch (X) { case 4: }", which is
772 // not valid. If ColonLoc doesn't point to a valid text location, there was
773 // another parsing error, so avoid producing extra diagnostics.
774 if (ColonLoc.isValid()) {
775 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
776 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
777 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
779 SubStmt = StmtError();
782 // Install the body into the most deeply-nested case.
783 if (DeepestParsedCaseStmt) {
784 // Broken sub-stmt shouldn't prevent forming the case statement properly.
785 if (SubStmt.isInvalid())
786 SubStmt = Actions.ActOnNullStmt(SourceLocation());
787 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
790 // Return the top level parsed statement tree.
794 /// ParseDefaultStatement
795 /// labeled-statement:
796 /// 'default' ':' statement
797 /// Note that this does not parse the 'statement' at the end.
799 StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
800 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
802 // The substatement is always a 'statement', not a 'declaration', but is
803 // otherwise in the same context as the labeled-statement.
804 StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
806 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
808 SourceLocation ColonLoc;
809 if (TryConsumeToken(tok::colon, ColonLoc)) {
810 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
811 // Treat "default;" as a typo for "default:".
812 Diag(ColonLoc, diag::err_expected_after)
813 << "'default'" << tok::colon
814 << FixItHint::CreateReplacement(ColonLoc, ":");
816 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
817 Diag(ExpectedLoc, diag::err_expected_after)
818 << "'default'" << tok::colon
819 << FixItHint::CreateInsertion(ExpectedLoc, ":");
820 ColonLoc = ExpectedLoc;
825 if (Tok.isNot(tok::r_brace)) {
826 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
828 // Diagnose the common error "switch (X) {... default: }", which is
830 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
831 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
832 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
836 // Broken sub-stmt shouldn't prevent forming the case statement properly.
837 if (SubStmt.isInvalid())
838 SubStmt = Actions.ActOnNullStmt(ColonLoc);
840 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
841 SubStmt.get(), getCurScope());
844 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
845 return ParseCompoundStatement(isStmtExpr,
846 Scope::DeclScope | Scope::CompoundStmtScope);
849 /// ParseCompoundStatement - Parse a "{}" block.
851 /// compound-statement: [C99 6.8.2]
852 /// { block-item-list[opt] }
853 /// [GNU] { label-declarations block-item-list } [TODO]
857 /// block-item-list block-item
861 /// [GNU] '__extension__' declaration
864 /// [GNU] label-declarations:
865 /// [GNU] label-declaration
866 /// [GNU] label-declarations label-declaration
868 /// [GNU] label-declaration:
869 /// [GNU] '__label__' identifier-list ';'
871 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
872 unsigned ScopeFlags) {
873 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
875 // Enter a scope to hold everything within the compound stmt. Compound
876 // statements can always hold declarations.
877 ParseScope CompoundScope(this, ScopeFlags);
879 // Parse the statements in the body.
880 return ParseCompoundStatementBody(isStmtExpr);
883 /// Parse any pragmas at the start of the compound expression. We handle these
884 /// separately since some pragmas (FP_CONTRACT) must appear before any C
885 /// statement in the compound, but may be intermingled with other pragmas.
886 void Parser::ParseCompoundStatementLeadingPragmas() {
887 bool checkForPragmas = true;
888 while (checkForPragmas) {
889 switch (Tok.getKind()) {
890 case tok::annot_pragma_vis:
891 HandlePragmaVisibility();
893 case tok::annot_pragma_pack:
896 case tok::annot_pragma_msstruct:
897 HandlePragmaMSStruct();
899 case tok::annot_pragma_align:
902 case tok::annot_pragma_weak:
905 case tok::annot_pragma_weakalias:
906 HandlePragmaWeakAlias();
908 case tok::annot_pragma_redefine_extname:
909 HandlePragmaRedefineExtname();
911 case tok::annot_pragma_opencl_extension:
912 HandlePragmaOpenCLExtension();
914 case tok::annot_pragma_fp_contract:
915 HandlePragmaFPContract();
917 case tok::annot_pragma_fp:
920 case tok::annot_pragma_fenv_access:
921 HandlePragmaFEnvAccess();
923 case tok::annot_pragma_ms_pointers_to_members:
924 HandlePragmaMSPointersToMembers();
926 case tok::annot_pragma_ms_pragma:
927 HandlePragmaMSPragma();
929 case tok::annot_pragma_ms_vtordisp:
930 HandlePragmaMSVtorDisp();
932 case tok::annot_pragma_dump:
936 checkForPragmas = false;
943 /// Consume any extra semi-colons resulting in null statements,
944 /// returning true if any tok::semi were consumed.
945 bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
946 if (!Tok.is(tok::semi))
949 SourceLocation StartLoc = Tok.getLocation();
950 SourceLocation EndLoc;
952 while (Tok.is(tok::semi) && !Tok.hasLeadingEmptyMacro() &&
953 Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
954 EndLoc = Tok.getLocation();
956 // Don't just ConsumeToken() this tok::semi, do store it in AST.
958 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
960 Stmts.push_back(R.get());
963 // Did not consume any extra semi.
964 if (EndLoc.isInvalid())
967 Diag(StartLoc, diag::warn_null_statement)
968 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
972 StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
973 bool IsStmtExprResult = false;
974 if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
975 // For GCC compatibility we skip past NullStmts.
976 unsigned LookAhead = 0;
977 while (GetLookAheadToken(LookAhead).is(tok::semi)) {
980 // Then look to see if the next two tokens close the statement expression;
981 // if so, this expression statement is the last statement in a statment
983 IsStmtExprResult = GetLookAheadToken(LookAhead).is(tok::r_brace) &&
984 GetLookAheadToken(LookAhead + 1).is(tok::r_paren);
987 if (IsStmtExprResult)
988 E = Actions.ActOnStmtExprResult(E);
989 return Actions.ActOnExprStmt(E, /*DiscardedValue=*/!IsStmtExprResult);
992 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
993 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
994 /// consume the '}' at the end of the block. It does not manipulate the scope
996 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
997 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
999 "in compound statement ('{}')");
1001 // Record the state of the FP_CONTRACT pragma, restore on leaving the
1002 // compound statement.
1003 Sema::FPContractStateRAII SaveFPContractState(Actions);
1005 InMessageExpressionRAIIObject InMessage(*this, false);
1006 BalancedDelimiterTracker T(*this, tok::l_brace);
1007 if (T.consumeOpen())
1010 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
1012 // Parse any pragmas at the beginning of the compound statement.
1013 ParseCompoundStatementLeadingPragmas();
1017 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1018 // only allowed at the start of a compound stmt regardless of the language.
1019 while (Tok.is(tok::kw___label__)) {
1020 SourceLocation LabelLoc = ConsumeToken();
1022 SmallVector<Decl *, 8> DeclsInGroup;
1024 if (Tok.isNot(tok::identifier)) {
1025 Diag(Tok, diag::err_expected) << tok::identifier;
1029 IdentifierInfo *II = Tok.getIdentifierInfo();
1030 SourceLocation IdLoc = ConsumeToken();
1031 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
1033 if (!TryConsumeToken(tok::comma))
1037 DeclSpec DS(AttrFactory);
1038 DeclGroupPtrTy Res =
1039 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1040 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
1042 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
1044 Stmts.push_back(R.get());
1047 ParsedStmtContext SubStmtCtx =
1048 ParsedStmtContext::Compound |
1049 (isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());
1051 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
1052 Tok.isNot(tok::eof)) {
1053 if (Tok.is(tok::annot_pragma_unused)) {
1054 HandlePragmaUnused();
1058 if (ConsumeNullStmt(Stmts))
1062 if (Tok.isNot(tok::kw___extension__)) {
1063 R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
1065 // __extension__ can start declarations and it can also be a unary
1066 // operator for expressions. Consume multiple __extension__ markers here
1067 // until we can determine which is which.
1068 // FIXME: This loses extension expressions in the AST!
1069 SourceLocation ExtLoc = ConsumeToken();
1070 while (Tok.is(tok::kw___extension__))
1073 ParsedAttributesWithRange attrs(AttrFactory);
1074 MaybeParseCXX11Attributes(attrs, nullptr,
1075 /*MightBeObjCMessageSend*/ true);
1077 // If this is the start of a declaration, parse it as such.
1078 if (isDeclarationStatement()) {
1079 // __extension__ silences extension warnings in the subdeclaration.
1080 // FIXME: Save the __extension__ on the decl as a node somehow?
1081 ExtensionRAIIObject O(Diags);
1083 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1084 DeclGroupPtrTy Res =
1085 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, attrs);
1086 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1088 // Otherwise this was a unary __extension__ marker.
1089 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1091 if (Res.isInvalid()) {
1092 SkipUntil(tok::semi);
1096 // Eat the semicolon at the end of stmt and convert the expr into a
1098 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1099 R = handleExprStmt(Res, SubStmtCtx);
1101 R = Actions.ProcessStmtAttributes(R.get(), attrs, attrs.Range);
1106 Stmts.push_back(R.get());
1109 SourceLocation CloseLoc = Tok.getLocation();
1111 // We broke out of the while loop because we found a '}' or EOF.
1112 if (!T.consumeClose())
1113 // Recover by creating a compound statement with what we parsed so far,
1114 // instead of dropping everything and returning StmtError();
1115 CloseLoc = T.getCloseLocation();
1117 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1121 /// ParseParenExprOrCondition:
1122 /// [C ] '(' expression ')'
1123 /// [C++] '(' condition ')'
1124 /// [C++1z] '(' init-statement[opt] condition ')'
1126 /// This function parses and performs error recovery on the specified condition
1127 /// or expression (depending on whether we're in C++ or C mode). This function
1128 /// goes out of its way to recover well. It returns true if there was a parser
1129 /// error (the right paren couldn't be found), which indicates that the caller
1130 /// should try to recover harder. It returns false if the condition is
1131 /// successfully parsed. Note that a successful parse can still have semantic
1132 /// errors in the condition.
1133 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1134 Sema::ConditionResult &Cond,
1136 Sema::ConditionKind CK) {
1137 BalancedDelimiterTracker T(*this, tok::l_paren);
1140 if (getLangOpts().CPlusPlus)
1141 Cond = ParseCXXCondition(InitStmt, Loc, CK);
1143 ExprResult CondExpr = ParseExpression();
1145 // If required, convert to a boolean value.
1146 if (CondExpr.isInvalid())
1147 Cond = Sema::ConditionError();
1149 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1152 // If the parser was confused by the condition and we don't have a ')', try to
1153 // recover by skipping ahead to a semi and bailing out. If condexp is
1154 // semantically invalid but we have well formed code, keep going.
1155 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1156 SkipUntil(tok::semi);
1157 // Skipping may have stopped if it found the containing ')'. If so, we can
1158 // continue parsing the if statement.
1159 if (Tok.isNot(tok::r_paren))
1163 // Otherwise the condition is valid or the rparen is present.
1166 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1167 // that all callers are looking for a statement after the condition, so ")"
1169 while (Tok.is(tok::r_paren)) {
1170 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1171 << FixItHint::CreateRemoval(Tok.getLocation());
1179 /// ParseIfStatement
1180 /// if-statement: [C99 6.8.4.1]
1181 /// 'if' '(' expression ')' statement
1182 /// 'if' '(' expression ')' statement 'else' statement
1183 /// [C++] 'if' '(' condition ')' statement
1184 /// [C++] 'if' '(' condition ')' statement 'else' statement
1186 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1187 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1188 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1190 bool IsConstexpr = false;
1191 if (Tok.is(tok::kw_constexpr)) {
1192 Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
1193 : diag::ext_constexpr_if);
1198 if (Tok.isNot(tok::l_paren)) {
1199 Diag(Tok, diag::err_expected_lparen_after) << "if";
1200 SkipUntil(tok::semi);
1204 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1206 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1207 // the case for C90.
1210 // A name introduced by a declaration in a condition is in scope from its
1211 // point of declaration until the end of the substatements controlled by the
1214 // Names declared in the for-init-statement, and in the condition of if,
1215 // while, for, and switch statements are local to the if, while, for, or
1216 // switch statement (including the controlled statement).
1218 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1220 // Parse the condition.
1221 StmtResult InitStmt;
1222 Sema::ConditionResult Cond;
1223 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1224 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1225 : Sema::ConditionKind::Boolean))
1228 llvm::Optional<bool> ConstexprCondition;
1230 ConstexprCondition = Cond.getKnownValue();
1232 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1233 // there is no compound stmt. C90 does not have this clause. We only do this
1234 // if the body isn't a compound statement to avoid push/pop in common cases.
1237 // The substatement in a selection-statement (each substatement, in the else
1238 // form of the if statement) implicitly defines a local scope.
1240 // For C++ we create a scope for the condition and a new scope for
1241 // substatements because:
1242 // -When the 'then' scope exits, we want the condition declaration to still be
1243 // active for the 'else' scope too.
1244 // -Sema will detect name clashes by considering declarations of a
1245 // 'ControlScope' as part of its direct subscope.
1246 // -If we wanted the condition and substatement to be in the same scope, we
1247 // would have to notify ParseStatement not to create a new scope. It's
1248 // simpler to let it create a new scope.
1250 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1252 // Read the 'then' stmt.
1253 SourceLocation ThenStmtLoc = Tok.getLocation();
1255 SourceLocation InnerStatementTrailingElseLoc;
1256 StmtResult ThenStmt;
1258 EnterExpressionEvaluationContext PotentiallyDiscarded(
1259 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1260 Sema::ExpressionEvaluationContextRecord::EK_Other,
1261 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1262 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1265 // Pop the 'if' scope if needed.
1268 // If it has an else, parse it.
1269 SourceLocation ElseLoc;
1270 SourceLocation ElseStmtLoc;
1271 StmtResult ElseStmt;
1273 if (Tok.is(tok::kw_else)) {
1274 if (TrailingElseLoc)
1275 *TrailingElseLoc = Tok.getLocation();
1277 ElseLoc = ConsumeToken();
1278 ElseStmtLoc = Tok.getLocation();
1280 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1281 // there is no compound stmt. C90 does not have this clause. We only do
1282 // this if the body isn't a compound statement to avoid push/pop in common
1286 // The substatement in a selection-statement (each substatement, in the else
1287 // form of the if statement) implicitly defines a local scope.
1289 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1290 Tok.is(tok::l_brace));
1292 EnterExpressionEvaluationContext PotentiallyDiscarded(
1293 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1294 Sema::ExpressionEvaluationContextRecord::EK_Other,
1295 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1296 ElseStmt = ParseStatement();
1298 // Pop the 'else' scope if needed.
1300 } else if (Tok.is(tok::code_completion)) {
1301 Actions.CodeCompleteAfterIf(getCurScope());
1304 } else if (InnerStatementTrailingElseLoc.isValid()) {
1305 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1310 // If the then or else stmt is invalid and the other is valid (and present),
1311 // make turn the invalid one into a null stmt to avoid dropping the other
1312 // part. If both are invalid, return error.
1313 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1314 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1315 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1316 // Both invalid, or one is invalid and other is non-present: return error.
1320 // Now if either are invalid, replace with a ';'.
1321 if (ThenStmt.isInvalid())
1322 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1323 if (ElseStmt.isInvalid())
1324 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1326 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1327 ThenStmt.get(), ElseLoc, ElseStmt.get());
1330 /// ParseSwitchStatement
1331 /// switch-statement:
1332 /// 'switch' '(' expression ')' statement
1333 /// [C++] 'switch' '(' condition ')' statement
1334 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1335 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1336 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1338 if (Tok.isNot(tok::l_paren)) {
1339 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1340 SkipUntil(tok::semi);
1344 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1346 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1347 // not the case for C90. Start the switch scope.
1350 // A name introduced by a declaration in a condition is in scope from its
1351 // point of declaration until the end of the substatements controlled by the
1354 // Names declared in the for-init-statement, and in the condition of if,
1355 // while, for, and switch statements are local to the if, while, for, or
1356 // switch statement (including the controlled statement).
1358 unsigned ScopeFlags = Scope::SwitchScope;
1360 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1361 ParseScope SwitchScope(this, ScopeFlags);
1363 // Parse the condition.
1364 StmtResult InitStmt;
1365 Sema::ConditionResult Cond;
1366 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1367 Sema::ConditionKind::Switch))
1371 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1373 if (Switch.isInvalid()) {
1374 // Skip the switch body.
1375 // FIXME: This is not optimal recovery, but parsing the body is more
1376 // dangerous due to the presence of case and default statements, which
1377 // will have no place to connect back with the switch.
1378 if (Tok.is(tok::l_brace)) {
1380 SkipUntil(tok::r_brace);
1382 SkipUntil(tok::semi);
1386 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1387 // there is no compound stmt. C90 does not have this clause. We only do this
1388 // if the body isn't a compound statement to avoid push/pop in common cases.
1391 // The substatement in a selection-statement (each substatement, in the else
1392 // form of the if statement) implicitly defines a local scope.
1394 // See comments in ParseIfStatement for why we create a scope for the
1395 // condition and a new scope for substatement in C++.
1397 getCurScope()->AddFlags(Scope::BreakScope);
1398 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1400 // We have incremented the mangling number for the SwitchScope and the
1401 // InnerScope, which is one too many.
1403 getCurScope()->decrementMSManglingNumber();
1405 // Read the body statement.
1406 StmtResult Body(ParseStatement(TrailingElseLoc));
1412 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1415 /// ParseWhileStatement
1416 /// while-statement: [C99 6.8.5.1]
1417 /// 'while' '(' expression ')' statement
1418 /// [C++] 'while' '(' condition ')' statement
1419 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1420 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1421 SourceLocation WhileLoc = Tok.getLocation();
1422 ConsumeToken(); // eat the 'while'.
1424 if (Tok.isNot(tok::l_paren)) {
1425 Diag(Tok, diag::err_expected_lparen_after) << "while";
1426 SkipUntil(tok::semi);
1430 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1432 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1433 // the case for C90. Start the loop scope.
1436 // A name introduced by a declaration in a condition is in scope from its
1437 // point of declaration until the end of the substatements controlled by the
1440 // Names declared in the for-init-statement, and in the condition of if,
1441 // while, for, and switch statements are local to the if, while, for, or
1442 // switch statement (including the controlled statement).
1444 unsigned ScopeFlags;
1446 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1447 Scope::DeclScope | Scope::ControlScope;
1449 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1450 ParseScope WhileScope(this, ScopeFlags);
1452 // Parse the condition.
1453 Sema::ConditionResult Cond;
1454 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1455 Sema::ConditionKind::Boolean))
1458 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1459 // there is no compound stmt. C90 does not have this clause. We only do this
1460 // if the body isn't a compound statement to avoid push/pop in common cases.
1463 // The substatement in an iteration-statement implicitly defines a local scope
1464 // which is entered and exited each time through the loop.
1466 // See comments in ParseIfStatement for why we create a scope for the
1467 // condition and a new scope for substatement in C++.
1469 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1471 // Read the body statement.
1472 StmtResult Body(ParseStatement(TrailingElseLoc));
1474 // Pop the body scope if needed.
1478 if (Cond.isInvalid() || Body.isInvalid())
1481 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1484 /// ParseDoStatement
1485 /// do-statement: [C99 6.8.5.2]
1486 /// 'do' statement 'while' '(' expression ')' ';'
1487 /// Note: this lets the caller parse the end ';'.
1488 StmtResult Parser::ParseDoStatement() {
1489 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1490 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1492 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1493 // the case for C90. Start the loop scope.
1494 unsigned ScopeFlags;
1495 if (getLangOpts().C99)
1496 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1498 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1500 ParseScope DoScope(this, ScopeFlags);
1502 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1503 // there is no compound stmt. C90 does not have this clause. We only do this
1504 // if the body isn't a compound statement to avoid push/pop in common cases.
1507 // The substatement in an iteration-statement implicitly defines a local scope
1508 // which is entered and exited each time through the loop.
1510 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1511 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1513 // Read the body statement.
1514 StmtResult Body(ParseStatement());
1516 // Pop the body scope if needed.
1519 if (Tok.isNot(tok::kw_while)) {
1520 if (!Body.isInvalid()) {
1521 Diag(Tok, diag::err_expected_while);
1522 Diag(DoLoc, diag::note_matching) << "'do'";
1523 SkipUntil(tok::semi, StopBeforeMatch);
1527 SourceLocation WhileLoc = ConsumeToken();
1529 if (Tok.isNot(tok::l_paren)) {
1530 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1531 SkipUntil(tok::semi, StopBeforeMatch);
1535 // Parse the parenthesized expression.
1536 BalancedDelimiterTracker T(*this, tok::l_paren);
1539 // A do-while expression is not a condition, so can't have attributes.
1540 DiagnoseAndSkipCXX11Attributes();
1542 ExprResult Cond = ParseExpression();
1543 // Correct the typos in condition before closing the scope.
1544 if (Cond.isUsable())
1545 Cond = Actions.CorrectDelayedTyposInExpr(Cond);
1549 if (Cond.isInvalid() || Body.isInvalid())
1552 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1553 Cond.get(), T.getCloseLocation());
1556 bool Parser::isForRangeIdentifier() {
1557 assert(Tok.is(tok::identifier));
1559 const Token &Next = NextToken();
1560 if (Next.is(tok::colon))
1563 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1564 TentativeParsingAction PA(*this);
1566 SkipCXX11Attributes();
1567 bool Result = Tok.is(tok::colon);
1575 /// ParseForStatement
1576 /// for-statement: [C99 6.8.5.3]
1577 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1578 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1579 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1582 /// 'co_await'[opt] [Coroutines]
1583 /// '(' for-range-declaration ':' for-range-initializer ')'
1585 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1586 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1588 /// [C++] for-init-statement:
1589 /// [C++] expression-statement
1590 /// [C++] simple-declaration
1592 /// [C++0x] for-range-declaration:
1593 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1594 /// [C++0x] for-range-initializer:
1595 /// [C++0x] expression
1596 /// [C++0x] braced-init-list [TODO]
1597 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1598 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1599 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1601 SourceLocation CoawaitLoc;
1602 if (Tok.is(tok::kw_co_await))
1603 CoawaitLoc = ConsumeToken();
1605 if (Tok.isNot(tok::l_paren)) {
1606 Diag(Tok, diag::err_expected_lparen_after) << "for";
1607 SkipUntil(tok::semi);
1611 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1614 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1615 // the case for C90. Start the loop scope.
1618 // A name introduced by a declaration in a condition is in scope from its
1619 // point of declaration until the end of the substatements controlled by the
1622 // Names declared in the for-init-statement, and in the condition of if,
1623 // while, for, and switch statements are local to the if, while, for, or
1624 // switch statement (including the controlled statement).
1626 // Names declared in the for-init-statement are in the same declarative-region
1627 // as those declared in the condition.
1629 unsigned ScopeFlags = 0;
1631 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1633 ParseScope ForScope(this, ScopeFlags);
1635 BalancedDelimiterTracker T(*this, tok::l_paren);
1640 bool ForEach = false;
1641 StmtResult FirstPart;
1642 Sema::ConditionResult SecondPart;
1643 ExprResult Collection;
1644 ForRangeInfo ForRangeInfo;
1645 FullExprArg ThirdPart(Actions);
1647 if (Tok.is(tok::code_completion)) {
1648 Actions.CodeCompleteOrdinaryName(getCurScope(),
1649 C99orCXXorObjC? Sema::PCC_ForInit
1650 : Sema::PCC_Expression);
1655 ParsedAttributesWithRange attrs(AttrFactory);
1656 MaybeParseCXX11Attributes(attrs);
1658 SourceLocation EmptyInitStmtSemiLoc;
1660 // Parse the first part of the for specifier.
1661 if (Tok.is(tok::semi)) { // for (;
1662 ProhibitAttributes(attrs);
1663 // no first part, eat the ';'.
1664 SourceLocation SemiLoc = Tok.getLocation();
1665 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
1666 EmptyInitStmtSemiLoc = SemiLoc;
1668 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1669 isForRangeIdentifier()) {
1670 ProhibitAttributes(attrs);
1671 IdentifierInfo *Name = Tok.getIdentifierInfo();
1672 SourceLocation Loc = ConsumeToken();
1673 MaybeParseCXX11Attributes(attrs);
1675 ForRangeInfo.ColonLoc = ConsumeToken();
1676 if (Tok.is(tok::l_brace))
1677 ForRangeInfo.RangeExpr = ParseBraceInitializer();
1679 ForRangeInfo.RangeExpr = ParseExpression();
1681 Diag(Loc, diag::err_for_range_identifier)
1682 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
1683 ? FixItHint::CreateInsertion(Loc, "auto &&")
1686 ForRangeInfo.LoopVar = Actions.ActOnCXXForRangeIdentifier(
1687 getCurScope(), Loc, Name, attrs, attrs.Range.getEnd());
1688 } else if (isForInitDeclaration()) { // for (int X = 4;
1689 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1691 // Parse declaration, which eats the ';'.
1692 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
1693 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1694 Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
1697 // In C++0x, "for (T NS:a" might not be a typo for ::
1698 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1699 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1701 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1702 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1703 DeclaratorContext::ForContext, DeclEnd, attrs, false,
1704 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
1705 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1706 if (ForRangeInfo.ParsedForRangeDecl()) {
1707 Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11 ?
1708 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1709 ForRangeInfo.LoopVar = FirstPart;
1710 FirstPart = StmtResult();
1711 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1713 } else if ((ForEach = isTokIdentifier_in())) {
1714 Actions.ActOnForEachDeclStmt(DG);
1715 // ObjC: for (id x in expr)
1716 ConsumeToken(); // consume 'in'
1718 if (Tok.is(tok::code_completion)) {
1719 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1723 Collection = ParseExpression();
1725 Diag(Tok, diag::err_expected_semi_for);
1728 ProhibitAttributes(attrs);
1729 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1731 ForEach = isTokIdentifier_in();
1733 // Turn the expression into a stmt.
1734 if (!Value.isInvalid()) {
1736 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1738 // We already know this is not an init-statement within a for loop, so
1739 // if we are parsing a C++11 range-based for loop, we should treat this
1740 // expression statement as being a discarded value expression because
1741 // we will err below. This way we do not warn on an unused expression
1742 // that was an error in the first place, like with: for (expr : expr);
1743 bool IsRangeBasedFor =
1744 getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon);
1745 FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
1749 if (Tok.is(tok::semi)) {
1751 } else if (ForEach) {
1752 ConsumeToken(); // consume 'in'
1754 if (Tok.is(tok::code_completion)) {
1755 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1759 Collection = ParseExpression();
1760 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1761 // User tried to write the reasonable, but ill-formed, for-range-statement
1762 // for (expr : expr) { ... }
1763 Diag(Tok, diag::err_for_range_expected_decl)
1764 << FirstPart.get()->getSourceRange();
1765 SkipUntil(tok::r_paren, StopBeforeMatch);
1766 SecondPart = Sema::ConditionError();
1768 if (!Value.isInvalid()) {
1769 Diag(Tok, diag::err_expected_semi_for);
1771 // Skip until semicolon or rparen, don't consume it.
1772 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1773 if (Tok.is(tok::semi))
1779 // Parse the second part of the for specifier.
1780 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1781 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
1782 !SecondPart.isInvalid()) {
1783 // Parse the second part of the for specifier.
1784 if (Tok.is(tok::semi)) { // for (...;;
1786 } else if (Tok.is(tok::r_paren)) {
1787 // missing both semicolons.
1789 if (getLangOpts().CPlusPlus) {
1790 // C++2a: We've parsed an init-statement; we might have a
1791 // for-range-declaration next.
1792 bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
1793 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1795 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean,
1796 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
1798 if (ForRangeInfo.ParsedForRangeDecl()) {
1799 Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
1800 : ForRangeInfo.ColonLoc,
1801 getLangOpts().CPlusPlus2a
1802 ? diag::warn_cxx17_compat_for_range_init_stmt
1803 : diag::ext_for_range_init_stmt)
1804 << (FirstPart.get() ? FirstPart.get()->getSourceRange()
1806 if (EmptyInitStmtSemiLoc.isValid()) {
1807 Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
1809 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
1813 ExprResult SecondExpr = ParseExpression();
1814 if (SecondExpr.isInvalid())
1815 SecondPart = Sema::ConditionError();
1818 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1819 Sema::ConditionKind::Boolean);
1824 // Parse the third part of the for statement.
1825 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
1826 if (Tok.isNot(tok::semi)) {
1827 if (!SecondPart.isInvalid())
1828 Diag(Tok, diag::err_expected_semi_for);
1830 // Skip until semicolon or rparen, don't consume it.
1831 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1834 if (Tok.is(tok::semi)) {
1838 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1839 ExprResult Third = ParseExpression();
1840 // FIXME: The C++11 standard doesn't actually say that this is a
1841 // discarded-value expression, but it clearly should be.
1842 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1848 // C++ Coroutines [stmt.iter]:
1849 // 'co_await' can only be used for a range-based for statement.
1850 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
1851 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1852 CoawaitLoc = SourceLocation();
1855 // We need to perform most of the semantic analysis for a C++0x for-range
1856 // statememt before parsing the body, in order to be able to deduce the type
1857 // of an auto-typed loop variable.
1858 StmtResult ForRangeStmt;
1859 StmtResult ForEachStmt;
1861 if (ForRangeInfo.ParsedForRangeDecl()) {
1862 ExprResult CorrectedRange =
1863 Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());
1864 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1865 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1866 ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),
1867 T.getCloseLocation(), Sema::BFRK_Build);
1869 // Similarly, we need to do the semantic analysis for a for-range
1870 // statement immediately in order to close over temporaries correctly.
1871 } else if (ForEach) {
1872 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1875 T.getCloseLocation());
1877 // In OpenMP loop region loop control variable must be captured and be
1878 // private. Perform analysis of first part (if any).
1879 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1880 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1884 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1885 // there is no compound stmt. C90 does not have this clause. We only do this
1886 // if the body isn't a compound statement to avoid push/pop in common cases.
1889 // The substatement in an iteration-statement implicitly defines a local scope
1890 // which is entered and exited each time through the loop.
1892 // See comments in ParseIfStatement for why we create a scope for
1893 // for-init-statement/condition and a new scope for substatement in C++.
1895 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1896 Tok.is(tok::l_brace));
1898 // The body of the for loop has the same local mangling number as the
1899 // for-init-statement.
1900 // It will only be incremented if the body contains other things that would
1901 // normally increment the mangling number (like a compound statement).
1903 getCurScope()->decrementMSManglingNumber();
1905 // Read the body statement.
1906 StmtResult Body(ParseStatement(TrailingElseLoc));
1908 // Pop the body scope if needed.
1911 // Leave the for-scope.
1914 if (Body.isInvalid())
1918 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1921 if (ForRangeInfo.ParsedForRangeDecl())
1922 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1924 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1925 SecondPart, ThirdPart, T.getCloseLocation(),
1929 /// ParseGotoStatement
1931 /// 'goto' identifier ';'
1932 /// [GNU] 'goto' '*' expression ';'
1934 /// Note: this lets the caller parse the end ';'.
1936 StmtResult Parser::ParseGotoStatement() {
1937 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1938 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1941 if (Tok.is(tok::identifier)) {
1942 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1944 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1946 } else if (Tok.is(tok::star)) {
1947 // GNU indirect goto extension.
1948 Diag(Tok, diag::ext_gnu_indirect_goto);
1949 SourceLocation StarLoc = ConsumeToken();
1950 ExprResult R(ParseExpression());
1951 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1952 SkipUntil(tok::semi, StopBeforeMatch);
1955 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1957 Diag(Tok, diag::err_expected) << tok::identifier;
1964 /// ParseContinueStatement
1968 /// Note: this lets the caller parse the end ';'.
1970 StmtResult Parser::ParseContinueStatement() {
1971 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1972 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1975 /// ParseBreakStatement
1979 /// Note: this lets the caller parse the end ';'.
1981 StmtResult Parser::ParseBreakStatement() {
1982 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1983 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1986 /// ParseReturnStatement
1988 /// 'return' expression[opt] ';'
1989 /// 'return' braced-init-list ';'
1990 /// 'co_return' expression[opt] ';'
1991 /// 'co_return' braced-init-list ';'
1992 StmtResult Parser::ParseReturnStatement() {
1993 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1994 "Not a return stmt!");
1995 bool IsCoreturn = Tok.is(tok::kw_co_return);
1996 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1999 if (Tok.isNot(tok::semi)) {
2001 PreferredType.enterReturn(Actions, Tok.getLocation());
2002 // FIXME: Code completion for co_return.
2003 if (Tok.is(tok::code_completion) && !IsCoreturn) {
2004 Actions.CodeCompleteExpression(getCurScope(),
2005 PreferredType.get(Tok.getLocation()));
2010 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
2011 R = ParseInitializer();
2013 Diag(R.get()->getBeginLoc(),
2014 getLangOpts().CPlusPlus11
2015 ? diag::warn_cxx98_compat_generalized_initializer_lists
2016 : diag::ext_generalized_initializer_lists)
2017 << R.get()->getSourceRange();
2019 R = ParseExpression();
2020 if (R.isInvalid()) {
2021 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2026 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
2027 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
2030 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
2031 ParsedStmtContext StmtCtx,
2032 SourceLocation *TrailingElseLoc,
2033 ParsedAttributesWithRange &Attrs) {
2034 // Create temporary attribute list.
2035 ParsedAttributesWithRange TempAttrs(AttrFactory);
2037 // Get loop hints and consume annotated token.
2038 while (Tok.is(tok::annot_pragma_loop_hint)) {
2040 if (!HandlePragmaLoopHint(Hint))
2043 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
2044 ArgsUnion(Hint.ValueExpr)};
2045 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
2046 Hint.PragmaNameLoc->Loc, ArgHints, 4,
2047 ParsedAttr::AS_Pragma);
2050 // Get the next statement.
2051 MaybeParseCXX11Attributes(Attrs);
2053 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
2054 Stmts, StmtCtx, TrailingElseLoc, Attrs);
2056 Attrs.takeAllFrom(TempAttrs);
2060 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2061 assert(Tok.is(tok::l_brace));
2062 SourceLocation LBraceLoc = Tok.getLocation();
2064 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
2065 "parsing function body");
2067 // Save and reset current vtordisp stack if we have entered a C++ method body.
2069 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2070 Sema::PragmaStackSentinelRAII
2071 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2073 // Do not enter a scope for the brace, as the arguments are in the same scope
2074 // (the function body) as the body itself. Instead, just read the statement
2075 // list and put it into a CompoundStmt for safe keeping.
2076 StmtResult FnBody(ParseCompoundStatementBody());
2078 // If the function body could not be parsed, make a bogus compoundstmt.
2079 if (FnBody.isInvalid()) {
2080 Sema::CompoundScopeRAII CompoundScope(Actions);
2081 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2085 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2088 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
2090 /// function-try-block:
2091 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2093 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2094 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2095 SourceLocation TryLoc = ConsumeToken();
2097 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
2098 "parsing function try block");
2100 // Constructor initializer list?
2101 if (Tok.is(tok::colon))
2102 ParseConstructorInitializer(Decl);
2104 Actions.ActOnDefaultCtorInitializers(Decl);
2106 // Save and reset current vtordisp stack if we have entered a C++ method body.
2108 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2109 Sema::PragmaStackSentinelRAII
2110 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2112 SourceLocation LBraceLoc = Tok.getLocation();
2113 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2114 // If we failed to parse the try-catch, we just give the function an empty
2115 // compound statement as the body.
2116 if (FnBody.isInvalid()) {
2117 Sema::CompoundScopeRAII CompoundScope(Actions);
2118 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2122 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2125 bool Parser::trySkippingFunctionBody() {
2126 assert(SkipFunctionBodies &&
2127 "Should only be called when SkipFunctionBodies is enabled");
2128 if (!PP.isCodeCompletionEnabled()) {
2133 // We're in code-completion mode. Skip parsing for all function bodies unless
2134 // the body contains the code-completion point.
2135 TentativeParsingAction PA(*this);
2136 bool IsTryCatch = Tok.is(tok::kw_try);
2138 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2139 if (llvm::any_of(Toks, [](const Token &Tok) {
2140 return Tok.is(tok::code_completion);
2145 if (ErrorInPrologue) {
2147 SkipMalformedDecl();
2150 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2154 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2155 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2156 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2165 /// ParseCXXTryBlock - Parse a C++ try-block.
2168 /// 'try' compound-statement handler-seq
2170 StmtResult Parser::ParseCXXTryBlock() {
2171 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2173 SourceLocation TryLoc = ConsumeToken();
2174 return ParseCXXTryBlockCommon(TryLoc);
2177 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2178 /// function-try-block.
2181 /// 'try' compound-statement handler-seq
2183 /// function-try-block:
2184 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2187 /// handler handler-seq[opt]
2189 /// [Borland] try-block:
2190 /// 'try' compound-statement seh-except-block
2191 /// 'try' compound-statement seh-finally-block
2193 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2194 if (Tok.isNot(tok::l_brace))
2195 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2197 StmtResult TryBlock(ParseCompoundStatement(
2198 /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2199 Scope::CompoundStmtScope |
2200 (FnTry ? Scope::FnTryCatchScope : 0)));
2201 if (TryBlock.isInvalid())
2204 // Borland allows SEH-handlers with 'try'
2206 if ((Tok.is(tok::identifier) &&
2207 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2208 Tok.is(tok::kw___finally)) {
2209 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2211 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2212 SourceLocation Loc = ConsumeToken();
2213 Handler = ParseSEHExceptBlock(Loc);
2216 SourceLocation Loc = ConsumeToken();
2217 Handler = ParseSEHFinallyBlock(Loc);
2219 if(Handler.isInvalid())
2222 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2228 StmtVector Handlers;
2230 // C++11 attributes can't appear here, despite this context seeming
2232 DiagnoseAndSkipCXX11Attributes();
2234 if (Tok.isNot(tok::kw_catch))
2235 return StmtError(Diag(Tok, diag::err_expected_catch));
2236 while (Tok.is(tok::kw_catch)) {
2237 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2238 if (!Handler.isInvalid())
2239 Handlers.push_back(Handler.get());
2241 // Don't bother creating the full statement if we don't have any usable
2243 if (Handlers.empty())
2246 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2250 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2253 /// 'catch' '(' exception-declaration ')' compound-statement
2255 /// exception-declaration:
2256 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2257 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2260 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2261 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2263 SourceLocation CatchLoc = ConsumeToken();
2265 BalancedDelimiterTracker T(*this, tok::l_paren);
2266 if (T.expectAndConsume())
2270 // The name in a catch exception-declaration is local to the handler and
2271 // shall not be redeclared in the outermost block of the handler.
2272 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2274 (FnCatch ? Scope::FnTryCatchScope : 0));
2276 // exception-declaration is equivalent to '...' or a parameter-declaration
2277 // without default arguments.
2278 Decl *ExceptionDecl = nullptr;
2279 if (Tok.isNot(tok::ellipsis)) {
2280 ParsedAttributesWithRange Attributes(AttrFactory);
2281 MaybeParseCXX11Attributes(Attributes);
2283 DeclSpec DS(AttrFactory);
2284 DS.takeAttributesFrom(Attributes);
2286 if (ParseCXXTypeSpecifierSeq(DS))
2289 Declarator ExDecl(DS, DeclaratorContext::CXXCatchContext);
2290 ParseDeclarator(ExDecl);
2291 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2296 if (T.getCloseLocation().isInvalid())
2299 if (Tok.isNot(tok::l_brace))
2300 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2302 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2303 StmtResult Block(ParseCompoundStatement());
2304 if (Block.isInvalid())
2307 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2310 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2311 IfExistsCondition Result;
2312 if (ParseMicrosoftIfExistsCondition(Result))
2315 // Handle dependent statements by parsing the braces as a compound statement.
2316 // This is not the same behavior as Visual C++, which don't treat this as a
2317 // compound statement, but for Clang's type checking we can't have anything
2318 // inside these braces escaping to the surrounding code.
2319 if (Result.Behavior == IEB_Dependent) {
2320 if (!Tok.is(tok::l_brace)) {
2321 Diag(Tok, diag::err_expected) << tok::l_brace;
2325 StmtResult Compound = ParseCompoundStatement();
2326 if (Compound.isInvalid())
2329 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2334 if (DepResult.isUsable())
2335 Stmts.push_back(DepResult.get());
2339 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2340 if (Braces.consumeOpen()) {
2341 Diag(Tok, diag::err_expected) << tok::l_brace;
2345 switch (Result.Behavior) {
2347 // Parse the statements below.
2351 llvm_unreachable("Dependent case handled above");
2358 // Condition is true, parse the statements.
2359 while (Tok.isNot(tok::r_brace)) {
2361 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
2363 Stmts.push_back(R.get());
2365 Braces.consumeClose();
2368 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2369 MaybeParseGNUAttributes(Attrs);
2374 if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
2377 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2378 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);