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/AST/PrettyDeclStackTrace.h"
16 #include "clang/Basic/Attributes.h"
17 #include "clang/Basic/PrettyStackTrace.h"
18 #include "clang/Parse/LoopHint.h"
19 #include "clang/Parse/Parser.h"
20 #include "clang/Parse/RAIIObjectsForParser.h"
21 #include "clang/Sema/DeclSpec.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 /// 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, 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_fenv_access:
352 ProhibitAttributes(Attrs);
353 HandlePragmaFEnvAccess();
356 case tok::annot_pragma_opencl_extension:
357 ProhibitAttributes(Attrs);
358 HandlePragmaOpenCLExtension();
361 case tok::annot_pragma_captured:
362 ProhibitAttributes(Attrs);
363 return HandlePragmaCaptured();
365 case tok::annot_pragma_openmp:
366 ProhibitAttributes(Attrs);
367 return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
369 case tok::annot_pragma_ms_pointers_to_members:
370 ProhibitAttributes(Attrs);
371 HandlePragmaMSPointersToMembers();
374 case tok::annot_pragma_ms_pragma:
375 ProhibitAttributes(Attrs);
376 HandlePragmaMSPragma();
379 case tok::annot_pragma_ms_vtordisp:
380 ProhibitAttributes(Attrs);
381 HandlePragmaMSVtorDisp();
384 case tok::annot_pragma_loop_hint:
385 ProhibitAttributes(Attrs);
386 return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
388 case tok::annot_pragma_dump:
392 case tok::annot_pragma_attribute:
393 HandlePragmaAttribute();
397 // If we reached this code, the statement must end in a semicolon.
398 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
399 // If the result was valid, then we do want to diagnose this. Use
400 // ExpectAndConsume to emit the diagnostic, even though we know it won't
402 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
403 // Skip until we see a } or ;, but don't eat it.
404 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
410 /// Parse an expression statement.
411 StmtResult Parser::ParseExprStatement() {
412 // If a case keyword is missing, this is where it should be inserted.
413 Token OldToken = Tok;
415 ExprStatementTokLoc = Tok.getLocation();
417 // expression[opt] ';'
418 ExprResult Expr(ParseExpression());
419 if (Expr.isInvalid()) {
420 // If the expression is invalid, skip ahead to the next semicolon or '}'.
421 // Not doing this opens us up to the possibility of infinite loops if
422 // ParseExpression does not consume any tokens.
423 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
424 if (Tok.is(tok::semi))
426 return Actions.ActOnExprStmtError();
429 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
430 Actions.CheckCaseExpression(Expr.get())) {
431 // If a constant expression is followed by a colon inside a switch block,
432 // suggest a missing case keyword.
433 Diag(OldToken, diag::err_expected_case_before_expression)
434 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
436 // Recover parsing as a case statement.
437 return ParseCaseStatement(/*MissingCase=*/true, Expr);
440 // Otherwise, eat the semicolon.
441 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
442 return Actions.ActOnExprStmt(Expr, isExprValueDiscarded());
445 /// ParseSEHTryBlockCommon
448 /// '__try' compound-statement seh-handler
452 /// seh-finally-block
454 StmtResult Parser::ParseSEHTryBlock() {
455 assert(Tok.is(tok::kw___try) && "Expected '__try'");
456 SourceLocation TryLoc = ConsumeToken();
458 if (Tok.isNot(tok::l_brace))
459 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
461 StmtResult TryBlock(ParseCompoundStatement(
462 /*isStmtExpr=*/false,
463 Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
464 if (TryBlock.isInvalid())
468 if (Tok.is(tok::identifier) &&
469 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
470 SourceLocation Loc = ConsumeToken();
471 Handler = ParseSEHExceptBlock(Loc);
472 } else if (Tok.is(tok::kw___finally)) {
473 SourceLocation Loc = ConsumeToken();
474 Handler = ParseSEHFinallyBlock(Loc);
476 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
479 if(Handler.isInvalid())
482 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
488 /// ParseSEHExceptBlock - Handle __except
490 /// seh-except-block:
491 /// '__except' '(' seh-filter-expression ')' compound-statement
493 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
494 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
495 raii2(Ident___exception_code, false),
496 raii3(Ident_GetExceptionCode, false);
498 if (ExpectAndConsume(tok::l_paren))
501 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
502 Scope::SEHExceptScope);
504 if (getLangOpts().Borland) {
505 Ident__exception_info->setIsPoisoned(false);
506 Ident___exception_info->setIsPoisoned(false);
507 Ident_GetExceptionInfo->setIsPoisoned(false);
510 ExprResult FilterExpr;
512 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
513 Scope::SEHFilterScope);
514 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
517 if (getLangOpts().Borland) {
518 Ident__exception_info->setIsPoisoned(true);
519 Ident___exception_info->setIsPoisoned(true);
520 Ident_GetExceptionInfo->setIsPoisoned(true);
523 if(FilterExpr.isInvalid())
526 if (ExpectAndConsume(tok::r_paren))
529 if (Tok.isNot(tok::l_brace))
530 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
532 StmtResult Block(ParseCompoundStatement());
534 if(Block.isInvalid())
537 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
540 /// ParseSEHFinallyBlock - Handle __finally
542 /// seh-finally-block:
543 /// '__finally' compound-statement
545 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
546 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
547 raii2(Ident___abnormal_termination, false),
548 raii3(Ident_AbnormalTermination, false);
550 if (Tok.isNot(tok::l_brace))
551 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
553 ParseScope FinallyScope(this, 0);
554 Actions.ActOnStartSEHFinallyBlock();
556 StmtResult Block(ParseCompoundStatement());
557 if(Block.isInvalid()) {
558 Actions.ActOnAbortSEHFinallyBlock();
562 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
567 /// seh-leave-statement:
570 StmtResult Parser::ParseSEHLeaveStatement() {
571 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
572 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
575 /// ParseLabeledStatement - We have an identifier and a ':' after it.
577 /// labeled-statement:
578 /// identifier ':' statement
579 /// [GNU] identifier ':' attributes[opt] statement
581 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
582 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
583 "Not an identifier!");
585 Token IdentTok = Tok; // Save the whole token.
586 ConsumeToken(); // eat the identifier.
588 assert(Tok.is(tok::colon) && "Not a label!");
590 // identifier ':' statement
591 SourceLocation ColonLoc = ConsumeToken();
593 // Read label attributes, if present.
595 if (Tok.is(tok::kw___attribute)) {
596 ParsedAttributesWithRange TempAttrs(AttrFactory);
597 ParseGNUAttributes(TempAttrs);
599 // In C++, GNU attributes only apply to the label if they are followed by a
600 // semicolon, to disambiguate label attributes from attributes on a labeled
603 // This doesn't quite match what GCC does; if the attribute list is empty
604 // and followed by a semicolon, GCC will reject (it appears to parse the
605 // attributes as part of a statement in that case). That looks like a bug.
606 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
607 attrs.takeAllFrom(TempAttrs);
608 else if (isDeclarationStatement()) {
610 // FIXME: We should do this whether or not we have a declaration
611 // statement, but that doesn't work correctly (because ProhibitAttributes
612 // can't handle GNU attributes), so only call it in the one case where
613 // GNU attributes are allowed.
614 SubStmt = ParseStatementOrDeclarationAfterAttributes(
615 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
617 if (!TempAttrs.empty() && !SubStmt.isInvalid())
618 SubStmt = Actions.ProcessStmtAttributes(SubStmt.get(), TempAttrs,
621 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
625 // If we've not parsed a statement yet, parse one now.
626 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
627 SubStmt = ParseStatement();
629 // Broken substmt shouldn't prevent the label from being added to the AST.
630 if (SubStmt.isInvalid())
631 SubStmt = Actions.ActOnNullStmt(ColonLoc);
633 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
634 IdentTok.getLocation());
635 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, attrs);
638 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
642 /// ParseCaseStatement
643 /// labeled-statement:
644 /// 'case' constant-expression ':' statement
645 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
647 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
648 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
650 // It is very very common for code to contain many case statements recursively
651 // nested, as in (but usually without indentation):
658 // Parsing this naively works, but is both inefficient and can cause us to run
659 // out of stack space in our recursive descent parser. As a special case,
660 // flatten this recursion into an iterative loop. This is complex and gross,
661 // but all the grossness is constrained to ParseCaseStatement (and some
662 // weirdness in the actions), so this is just local grossness :).
664 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
666 StmtResult TopLevelCase(true);
668 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
669 // gets updated each time a new case is parsed, and whose body is unset so
670 // far. When parsing 'case 4', this is the 'case 3' node.
671 Stmt *DeepestParsedCaseStmt = nullptr;
673 // While we have case statements, eat and stack them.
674 SourceLocation ColonLoc;
676 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
677 ConsumeToken(); // eat the 'case'.
678 ColonLoc = SourceLocation();
680 if (Tok.is(tok::code_completion)) {
681 Actions.CodeCompleteCase(getCurScope());
686 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
687 /// Disable this form of error recovery while we're parsing the case
689 ColonProtectionRAIIObject ColonProtection(*this);
693 LHS = ParseCaseExpression(CaseLoc);
694 if (LHS.isInvalid()) {
695 // If constant-expression is parsed unsuccessfully, recover by skipping
696 // current case statement (moving to the colon that ends it).
697 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
705 // GNU case range extension.
706 SourceLocation DotDotDotLoc;
708 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
709 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
710 RHS = ParseCaseExpression(CaseLoc);
711 if (RHS.isInvalid()) {
712 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
717 ColonProtection.restore();
719 if (TryConsumeToken(tok::colon, ColonLoc)) {
720 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
721 TryConsumeToken(tok::coloncolon, ColonLoc)) {
722 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
723 Diag(ColonLoc, diag::err_expected_after)
724 << "'case'" << tok::colon
725 << FixItHint::CreateReplacement(ColonLoc, ":");
727 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
728 Diag(ExpectedLoc, diag::err_expected_after)
729 << "'case'" << tok::colon
730 << FixItHint::CreateInsertion(ExpectedLoc, ":");
731 ColonLoc = ExpectedLoc;
735 Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
737 // If we had a sema error parsing this case, then just ignore it and
738 // continue parsing the sub-stmt.
739 if (Case.isInvalid()) {
740 if (TopLevelCase.isInvalid()) // No parsed case stmts.
741 return ParseStatement(/*TrailingElseLoc=*/nullptr,
742 /*AllowOpenMPStandalone=*/true);
743 // Otherwise, just don't add it as a nested case.
745 // If this is the first case statement we parsed, it becomes TopLevelCase.
746 // Otherwise we link it into the current chain.
747 Stmt *NextDeepest = Case.get();
748 if (TopLevelCase.isInvalid())
751 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
752 DeepestParsedCaseStmt = NextDeepest;
755 // Handle all case statements.
756 } while (Tok.is(tok::kw_case));
758 // If we found a non-case statement, start by parsing it.
761 if (Tok.isNot(tok::r_brace)) {
762 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
763 /*AllowOpenMPStandalone=*/true);
765 // Nicely diagnose the common error "switch (X) { case 4: }", which is
766 // not valid. If ColonLoc doesn't point to a valid text location, there was
767 // another parsing error, so avoid producing extra diagnostics.
768 if (ColonLoc.isValid()) {
769 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
770 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
771 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
773 SubStmt = StmtError();
776 // Install the body into the most deeply-nested case.
777 if (DeepestParsedCaseStmt) {
778 // Broken sub-stmt shouldn't prevent forming the case statement properly.
779 if (SubStmt.isInvalid())
780 SubStmt = Actions.ActOnNullStmt(SourceLocation());
781 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
784 // Return the top level parsed statement tree.
788 /// ParseDefaultStatement
789 /// labeled-statement:
790 /// 'default' ':' statement
791 /// Note that this does not parse the 'statement' at the end.
793 StmtResult Parser::ParseDefaultStatement() {
794 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
795 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
797 SourceLocation ColonLoc;
798 if (TryConsumeToken(tok::colon, ColonLoc)) {
799 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
800 // Treat "default;" as a typo for "default:".
801 Diag(ColonLoc, diag::err_expected_after)
802 << "'default'" << tok::colon
803 << FixItHint::CreateReplacement(ColonLoc, ":");
805 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
806 Diag(ExpectedLoc, diag::err_expected_after)
807 << "'default'" << tok::colon
808 << FixItHint::CreateInsertion(ExpectedLoc, ":");
809 ColonLoc = ExpectedLoc;
814 if (Tok.isNot(tok::r_brace)) {
815 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
816 /*AllowOpenMPStandalone=*/true);
818 // Diagnose the common error "switch (X) {... default: }", which is
820 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
821 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
822 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
826 // Broken sub-stmt shouldn't prevent forming the case statement properly.
827 if (SubStmt.isInvalid())
828 SubStmt = Actions.ActOnNullStmt(ColonLoc);
830 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
831 SubStmt.get(), getCurScope());
834 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
835 return ParseCompoundStatement(isStmtExpr,
836 Scope::DeclScope | Scope::CompoundStmtScope);
839 /// ParseCompoundStatement - Parse a "{}" block.
841 /// compound-statement: [C99 6.8.2]
842 /// { block-item-list[opt] }
843 /// [GNU] { label-declarations block-item-list } [TODO]
847 /// block-item-list block-item
851 /// [GNU] '__extension__' declaration
854 /// [GNU] label-declarations:
855 /// [GNU] label-declaration
856 /// [GNU] label-declarations label-declaration
858 /// [GNU] label-declaration:
859 /// [GNU] '__label__' identifier-list ';'
861 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
862 unsigned ScopeFlags) {
863 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
865 // Enter a scope to hold everything within the compound stmt. Compound
866 // statements can always hold declarations.
867 ParseScope CompoundScope(this, ScopeFlags);
869 // Parse the statements in the body.
870 return ParseCompoundStatementBody(isStmtExpr);
873 /// Parse any pragmas at the start of the compound expression. We handle these
874 /// separately since some pragmas (FP_CONTRACT) must appear before any C
875 /// statement in the compound, but may be intermingled with other pragmas.
876 void Parser::ParseCompoundStatementLeadingPragmas() {
877 bool checkForPragmas = true;
878 while (checkForPragmas) {
879 switch (Tok.getKind()) {
880 case tok::annot_pragma_vis:
881 HandlePragmaVisibility();
883 case tok::annot_pragma_pack:
886 case tok::annot_pragma_msstruct:
887 HandlePragmaMSStruct();
889 case tok::annot_pragma_align:
892 case tok::annot_pragma_weak:
895 case tok::annot_pragma_weakalias:
896 HandlePragmaWeakAlias();
898 case tok::annot_pragma_redefine_extname:
899 HandlePragmaRedefineExtname();
901 case tok::annot_pragma_opencl_extension:
902 HandlePragmaOpenCLExtension();
904 case tok::annot_pragma_fp_contract:
905 HandlePragmaFPContract();
907 case tok::annot_pragma_fp:
910 case tok::annot_pragma_fenv_access:
911 HandlePragmaFEnvAccess();
913 case tok::annot_pragma_ms_pointers_to_members:
914 HandlePragmaMSPointersToMembers();
916 case tok::annot_pragma_ms_pragma:
917 HandlePragmaMSPragma();
919 case tok::annot_pragma_ms_vtordisp:
920 HandlePragmaMSVtorDisp();
922 case tok::annot_pragma_dump:
926 checkForPragmas = false;
933 /// Consume any extra semi-colons resulting in null statements,
934 /// returning true if any tok::semi were consumed.
935 bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
936 if (!Tok.is(tok::semi))
939 SourceLocation StartLoc = Tok.getLocation();
940 SourceLocation EndLoc;
942 while (Tok.is(tok::semi) && !Tok.hasLeadingEmptyMacro() &&
943 Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
944 EndLoc = Tok.getLocation();
946 // Don't just ConsumeToken() this tok::semi, do store it in AST.
947 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
949 Stmts.push_back(R.get());
952 // Did not consume any extra semi.
953 if (EndLoc.isInvalid())
956 Diag(StartLoc, diag::warn_null_statement)
957 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
961 bool Parser::isExprValueDiscarded() {
962 if (Actions.isCurCompoundStmtAStmtExpr()) {
963 // Look to see if the next two tokens close the statement expression;
964 // if so, this expression statement is the last statement in a
965 // statment expression.
966 return Tok.isNot(tok::r_brace) || NextToken().isNot(tok::r_paren);
971 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
972 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
973 /// consume the '}' at the end of the block. It does not manipulate the scope
975 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
976 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
978 "in compound statement ('{}')");
980 // Record the state of the FP_CONTRACT pragma, restore on leaving the
981 // compound statement.
982 Sema::FPContractStateRAII SaveFPContractState(Actions);
984 InMessageExpressionRAIIObject InMessage(*this, false);
985 BalancedDelimiterTracker T(*this, tok::l_brace);
989 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
991 // Parse any pragmas at the beginning of the compound statement.
992 ParseCompoundStatementLeadingPragmas();
996 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
997 // only allowed at the start of a compound stmt regardless of the language.
998 while (Tok.is(tok::kw___label__)) {
999 SourceLocation LabelLoc = ConsumeToken();
1001 SmallVector<Decl *, 8> DeclsInGroup;
1003 if (Tok.isNot(tok::identifier)) {
1004 Diag(Tok, diag::err_expected) << tok::identifier;
1008 IdentifierInfo *II = Tok.getIdentifierInfo();
1009 SourceLocation IdLoc = ConsumeToken();
1010 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
1012 if (!TryConsumeToken(tok::comma))
1016 DeclSpec DS(AttrFactory);
1017 DeclGroupPtrTy Res =
1018 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1019 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
1021 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
1023 Stmts.push_back(R.get());
1026 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
1027 Tok.isNot(tok::eof)) {
1028 if (Tok.is(tok::annot_pragma_unused)) {
1029 HandlePragmaUnused();
1033 if (ConsumeNullStmt(Stmts))
1037 if (Tok.isNot(tok::kw___extension__)) {
1038 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
1040 // __extension__ can start declarations and it can also be a unary
1041 // operator for expressions. Consume multiple __extension__ markers here
1042 // until we can determine which is which.
1043 // FIXME: This loses extension expressions in the AST!
1044 SourceLocation ExtLoc = ConsumeToken();
1045 while (Tok.is(tok::kw___extension__))
1048 ParsedAttributesWithRange attrs(AttrFactory);
1049 MaybeParseCXX11Attributes(attrs, nullptr,
1050 /*MightBeObjCMessageSend*/ true);
1052 // If this is the start of a declaration, parse it as such.
1053 if (isDeclarationStatement()) {
1054 // __extension__ silences extension warnings in the subdeclaration.
1055 // FIXME: Save the __extension__ on the decl as a node somehow?
1056 ExtensionRAIIObject O(Diags);
1058 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1059 DeclGroupPtrTy Res =
1060 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, attrs);
1061 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1063 // Otherwise this was a unary __extension__ marker.
1064 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1066 if (Res.isInvalid()) {
1067 SkipUntil(tok::semi);
1071 // FIXME: Use attributes?
1072 // Eat the semicolon at the end of stmt and convert the expr into a
1074 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1075 R = Actions.ActOnExprStmt(Res, isExprValueDiscarded());
1080 Stmts.push_back(R.get());
1083 SourceLocation CloseLoc = Tok.getLocation();
1085 // We broke out of the while loop because we found a '}' or EOF.
1086 if (!T.consumeClose())
1087 // Recover by creating a compound statement with what we parsed so far,
1088 // instead of dropping everything and returning StmtError();
1089 CloseLoc = T.getCloseLocation();
1091 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1095 /// ParseParenExprOrCondition:
1096 /// [C ] '(' expression ')'
1097 /// [C++] '(' condition ')'
1098 /// [C++1z] '(' init-statement[opt] condition ')'
1100 /// This function parses and performs error recovery on the specified condition
1101 /// or expression (depending on whether we're in C++ or C mode). This function
1102 /// goes out of its way to recover well. It returns true if there was a parser
1103 /// error (the right paren couldn't be found), which indicates that the caller
1104 /// should try to recover harder. It returns false if the condition is
1105 /// successfully parsed. Note that a successful parse can still have semantic
1106 /// errors in the condition.
1107 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1108 Sema::ConditionResult &Cond,
1110 Sema::ConditionKind CK) {
1111 BalancedDelimiterTracker T(*this, tok::l_paren);
1114 if (getLangOpts().CPlusPlus)
1115 Cond = ParseCXXCondition(InitStmt, Loc, CK);
1117 ExprResult CondExpr = ParseExpression();
1119 // If required, convert to a boolean value.
1120 if (CondExpr.isInvalid())
1121 Cond = Sema::ConditionError();
1123 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1126 // If the parser was confused by the condition and we don't have a ')', try to
1127 // recover by skipping ahead to a semi and bailing out. If condexp is
1128 // semantically invalid but we have well formed code, keep going.
1129 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1130 SkipUntil(tok::semi);
1131 // Skipping may have stopped if it found the containing ')'. If so, we can
1132 // continue parsing the if statement.
1133 if (Tok.isNot(tok::r_paren))
1137 // Otherwise the condition is valid or the rparen is present.
1140 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1141 // that all callers are looking for a statement after the condition, so ")"
1143 while (Tok.is(tok::r_paren)) {
1144 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1145 << FixItHint::CreateRemoval(Tok.getLocation());
1153 /// ParseIfStatement
1154 /// if-statement: [C99 6.8.4.1]
1155 /// 'if' '(' expression ')' statement
1156 /// 'if' '(' expression ')' statement 'else' statement
1157 /// [C++] 'if' '(' condition ')' statement
1158 /// [C++] 'if' '(' condition ')' statement 'else' statement
1160 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1161 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1162 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1164 bool IsConstexpr = false;
1165 if (Tok.is(tok::kw_constexpr)) {
1166 Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
1167 : diag::ext_constexpr_if);
1172 if (Tok.isNot(tok::l_paren)) {
1173 Diag(Tok, diag::err_expected_lparen_after) << "if";
1174 SkipUntil(tok::semi);
1178 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1180 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1181 // the case for C90.
1184 // A name introduced by a declaration in a condition is in scope from its
1185 // point of declaration until the end of the substatements controlled by the
1188 // Names declared in the for-init-statement, and in the condition of if,
1189 // while, for, and switch statements are local to the if, while, for, or
1190 // switch statement (including the controlled statement).
1192 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1194 // Parse the condition.
1195 StmtResult InitStmt;
1196 Sema::ConditionResult Cond;
1197 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1198 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1199 : Sema::ConditionKind::Boolean))
1202 llvm::Optional<bool> ConstexprCondition;
1204 ConstexprCondition = Cond.getKnownValue();
1206 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1207 // there is no compound stmt. C90 does not have this clause. We only do this
1208 // if the body isn't a compound statement to avoid push/pop in common cases.
1211 // The substatement in a selection-statement (each substatement, in the else
1212 // form of the if statement) implicitly defines a local scope.
1214 // For C++ we create a scope for the condition and a new scope for
1215 // substatements because:
1216 // -When the 'then' scope exits, we want the condition declaration to still be
1217 // active for the 'else' scope too.
1218 // -Sema will detect name clashes by considering declarations of a
1219 // 'ControlScope' as part of its direct subscope.
1220 // -If we wanted the condition and substatement to be in the same scope, we
1221 // would have to notify ParseStatement not to create a new scope. It's
1222 // simpler to let it create a new scope.
1224 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1226 // Read the 'then' stmt.
1227 SourceLocation ThenStmtLoc = Tok.getLocation();
1229 SourceLocation InnerStatementTrailingElseLoc;
1230 StmtResult ThenStmt;
1232 EnterExpressionEvaluationContext PotentiallyDiscarded(
1233 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1234 Sema::ExpressionEvaluationContextRecord::EK_Other,
1235 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1236 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1239 // Pop the 'if' scope if needed.
1242 // If it has an else, parse it.
1243 SourceLocation ElseLoc;
1244 SourceLocation ElseStmtLoc;
1245 StmtResult ElseStmt;
1247 if (Tok.is(tok::kw_else)) {
1248 if (TrailingElseLoc)
1249 *TrailingElseLoc = Tok.getLocation();
1251 ElseLoc = ConsumeToken();
1252 ElseStmtLoc = Tok.getLocation();
1254 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1255 // there is no compound stmt. C90 does not have this clause. We only do
1256 // this if the body isn't a compound statement to avoid push/pop in common
1260 // The substatement in a selection-statement (each substatement, in the else
1261 // form of the if statement) implicitly defines a local scope.
1263 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1264 Tok.is(tok::l_brace));
1266 EnterExpressionEvaluationContext PotentiallyDiscarded(
1267 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1268 Sema::ExpressionEvaluationContextRecord::EK_Other,
1269 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1270 ElseStmt = ParseStatement();
1272 // Pop the 'else' scope if needed.
1274 } else if (Tok.is(tok::code_completion)) {
1275 Actions.CodeCompleteAfterIf(getCurScope());
1278 } else if (InnerStatementTrailingElseLoc.isValid()) {
1279 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1284 // If the then or else stmt is invalid and the other is valid (and present),
1285 // make turn the invalid one into a null stmt to avoid dropping the other
1286 // part. If both are invalid, return error.
1287 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1288 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1289 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1290 // Both invalid, or one is invalid and other is non-present: return error.
1294 // Now if either are invalid, replace with a ';'.
1295 if (ThenStmt.isInvalid())
1296 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1297 if (ElseStmt.isInvalid())
1298 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1300 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1301 ThenStmt.get(), ElseLoc, ElseStmt.get());
1304 /// ParseSwitchStatement
1305 /// switch-statement:
1306 /// 'switch' '(' expression ')' statement
1307 /// [C++] 'switch' '(' condition ')' statement
1308 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1309 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1310 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1312 if (Tok.isNot(tok::l_paren)) {
1313 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1314 SkipUntil(tok::semi);
1318 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1320 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1321 // not the case for C90. Start the switch scope.
1324 // A name introduced by a declaration in a condition is in scope from its
1325 // point of declaration until the end of the substatements controlled by the
1328 // Names declared in the for-init-statement, and in the condition of if,
1329 // while, for, and switch statements are local to the if, while, for, or
1330 // switch statement (including the controlled statement).
1332 unsigned ScopeFlags = Scope::SwitchScope;
1334 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1335 ParseScope SwitchScope(this, ScopeFlags);
1337 // Parse the condition.
1338 StmtResult InitStmt;
1339 Sema::ConditionResult Cond;
1340 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1341 Sema::ConditionKind::Switch))
1345 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1347 if (Switch.isInvalid()) {
1348 // Skip the switch body.
1349 // FIXME: This is not optimal recovery, but parsing the body is more
1350 // dangerous due to the presence of case and default statements, which
1351 // will have no place to connect back with the switch.
1352 if (Tok.is(tok::l_brace)) {
1354 SkipUntil(tok::r_brace);
1356 SkipUntil(tok::semi);
1360 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1361 // there is no compound stmt. C90 does not have this clause. We only do this
1362 // if the body isn't a compound statement to avoid push/pop in common cases.
1365 // The substatement in a selection-statement (each substatement, in the else
1366 // form of the if statement) implicitly defines a local scope.
1368 // See comments in ParseIfStatement for why we create a scope for the
1369 // condition and a new scope for substatement in C++.
1371 getCurScope()->AddFlags(Scope::BreakScope);
1372 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1374 // We have incremented the mangling number for the SwitchScope and the
1375 // InnerScope, which is one too many.
1377 getCurScope()->decrementMSManglingNumber();
1379 // Read the body statement.
1380 StmtResult Body(ParseStatement(TrailingElseLoc));
1386 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1389 /// ParseWhileStatement
1390 /// while-statement: [C99 6.8.5.1]
1391 /// 'while' '(' expression ')' statement
1392 /// [C++] 'while' '(' condition ')' statement
1393 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1394 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1395 SourceLocation WhileLoc = Tok.getLocation();
1396 ConsumeToken(); // eat the 'while'.
1398 if (Tok.isNot(tok::l_paren)) {
1399 Diag(Tok, diag::err_expected_lparen_after) << "while";
1400 SkipUntil(tok::semi);
1404 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1406 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1407 // the case for C90. Start the loop scope.
1410 // A name introduced by a declaration in a condition is in scope from its
1411 // point of declaration until the end of the substatements controlled by the
1414 // Names declared in the for-init-statement, and in the condition of if,
1415 // while, for, and switch statements are local to the if, while, for, or
1416 // switch statement (including the controlled statement).
1418 unsigned ScopeFlags;
1420 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1421 Scope::DeclScope | Scope::ControlScope;
1423 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1424 ParseScope WhileScope(this, ScopeFlags);
1426 // Parse the condition.
1427 Sema::ConditionResult Cond;
1428 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1429 Sema::ConditionKind::Boolean))
1432 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1433 // there is no compound stmt. C90 does not have this clause. We only do this
1434 // if the body isn't a compound statement to avoid push/pop in common cases.
1437 // The substatement in an iteration-statement implicitly defines a local scope
1438 // which is entered and exited each time through the loop.
1440 // See comments in ParseIfStatement for why we create a scope for the
1441 // condition and a new scope for substatement in C++.
1443 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1445 // Read the body statement.
1446 StmtResult Body(ParseStatement(TrailingElseLoc));
1448 // Pop the body scope if needed.
1452 if (Cond.isInvalid() || Body.isInvalid())
1455 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1458 /// ParseDoStatement
1459 /// do-statement: [C99 6.8.5.2]
1460 /// 'do' statement 'while' '(' expression ')' ';'
1461 /// Note: this lets the caller parse the end ';'.
1462 StmtResult Parser::ParseDoStatement() {
1463 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1464 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1466 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1467 // the case for C90. Start the loop scope.
1468 unsigned ScopeFlags;
1469 if (getLangOpts().C99)
1470 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1472 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1474 ParseScope DoScope(this, ScopeFlags);
1476 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1477 // there is no compound stmt. C90 does not have this clause. We only do this
1478 // if the body isn't a compound statement to avoid push/pop in common cases.
1481 // The substatement in an iteration-statement implicitly defines a local scope
1482 // which is entered and exited each time through the loop.
1484 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1485 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1487 // Read the body statement.
1488 StmtResult Body(ParseStatement());
1490 // Pop the body scope if needed.
1493 if (Tok.isNot(tok::kw_while)) {
1494 if (!Body.isInvalid()) {
1495 Diag(Tok, diag::err_expected_while);
1496 Diag(DoLoc, diag::note_matching) << "'do'";
1497 SkipUntil(tok::semi, StopBeforeMatch);
1501 SourceLocation WhileLoc = ConsumeToken();
1503 if (Tok.isNot(tok::l_paren)) {
1504 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1505 SkipUntil(tok::semi, StopBeforeMatch);
1509 // Parse the parenthesized expression.
1510 BalancedDelimiterTracker T(*this, tok::l_paren);
1513 // A do-while expression is not a condition, so can't have attributes.
1514 DiagnoseAndSkipCXX11Attributes();
1516 ExprResult Cond = ParseExpression();
1517 // Correct the typos in condition before closing the scope.
1518 if (Cond.isUsable())
1519 Cond = Actions.CorrectDelayedTyposInExpr(Cond);
1523 if (Cond.isInvalid() || Body.isInvalid())
1526 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1527 Cond.get(), T.getCloseLocation());
1530 bool Parser::isForRangeIdentifier() {
1531 assert(Tok.is(tok::identifier));
1533 const Token &Next = NextToken();
1534 if (Next.is(tok::colon))
1537 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1538 TentativeParsingAction PA(*this);
1540 SkipCXX11Attributes();
1541 bool Result = Tok.is(tok::colon);
1549 /// ParseForStatement
1550 /// for-statement: [C99 6.8.5.3]
1551 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1552 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1553 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1556 /// 'co_await'[opt] [Coroutines]
1557 /// '(' for-range-declaration ':' for-range-initializer ')'
1559 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1560 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1562 /// [C++] for-init-statement:
1563 /// [C++] expression-statement
1564 /// [C++] simple-declaration
1566 /// [C++0x] for-range-declaration:
1567 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1568 /// [C++0x] for-range-initializer:
1569 /// [C++0x] expression
1570 /// [C++0x] braced-init-list [TODO]
1571 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1572 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1573 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1575 SourceLocation CoawaitLoc;
1576 if (Tok.is(tok::kw_co_await))
1577 CoawaitLoc = ConsumeToken();
1579 if (Tok.isNot(tok::l_paren)) {
1580 Diag(Tok, diag::err_expected_lparen_after) << "for";
1581 SkipUntil(tok::semi);
1585 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1588 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1589 // the case for C90. Start the loop scope.
1592 // A name introduced by a declaration in a condition is in scope from its
1593 // point of declaration until the end of the substatements controlled by the
1596 // Names declared in the for-init-statement, and in the condition of if,
1597 // while, for, and switch statements are local to the if, while, for, or
1598 // switch statement (including the controlled statement).
1600 // Names declared in the for-init-statement are in the same declarative-region
1601 // as those declared in the condition.
1603 unsigned ScopeFlags = 0;
1605 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1607 ParseScope ForScope(this, ScopeFlags);
1609 BalancedDelimiterTracker T(*this, tok::l_paren);
1614 bool ForEach = false;
1615 StmtResult FirstPart;
1616 Sema::ConditionResult SecondPart;
1617 ExprResult Collection;
1618 ForRangeInfo ForRangeInfo;
1619 FullExprArg ThirdPart(Actions);
1621 if (Tok.is(tok::code_completion)) {
1622 Actions.CodeCompleteOrdinaryName(getCurScope(),
1623 C99orCXXorObjC? Sema::PCC_ForInit
1624 : Sema::PCC_Expression);
1629 ParsedAttributesWithRange attrs(AttrFactory);
1630 MaybeParseCXX11Attributes(attrs);
1632 SourceLocation EmptyInitStmtSemiLoc;
1634 // Parse the first part of the for specifier.
1635 if (Tok.is(tok::semi)) { // for (;
1636 ProhibitAttributes(attrs);
1637 // no first part, eat the ';'.
1638 SourceLocation SemiLoc = Tok.getLocation();
1639 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
1640 EmptyInitStmtSemiLoc = SemiLoc;
1642 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1643 isForRangeIdentifier()) {
1644 ProhibitAttributes(attrs);
1645 IdentifierInfo *Name = Tok.getIdentifierInfo();
1646 SourceLocation Loc = ConsumeToken();
1647 MaybeParseCXX11Attributes(attrs);
1649 ForRangeInfo.ColonLoc = ConsumeToken();
1650 if (Tok.is(tok::l_brace))
1651 ForRangeInfo.RangeExpr = ParseBraceInitializer();
1653 ForRangeInfo.RangeExpr = ParseExpression();
1655 Diag(Loc, diag::err_for_range_identifier)
1656 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
1657 ? FixItHint::CreateInsertion(Loc, "auto &&")
1660 ForRangeInfo.LoopVar = Actions.ActOnCXXForRangeIdentifier(
1661 getCurScope(), Loc, Name, attrs, attrs.Range.getEnd());
1662 } else if (isForInitDeclaration()) { // for (int X = 4;
1663 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1665 // Parse declaration, which eats the ';'.
1666 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
1667 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1668 Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
1671 // In C++0x, "for (T NS:a" might not be a typo for ::
1672 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1673 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1675 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1676 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1677 DeclaratorContext::ForContext, DeclEnd, attrs, false,
1678 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
1679 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1680 if (ForRangeInfo.ParsedForRangeDecl()) {
1681 Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11 ?
1682 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1683 ForRangeInfo.LoopVar = FirstPart;
1684 FirstPart = StmtResult();
1685 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1687 } else if ((ForEach = isTokIdentifier_in())) {
1688 Actions.ActOnForEachDeclStmt(DG);
1689 // ObjC: for (id x in expr)
1690 ConsumeToken(); // consume 'in'
1692 if (Tok.is(tok::code_completion)) {
1693 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1697 Collection = ParseExpression();
1699 Diag(Tok, diag::err_expected_semi_for);
1702 ProhibitAttributes(attrs);
1703 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1705 ForEach = isTokIdentifier_in();
1707 // Turn the expression into a stmt.
1708 if (!Value.isInvalid()) {
1710 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1712 // We already know this is not an init-statement within a for loop, so
1713 // if we are parsing a C++11 range-based for loop, we should treat this
1714 // expression statement as being a discarded value expression because
1715 // we will err below. This way we do not warn on an unused expression
1716 // that was an error in the first place, like with: for (expr : expr);
1717 bool IsRangeBasedFor =
1718 getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon);
1719 FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
1723 if (Tok.is(tok::semi)) {
1725 } else if (ForEach) {
1726 ConsumeToken(); // consume 'in'
1728 if (Tok.is(tok::code_completion)) {
1729 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1733 Collection = ParseExpression();
1734 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1735 // User tried to write the reasonable, but ill-formed, for-range-statement
1736 // for (expr : expr) { ... }
1737 Diag(Tok, diag::err_for_range_expected_decl)
1738 << FirstPart.get()->getSourceRange();
1739 SkipUntil(tok::r_paren, StopBeforeMatch);
1740 SecondPart = Sema::ConditionError();
1742 if (!Value.isInvalid()) {
1743 Diag(Tok, diag::err_expected_semi_for);
1745 // Skip until semicolon or rparen, don't consume it.
1746 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1747 if (Tok.is(tok::semi))
1753 // Parse the second part of the for specifier.
1754 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1755 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
1756 !SecondPart.isInvalid()) {
1757 // Parse the second part of the for specifier.
1758 if (Tok.is(tok::semi)) { // for (...;;
1760 } else if (Tok.is(tok::r_paren)) {
1761 // missing both semicolons.
1763 if (getLangOpts().CPlusPlus) {
1764 // C++2a: We've parsed an init-statement; we might have a
1765 // for-range-declaration next.
1766 bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
1767 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1769 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean,
1770 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
1772 if (ForRangeInfo.ParsedForRangeDecl()) {
1773 Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
1774 : ForRangeInfo.ColonLoc,
1775 getLangOpts().CPlusPlus2a
1776 ? diag::warn_cxx17_compat_for_range_init_stmt
1777 : diag::ext_for_range_init_stmt)
1778 << (FirstPart.get() ? FirstPart.get()->getSourceRange()
1780 if (EmptyInitStmtSemiLoc.isValid()) {
1781 Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
1783 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
1787 ExprResult SecondExpr = ParseExpression();
1788 if (SecondExpr.isInvalid())
1789 SecondPart = Sema::ConditionError();
1792 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1793 Sema::ConditionKind::Boolean);
1798 // Parse the third part of the for statement.
1799 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
1800 if (Tok.isNot(tok::semi)) {
1801 if (!SecondPart.isInvalid())
1802 Diag(Tok, diag::err_expected_semi_for);
1804 // Skip until semicolon or rparen, don't consume it.
1805 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1808 if (Tok.is(tok::semi)) {
1812 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1813 ExprResult Third = ParseExpression();
1814 // FIXME: The C++11 standard doesn't actually say that this is a
1815 // discarded-value expression, but it clearly should be.
1816 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1822 // C++ Coroutines [stmt.iter]:
1823 // 'co_await' can only be used for a range-based for statement.
1824 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
1825 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1826 CoawaitLoc = SourceLocation();
1829 // We need to perform most of the semantic analysis for a C++0x for-range
1830 // statememt before parsing the body, in order to be able to deduce the type
1831 // of an auto-typed loop variable.
1832 StmtResult ForRangeStmt;
1833 StmtResult ForEachStmt;
1835 if (ForRangeInfo.ParsedForRangeDecl()) {
1836 ExprResult CorrectedRange =
1837 Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());
1838 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1839 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1840 ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),
1841 T.getCloseLocation(), Sema::BFRK_Build);
1843 // Similarly, we need to do the semantic analysis for a for-range
1844 // statement immediately in order to close over temporaries correctly.
1845 } else if (ForEach) {
1846 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1849 T.getCloseLocation());
1851 // In OpenMP loop region loop control variable must be captured and be
1852 // private. Perform analysis of first part (if any).
1853 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1854 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1858 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1859 // there is no compound stmt. C90 does not have this clause. We only do this
1860 // if the body isn't a compound statement to avoid push/pop in common cases.
1863 // The substatement in an iteration-statement implicitly defines a local scope
1864 // which is entered and exited each time through the loop.
1866 // See comments in ParseIfStatement for why we create a scope for
1867 // for-init-statement/condition and a new scope for substatement in C++.
1869 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1870 Tok.is(tok::l_brace));
1872 // The body of the for loop has the same local mangling number as the
1873 // for-init-statement.
1874 // It will only be incremented if the body contains other things that would
1875 // normally increment the mangling number (like a compound statement).
1877 getCurScope()->decrementMSManglingNumber();
1879 // Read the body statement.
1880 StmtResult Body(ParseStatement(TrailingElseLoc));
1882 // Pop the body scope if needed.
1885 // Leave the for-scope.
1888 if (Body.isInvalid())
1892 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1895 if (ForRangeInfo.ParsedForRangeDecl())
1896 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1898 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1899 SecondPart, ThirdPart, T.getCloseLocation(),
1903 /// ParseGotoStatement
1905 /// 'goto' identifier ';'
1906 /// [GNU] 'goto' '*' expression ';'
1908 /// Note: this lets the caller parse the end ';'.
1910 StmtResult Parser::ParseGotoStatement() {
1911 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1912 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1915 if (Tok.is(tok::identifier)) {
1916 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1918 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1920 } else if (Tok.is(tok::star)) {
1921 // GNU indirect goto extension.
1922 Diag(Tok, diag::ext_gnu_indirect_goto);
1923 SourceLocation StarLoc = ConsumeToken();
1924 ExprResult R(ParseExpression());
1925 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1926 SkipUntil(tok::semi, StopBeforeMatch);
1929 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1931 Diag(Tok, diag::err_expected) << tok::identifier;
1938 /// ParseContinueStatement
1942 /// Note: this lets the caller parse the end ';'.
1944 StmtResult Parser::ParseContinueStatement() {
1945 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1946 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1949 /// ParseBreakStatement
1953 /// Note: this lets the caller parse the end ';'.
1955 StmtResult Parser::ParseBreakStatement() {
1956 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1957 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1960 /// ParseReturnStatement
1962 /// 'return' expression[opt] ';'
1963 /// 'return' braced-init-list ';'
1964 /// 'co_return' expression[opt] ';'
1965 /// 'co_return' braced-init-list ';'
1966 StmtResult Parser::ParseReturnStatement() {
1967 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1968 "Not a return stmt!");
1969 bool IsCoreturn = Tok.is(tok::kw_co_return);
1970 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1973 if (Tok.isNot(tok::semi)) {
1974 // FIXME: Code completion for co_return.
1975 if (Tok.is(tok::code_completion) && !IsCoreturn) {
1976 Actions.CodeCompleteReturn(getCurScope());
1981 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1982 R = ParseInitializer();
1984 Diag(R.get()->getBeginLoc(),
1985 getLangOpts().CPlusPlus11
1986 ? diag::warn_cxx98_compat_generalized_initializer_lists
1987 : diag::ext_generalized_initializer_lists)
1988 << R.get()->getSourceRange();
1990 R = ParseExpression();
1991 if (R.isInvalid()) {
1992 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1997 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
1998 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
2001 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
2002 AllowedConstructsKind Allowed,
2003 SourceLocation *TrailingElseLoc,
2004 ParsedAttributesWithRange &Attrs) {
2005 // Create temporary attribute list.
2006 ParsedAttributesWithRange TempAttrs(AttrFactory);
2008 // Get loop hints and consume annotated token.
2009 while (Tok.is(tok::annot_pragma_loop_hint)) {
2011 if (!HandlePragmaLoopHint(Hint))
2014 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
2015 ArgsUnion(Hint.ValueExpr)};
2016 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
2017 Hint.PragmaNameLoc->Loc, ArgHints, 4,
2018 ParsedAttr::AS_Pragma);
2021 // Get the next statement.
2022 MaybeParseCXX11Attributes(Attrs);
2024 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
2025 Stmts, Allowed, TrailingElseLoc, Attrs);
2027 Attrs.takeAllFrom(TempAttrs);
2031 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2032 assert(Tok.is(tok::l_brace));
2033 SourceLocation LBraceLoc = Tok.getLocation();
2035 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
2036 "parsing function body");
2038 // Save and reset current vtordisp stack if we have entered a C++ method body.
2040 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2041 Sema::PragmaStackSentinelRAII
2042 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2044 // Do not enter a scope for the brace, as the arguments are in the same scope
2045 // (the function body) as the body itself. Instead, just read the statement
2046 // list and put it into a CompoundStmt for safe keeping.
2047 StmtResult FnBody(ParseCompoundStatementBody());
2049 // If the function body could not be parsed, make a bogus compoundstmt.
2050 if (FnBody.isInvalid()) {
2051 Sema::CompoundScopeRAII CompoundScope(Actions);
2052 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2056 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2059 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
2061 /// function-try-block:
2062 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2064 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2065 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2066 SourceLocation TryLoc = ConsumeToken();
2068 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
2069 "parsing function try block");
2071 // Constructor initializer list?
2072 if (Tok.is(tok::colon))
2073 ParseConstructorInitializer(Decl);
2075 Actions.ActOnDefaultCtorInitializers(Decl);
2077 // Save and reset current vtordisp stack if we have entered a C++ method body.
2079 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2080 Sema::PragmaStackSentinelRAII
2081 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2083 SourceLocation LBraceLoc = Tok.getLocation();
2084 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2085 // If we failed to parse the try-catch, we just give the function an empty
2086 // compound statement as the body.
2087 if (FnBody.isInvalid()) {
2088 Sema::CompoundScopeRAII CompoundScope(Actions);
2089 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2093 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2096 bool Parser::trySkippingFunctionBody() {
2097 assert(SkipFunctionBodies &&
2098 "Should only be called when SkipFunctionBodies is enabled");
2099 if (!PP.isCodeCompletionEnabled()) {
2104 // We're in code-completion mode. Skip parsing for all function bodies unless
2105 // the body contains the code-completion point.
2106 TentativeParsingAction PA(*this);
2107 bool IsTryCatch = Tok.is(tok::kw_try);
2109 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2110 if (llvm::any_of(Toks, [](const Token &Tok) {
2111 return Tok.is(tok::code_completion);
2116 if (ErrorInPrologue) {
2118 SkipMalformedDecl();
2121 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2125 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2126 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2127 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2136 /// ParseCXXTryBlock - Parse a C++ try-block.
2139 /// 'try' compound-statement handler-seq
2141 StmtResult Parser::ParseCXXTryBlock() {
2142 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2144 SourceLocation TryLoc = ConsumeToken();
2145 return ParseCXXTryBlockCommon(TryLoc);
2148 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2149 /// function-try-block.
2152 /// 'try' compound-statement handler-seq
2154 /// function-try-block:
2155 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2158 /// handler handler-seq[opt]
2160 /// [Borland] try-block:
2161 /// 'try' compound-statement seh-except-block
2162 /// 'try' compound-statement seh-finally-block
2164 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2165 if (Tok.isNot(tok::l_brace))
2166 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2168 StmtResult TryBlock(ParseCompoundStatement(
2169 /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2170 Scope::CompoundStmtScope |
2171 (FnTry ? Scope::FnTryCatchScope : 0)));
2172 if (TryBlock.isInvalid())
2175 // Borland allows SEH-handlers with 'try'
2177 if ((Tok.is(tok::identifier) &&
2178 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2179 Tok.is(tok::kw___finally)) {
2180 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2182 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2183 SourceLocation Loc = ConsumeToken();
2184 Handler = ParseSEHExceptBlock(Loc);
2187 SourceLocation Loc = ConsumeToken();
2188 Handler = ParseSEHFinallyBlock(Loc);
2190 if(Handler.isInvalid())
2193 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2199 StmtVector Handlers;
2201 // C++11 attributes can't appear here, despite this context seeming
2203 DiagnoseAndSkipCXX11Attributes();
2205 if (Tok.isNot(tok::kw_catch))
2206 return StmtError(Diag(Tok, diag::err_expected_catch));
2207 while (Tok.is(tok::kw_catch)) {
2208 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2209 if (!Handler.isInvalid())
2210 Handlers.push_back(Handler.get());
2212 // Don't bother creating the full statement if we don't have any usable
2214 if (Handlers.empty())
2217 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2221 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2224 /// 'catch' '(' exception-declaration ')' compound-statement
2226 /// exception-declaration:
2227 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2228 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2231 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2232 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2234 SourceLocation CatchLoc = ConsumeToken();
2236 BalancedDelimiterTracker T(*this, tok::l_paren);
2237 if (T.expectAndConsume())
2241 // The name in a catch exception-declaration is local to the handler and
2242 // shall not be redeclared in the outermost block of the handler.
2243 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2244 (FnCatch ? Scope::FnTryCatchScope : 0));
2246 // exception-declaration is equivalent to '...' or a parameter-declaration
2247 // without default arguments.
2248 Decl *ExceptionDecl = nullptr;
2249 if (Tok.isNot(tok::ellipsis)) {
2250 ParsedAttributesWithRange Attributes(AttrFactory);
2251 MaybeParseCXX11Attributes(Attributes);
2253 DeclSpec DS(AttrFactory);
2254 DS.takeAttributesFrom(Attributes);
2256 if (ParseCXXTypeSpecifierSeq(DS))
2259 Declarator ExDecl(DS, DeclaratorContext::CXXCatchContext);
2260 ParseDeclarator(ExDecl);
2261 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2266 if (T.getCloseLocation().isInvalid())
2269 if (Tok.isNot(tok::l_brace))
2270 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2272 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2273 StmtResult Block(ParseCompoundStatement());
2274 if (Block.isInvalid())
2277 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2280 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2281 IfExistsCondition Result;
2282 if (ParseMicrosoftIfExistsCondition(Result))
2285 // Handle dependent statements by parsing the braces as a compound statement.
2286 // This is not the same behavior as Visual C++, which don't treat this as a
2287 // compound statement, but for Clang's type checking we can't have anything
2288 // inside these braces escaping to the surrounding code.
2289 if (Result.Behavior == IEB_Dependent) {
2290 if (!Tok.is(tok::l_brace)) {
2291 Diag(Tok, diag::err_expected) << tok::l_brace;
2295 StmtResult Compound = ParseCompoundStatement();
2296 if (Compound.isInvalid())
2299 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2304 if (DepResult.isUsable())
2305 Stmts.push_back(DepResult.get());
2309 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2310 if (Braces.consumeOpen()) {
2311 Diag(Tok, diag::err_expected) << tok::l_brace;
2315 switch (Result.Behavior) {
2317 // Parse the statements below.
2321 llvm_unreachable("Dependent case handled above");
2328 // Condition is true, parse the statements.
2329 while (Tok.isNot(tok::r_brace)) {
2330 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2332 Stmts.push_back(R.get());
2334 Braces.consumeClose();
2337 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2338 MaybeParseGNUAttributes(Attrs);
2343 if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
2346 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2347 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);