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/Parser.h"
19 #include "clang/Parse/RAIIObjectsForParser.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/LoopHint.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_opencl_extension:
352 ProhibitAttributes(Attrs);
353 HandlePragmaOpenCLExtension();
356 case tok::annot_pragma_captured:
357 ProhibitAttributes(Attrs);
358 return HandlePragmaCaptured();
360 case tok::annot_pragma_openmp:
361 ProhibitAttributes(Attrs);
362 return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
364 case tok::annot_pragma_ms_pointers_to_members:
365 ProhibitAttributes(Attrs);
366 HandlePragmaMSPointersToMembers();
369 case tok::annot_pragma_ms_pragma:
370 ProhibitAttributes(Attrs);
371 HandlePragmaMSPragma();
374 case tok::annot_pragma_ms_vtordisp:
375 ProhibitAttributes(Attrs);
376 HandlePragmaMSVtorDisp();
379 case tok::annot_pragma_loop_hint:
380 ProhibitAttributes(Attrs);
381 return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
383 case tok::annot_pragma_dump:
387 case tok::annot_pragma_attribute:
388 HandlePragmaAttribute();
392 // If we reached this code, the statement must end in a semicolon.
393 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
394 // If the result was valid, then we do want to diagnose this. Use
395 // ExpectAndConsume to emit the diagnostic, even though we know it won't
397 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
398 // Skip until we see a } or ;, but don't eat it.
399 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
405 /// Parse an expression statement.
406 StmtResult Parser::ParseExprStatement() {
407 // If a case keyword is missing, this is where it should be inserted.
408 Token OldToken = Tok;
410 ExprStatementTokLoc = Tok.getLocation();
412 // expression[opt] ';'
413 ExprResult Expr(ParseExpression());
414 if (Expr.isInvalid()) {
415 // If the expression is invalid, skip ahead to the next semicolon or '}'.
416 // Not doing this opens us up to the possibility of infinite loops if
417 // ParseExpression does not consume any tokens.
418 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
419 if (Tok.is(tok::semi))
421 return Actions.ActOnExprStmtError();
424 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
425 Actions.CheckCaseExpression(Expr.get())) {
426 // If a constant expression is followed by a colon inside a switch block,
427 // suggest a missing case keyword.
428 Diag(OldToken, diag::err_expected_case_before_expression)
429 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
431 // Recover parsing as a case statement.
432 return ParseCaseStatement(/*MissingCase=*/true, Expr);
435 // Otherwise, eat the semicolon.
436 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
437 return Actions.ActOnExprStmt(Expr);
440 /// ParseSEHTryBlockCommon
443 /// '__try' compound-statement seh-handler
447 /// seh-finally-block
449 StmtResult Parser::ParseSEHTryBlock() {
450 assert(Tok.is(tok::kw___try) && "Expected '__try'");
451 SourceLocation TryLoc = ConsumeToken();
453 if (Tok.isNot(tok::l_brace))
454 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
456 StmtResult TryBlock(ParseCompoundStatement(
457 /*isStmtExpr=*/false,
458 Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
459 if (TryBlock.isInvalid())
463 if (Tok.is(tok::identifier) &&
464 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
465 SourceLocation Loc = ConsumeToken();
466 Handler = ParseSEHExceptBlock(Loc);
467 } else if (Tok.is(tok::kw___finally)) {
468 SourceLocation Loc = ConsumeToken();
469 Handler = ParseSEHFinallyBlock(Loc);
471 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
474 if(Handler.isInvalid())
477 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
483 /// ParseSEHExceptBlock - Handle __except
485 /// seh-except-block:
486 /// '__except' '(' seh-filter-expression ')' compound-statement
488 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
489 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
490 raii2(Ident___exception_code, false),
491 raii3(Ident_GetExceptionCode, false);
493 if (ExpectAndConsume(tok::l_paren))
496 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
497 Scope::SEHExceptScope);
499 if (getLangOpts().Borland) {
500 Ident__exception_info->setIsPoisoned(false);
501 Ident___exception_info->setIsPoisoned(false);
502 Ident_GetExceptionInfo->setIsPoisoned(false);
505 ExprResult FilterExpr;
507 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
508 Scope::SEHFilterScope);
509 FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
512 if (getLangOpts().Borland) {
513 Ident__exception_info->setIsPoisoned(true);
514 Ident___exception_info->setIsPoisoned(true);
515 Ident_GetExceptionInfo->setIsPoisoned(true);
518 if(FilterExpr.isInvalid())
521 if (ExpectAndConsume(tok::r_paren))
524 if (Tok.isNot(tok::l_brace))
525 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
527 StmtResult Block(ParseCompoundStatement());
529 if(Block.isInvalid())
532 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
535 /// ParseSEHFinallyBlock - Handle __finally
537 /// seh-finally-block:
538 /// '__finally' compound-statement
540 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
541 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
542 raii2(Ident___abnormal_termination, false),
543 raii3(Ident_AbnormalTermination, false);
545 if (Tok.isNot(tok::l_brace))
546 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
548 ParseScope FinallyScope(this, 0);
549 Actions.ActOnStartSEHFinallyBlock();
551 StmtResult Block(ParseCompoundStatement());
552 if(Block.isInvalid()) {
553 Actions.ActOnAbortSEHFinallyBlock();
557 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
562 /// seh-leave-statement:
565 StmtResult Parser::ParseSEHLeaveStatement() {
566 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
567 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
570 /// ParseLabeledStatement - We have an identifier and a ':' after it.
572 /// labeled-statement:
573 /// identifier ':' statement
574 /// [GNU] identifier ':' attributes[opt] statement
576 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
577 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
578 "Not an identifier!");
580 Token IdentTok = Tok; // Save the whole token.
581 ConsumeToken(); // eat the identifier.
583 assert(Tok.is(tok::colon) && "Not a label!");
585 // identifier ':' statement
586 SourceLocation ColonLoc = ConsumeToken();
588 // Read label attributes, if present.
590 if (Tok.is(tok::kw___attribute)) {
591 ParsedAttributesWithRange TempAttrs(AttrFactory);
592 ParseGNUAttributes(TempAttrs);
594 // In C++, GNU attributes only apply to the label if they are followed by a
595 // semicolon, to disambiguate label attributes from attributes on a labeled
598 // This doesn't quite match what GCC does; if the attribute list is empty
599 // and followed by a semicolon, GCC will reject (it appears to parse the
600 // attributes as part of a statement in that case). That looks like a bug.
601 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
602 attrs.takeAllFrom(TempAttrs);
603 else if (isDeclarationStatement()) {
605 // FIXME: We should do this whether or not we have a declaration
606 // statement, but that doesn't work correctly (because ProhibitAttributes
607 // can't handle GNU attributes), so only call it in the one case where
608 // GNU attributes are allowed.
609 SubStmt = ParseStatementOrDeclarationAfterAttributes(
610 Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
612 if (!TempAttrs.empty() && !SubStmt.isInvalid())
613 SubStmt = Actions.ProcessStmtAttributes(SubStmt.get(), TempAttrs,
616 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
620 // If we've not parsed a statement yet, parse one now.
621 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
622 SubStmt = ParseStatement();
624 // Broken substmt shouldn't prevent the label from being added to the AST.
625 if (SubStmt.isInvalid())
626 SubStmt = Actions.ActOnNullStmt(ColonLoc);
628 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
629 IdentTok.getLocation());
630 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, attrs);
633 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
637 /// ParseCaseStatement
638 /// labeled-statement:
639 /// 'case' constant-expression ':' statement
640 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
642 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
643 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
645 // It is very very common for code to contain many case statements recursively
646 // nested, as in (but usually without indentation):
653 // Parsing this naively works, but is both inefficient and can cause us to run
654 // out of stack space in our recursive descent parser. As a special case,
655 // flatten this recursion into an iterative loop. This is complex and gross,
656 // but all the grossness is constrained to ParseCaseStatement (and some
657 // weirdness in the actions), so this is just local grossness :).
659 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
661 StmtResult TopLevelCase(true);
663 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
664 // gets updated each time a new case is parsed, and whose body is unset so
665 // far. When parsing 'case 4', this is the 'case 3' node.
666 Stmt *DeepestParsedCaseStmt = nullptr;
668 // While we have case statements, eat and stack them.
669 SourceLocation ColonLoc;
671 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
672 ConsumeToken(); // eat the 'case'.
673 ColonLoc = SourceLocation();
675 if (Tok.is(tok::code_completion)) {
676 Actions.CodeCompleteCase(getCurScope());
681 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
682 /// Disable this form of error recovery while we're parsing the case
684 ColonProtectionRAIIObject ColonProtection(*this);
688 LHS = ParseCaseExpression(CaseLoc);
689 if (LHS.isInvalid()) {
690 // If constant-expression is parsed unsuccessfully, recover by skipping
691 // current case statement (moving to the colon that ends it).
692 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
700 // GNU case range extension.
701 SourceLocation DotDotDotLoc;
703 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
704 Diag(DotDotDotLoc, diag::ext_gnu_case_range);
705 RHS = ParseCaseExpression(CaseLoc);
706 if (RHS.isInvalid()) {
707 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
712 ColonProtection.restore();
714 if (TryConsumeToken(tok::colon, ColonLoc)) {
715 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
716 TryConsumeToken(tok::coloncolon, ColonLoc)) {
717 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
718 Diag(ColonLoc, diag::err_expected_after)
719 << "'case'" << tok::colon
720 << FixItHint::CreateReplacement(ColonLoc, ":");
722 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
723 Diag(ExpectedLoc, diag::err_expected_after)
724 << "'case'" << tok::colon
725 << FixItHint::CreateInsertion(ExpectedLoc, ":");
726 ColonLoc = ExpectedLoc;
730 Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
732 // If we had a sema error parsing this case, then just ignore it and
733 // continue parsing the sub-stmt.
734 if (Case.isInvalid()) {
735 if (TopLevelCase.isInvalid()) // No parsed case stmts.
736 return ParseStatement(/*TrailingElseLoc=*/nullptr,
737 /*AllowOpenMPStandalone=*/true);
738 // Otherwise, just don't add it as a nested case.
740 // If this is the first case statement we parsed, it becomes TopLevelCase.
741 // Otherwise we link it into the current chain.
742 Stmt *NextDeepest = Case.get();
743 if (TopLevelCase.isInvalid())
746 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
747 DeepestParsedCaseStmt = NextDeepest;
750 // Handle all case statements.
751 } while (Tok.is(tok::kw_case));
753 // If we found a non-case statement, start by parsing it.
756 if (Tok.isNot(tok::r_brace)) {
757 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
758 /*AllowOpenMPStandalone=*/true);
760 // Nicely diagnose the common error "switch (X) { case 4: }", which is
761 // not valid. If ColonLoc doesn't point to a valid text location, there was
762 // another parsing error, so avoid producing extra diagnostics.
763 if (ColonLoc.isValid()) {
764 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
765 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
766 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
768 SubStmt = StmtError();
771 // Install the body into the most deeply-nested case.
772 if (DeepestParsedCaseStmt) {
773 // Broken sub-stmt shouldn't prevent forming the case statement properly.
774 if (SubStmt.isInvalid())
775 SubStmt = Actions.ActOnNullStmt(SourceLocation());
776 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
779 // Return the top level parsed statement tree.
783 /// ParseDefaultStatement
784 /// labeled-statement:
785 /// 'default' ':' statement
786 /// Note that this does not parse the 'statement' at the end.
788 StmtResult Parser::ParseDefaultStatement() {
789 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
790 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
792 SourceLocation ColonLoc;
793 if (TryConsumeToken(tok::colon, ColonLoc)) {
794 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
795 // Treat "default;" as a typo for "default:".
796 Diag(ColonLoc, diag::err_expected_after)
797 << "'default'" << tok::colon
798 << FixItHint::CreateReplacement(ColonLoc, ":");
800 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
801 Diag(ExpectedLoc, diag::err_expected_after)
802 << "'default'" << tok::colon
803 << FixItHint::CreateInsertion(ExpectedLoc, ":");
804 ColonLoc = ExpectedLoc;
809 if (Tok.isNot(tok::r_brace)) {
810 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
811 /*AllowOpenMPStandalone=*/true);
813 // Diagnose the common error "switch (X) {... default: }", which is
815 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
816 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
817 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
821 // Broken sub-stmt shouldn't prevent forming the case statement properly.
822 if (SubStmt.isInvalid())
823 SubStmt = Actions.ActOnNullStmt(ColonLoc);
825 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
826 SubStmt.get(), getCurScope());
829 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
830 return ParseCompoundStatement(isStmtExpr,
831 Scope::DeclScope | Scope::CompoundStmtScope);
834 /// ParseCompoundStatement - Parse a "{}" block.
836 /// compound-statement: [C99 6.8.2]
837 /// { block-item-list[opt] }
838 /// [GNU] { label-declarations block-item-list } [TODO]
842 /// block-item-list block-item
846 /// [GNU] '__extension__' declaration
849 /// [GNU] label-declarations:
850 /// [GNU] label-declaration
851 /// [GNU] label-declarations label-declaration
853 /// [GNU] label-declaration:
854 /// [GNU] '__label__' identifier-list ';'
856 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
857 unsigned ScopeFlags) {
858 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
860 // Enter a scope to hold everything within the compound stmt. Compound
861 // statements can always hold declarations.
862 ParseScope CompoundScope(this, ScopeFlags);
864 // Parse the statements in the body.
865 return ParseCompoundStatementBody(isStmtExpr);
868 /// Parse any pragmas at the start of the compound expression. We handle these
869 /// separately since some pragmas (FP_CONTRACT) must appear before any C
870 /// statement in the compound, but may be intermingled with other pragmas.
871 void Parser::ParseCompoundStatementLeadingPragmas() {
872 bool checkForPragmas = true;
873 while (checkForPragmas) {
874 switch (Tok.getKind()) {
875 case tok::annot_pragma_vis:
876 HandlePragmaVisibility();
878 case tok::annot_pragma_pack:
881 case tok::annot_pragma_msstruct:
882 HandlePragmaMSStruct();
884 case tok::annot_pragma_align:
887 case tok::annot_pragma_weak:
890 case tok::annot_pragma_weakalias:
891 HandlePragmaWeakAlias();
893 case tok::annot_pragma_redefine_extname:
894 HandlePragmaRedefineExtname();
896 case tok::annot_pragma_opencl_extension:
897 HandlePragmaOpenCLExtension();
899 case tok::annot_pragma_fp_contract:
900 HandlePragmaFPContract();
902 case tok::annot_pragma_fp:
905 case tok::annot_pragma_ms_pointers_to_members:
906 HandlePragmaMSPointersToMembers();
908 case tok::annot_pragma_ms_pragma:
909 HandlePragmaMSPragma();
911 case tok::annot_pragma_ms_vtordisp:
912 HandlePragmaMSVtorDisp();
914 case tok::annot_pragma_dump:
918 checkForPragmas = false;
925 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
926 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
927 /// consume the '}' at the end of the block. It does not manipulate the scope
929 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
930 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
932 "in compound statement ('{}')");
934 // Record the state of the FP_CONTRACT pragma, restore on leaving the
935 // compound statement.
936 Sema::FPContractStateRAII SaveFPContractState(Actions);
938 InMessageExpressionRAIIObject InMessage(*this, false);
939 BalancedDelimiterTracker T(*this, tok::l_brace);
943 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
945 // Parse any pragmas at the beginning of the compound statement.
946 ParseCompoundStatementLeadingPragmas();
950 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
951 // only allowed at the start of a compound stmt regardless of the language.
952 while (Tok.is(tok::kw___label__)) {
953 SourceLocation LabelLoc = ConsumeToken();
955 SmallVector<Decl *, 8> DeclsInGroup;
957 if (Tok.isNot(tok::identifier)) {
958 Diag(Tok, diag::err_expected) << tok::identifier;
962 IdentifierInfo *II = Tok.getIdentifierInfo();
963 SourceLocation IdLoc = ConsumeToken();
964 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
966 if (!TryConsumeToken(tok::comma))
970 DeclSpec DS(AttrFactory);
972 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
973 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
975 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
977 Stmts.push_back(R.get());
980 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
981 Tok.isNot(tok::eof)) {
982 if (Tok.is(tok::annot_pragma_unused)) {
983 HandlePragmaUnused();
988 if (Tok.isNot(tok::kw___extension__)) {
989 R = ParseStatementOrDeclaration(Stmts, ACK_Any);
991 // __extension__ can start declarations and it can also be a unary
992 // operator for expressions. Consume multiple __extension__ markers here
993 // until we can determine which is which.
994 // FIXME: This loses extension expressions in the AST!
995 SourceLocation ExtLoc = ConsumeToken();
996 while (Tok.is(tok::kw___extension__))
999 ParsedAttributesWithRange attrs(AttrFactory);
1000 MaybeParseCXX11Attributes(attrs, nullptr,
1001 /*MightBeObjCMessageSend*/ true);
1003 // If this is the start of a declaration, parse it as such.
1004 if (isDeclarationStatement()) {
1005 // __extension__ silences extension warnings in the subdeclaration.
1006 // FIXME: Save the __extension__ on the decl as a node somehow?
1007 ExtensionRAIIObject O(Diags);
1009 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1010 DeclGroupPtrTy Res =
1011 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, attrs);
1012 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1014 // Otherwise this was a unary __extension__ marker.
1015 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1017 if (Res.isInvalid()) {
1018 SkipUntil(tok::semi);
1022 // FIXME: Use attributes?
1023 // Eat the semicolon at the end of stmt and convert the expr into a
1025 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1026 R = Actions.ActOnExprStmt(Res);
1031 Stmts.push_back(R.get());
1034 SourceLocation CloseLoc = Tok.getLocation();
1036 // We broke out of the while loop because we found a '}' or EOF.
1037 if (!T.consumeClose())
1038 // Recover by creating a compound statement with what we parsed so far,
1039 // instead of dropping everything and returning StmtError();
1040 CloseLoc = T.getCloseLocation();
1042 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1046 /// ParseParenExprOrCondition:
1047 /// [C ] '(' expression ')'
1048 /// [C++] '(' condition ')'
1049 /// [C++1z] '(' init-statement[opt] condition ')'
1051 /// This function parses and performs error recovery on the specified condition
1052 /// or expression (depending on whether we're in C++ or C mode). This function
1053 /// goes out of its way to recover well. It returns true if there was a parser
1054 /// error (the right paren couldn't be found), which indicates that the caller
1055 /// should try to recover harder. It returns false if the condition is
1056 /// successfully parsed. Note that a successful parse can still have semantic
1057 /// errors in the condition.
1058 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1059 Sema::ConditionResult &Cond,
1061 Sema::ConditionKind CK) {
1062 BalancedDelimiterTracker T(*this, tok::l_paren);
1065 if (getLangOpts().CPlusPlus)
1066 Cond = ParseCXXCondition(InitStmt, Loc, CK);
1068 ExprResult CondExpr = ParseExpression();
1070 // If required, convert to a boolean value.
1071 if (CondExpr.isInvalid())
1072 Cond = Sema::ConditionError();
1074 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1077 // If the parser was confused by the condition and we don't have a ')', try to
1078 // recover by skipping ahead to a semi and bailing out. If condexp is
1079 // semantically invalid but we have well formed code, keep going.
1080 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1081 SkipUntil(tok::semi);
1082 // Skipping may have stopped if it found the containing ')'. If so, we can
1083 // continue parsing the if statement.
1084 if (Tok.isNot(tok::r_paren))
1088 // Otherwise the condition is valid or the rparen is present.
1091 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1092 // that all callers are looking for a statement after the condition, so ")"
1094 while (Tok.is(tok::r_paren)) {
1095 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1096 << FixItHint::CreateRemoval(Tok.getLocation());
1104 /// ParseIfStatement
1105 /// if-statement: [C99 6.8.4.1]
1106 /// 'if' '(' expression ')' statement
1107 /// 'if' '(' expression ')' statement 'else' statement
1108 /// [C++] 'if' '(' condition ')' statement
1109 /// [C++] 'if' '(' condition ')' statement 'else' statement
1111 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1112 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1113 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1115 bool IsConstexpr = false;
1116 if (Tok.is(tok::kw_constexpr)) {
1117 Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
1118 : diag::ext_constexpr_if);
1123 if (Tok.isNot(tok::l_paren)) {
1124 Diag(Tok, diag::err_expected_lparen_after) << "if";
1125 SkipUntil(tok::semi);
1129 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1131 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1132 // the case for C90.
1135 // A name introduced by a declaration in a condition is in scope from its
1136 // point of declaration until the end of the substatements controlled by the
1139 // Names declared in the for-init-statement, and in the condition of if,
1140 // while, for, and switch statements are local to the if, while, for, or
1141 // switch statement (including the controlled statement).
1143 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1145 // Parse the condition.
1146 StmtResult InitStmt;
1147 Sema::ConditionResult Cond;
1148 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1149 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1150 : Sema::ConditionKind::Boolean))
1153 llvm::Optional<bool> ConstexprCondition;
1155 ConstexprCondition = Cond.getKnownValue();
1157 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1158 // there is no compound stmt. C90 does not have this clause. We only do this
1159 // if the body isn't a compound statement to avoid push/pop in common cases.
1162 // The substatement in a selection-statement (each substatement, in the else
1163 // form of the if statement) implicitly defines a local scope.
1165 // For C++ we create a scope for the condition and a new scope for
1166 // substatements because:
1167 // -When the 'then' scope exits, we want the condition declaration to still be
1168 // active for the 'else' scope too.
1169 // -Sema will detect name clashes by considering declarations of a
1170 // 'ControlScope' as part of its direct subscope.
1171 // -If we wanted the condition and substatement to be in the same scope, we
1172 // would have to notify ParseStatement not to create a new scope. It's
1173 // simpler to let it create a new scope.
1175 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1177 // Read the 'then' stmt.
1178 SourceLocation ThenStmtLoc = Tok.getLocation();
1180 SourceLocation InnerStatementTrailingElseLoc;
1181 StmtResult ThenStmt;
1183 EnterExpressionEvaluationContext PotentiallyDiscarded(
1184 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1185 Sema::ExpressionEvaluationContextRecord::EK_Other,
1186 /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1187 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1190 // Pop the 'if' scope if needed.
1193 // If it has an else, parse it.
1194 SourceLocation ElseLoc;
1195 SourceLocation ElseStmtLoc;
1196 StmtResult ElseStmt;
1198 if (Tok.is(tok::kw_else)) {
1199 if (TrailingElseLoc)
1200 *TrailingElseLoc = Tok.getLocation();
1202 ElseLoc = ConsumeToken();
1203 ElseStmtLoc = Tok.getLocation();
1205 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1206 // there is no compound stmt. C90 does not have this clause. We only do
1207 // this if the body isn't a compound statement to avoid push/pop in common
1211 // The substatement in a selection-statement (each substatement, in the else
1212 // form of the if statement) implicitly defines a local scope.
1214 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1215 Tok.is(tok::l_brace));
1217 EnterExpressionEvaluationContext PotentiallyDiscarded(
1218 Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1219 Sema::ExpressionEvaluationContextRecord::EK_Other,
1220 /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1221 ElseStmt = ParseStatement();
1223 // Pop the 'else' scope if needed.
1225 } else if (Tok.is(tok::code_completion)) {
1226 Actions.CodeCompleteAfterIf(getCurScope());
1229 } else if (InnerStatementTrailingElseLoc.isValid()) {
1230 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1235 // If the then or else stmt is invalid and the other is valid (and present),
1236 // make turn the invalid one into a null stmt to avoid dropping the other
1237 // part. If both are invalid, return error.
1238 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1239 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1240 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1241 // Both invalid, or one is invalid and other is non-present: return error.
1245 // Now if either are invalid, replace with a ';'.
1246 if (ThenStmt.isInvalid())
1247 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1248 if (ElseStmt.isInvalid())
1249 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1251 return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1252 ThenStmt.get(), ElseLoc, ElseStmt.get());
1255 /// ParseSwitchStatement
1256 /// switch-statement:
1257 /// 'switch' '(' expression ')' statement
1258 /// [C++] 'switch' '(' condition ')' statement
1259 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1260 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1261 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1263 if (Tok.isNot(tok::l_paren)) {
1264 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1265 SkipUntil(tok::semi);
1269 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1271 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1272 // not the case for C90. Start the switch scope.
1275 // A name introduced by a declaration in a condition is in scope from its
1276 // point of declaration until the end of the substatements controlled by the
1279 // Names declared in the for-init-statement, and in the condition of if,
1280 // while, for, and switch statements are local to the if, while, for, or
1281 // switch statement (including the controlled statement).
1283 unsigned ScopeFlags = Scope::SwitchScope;
1285 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1286 ParseScope SwitchScope(this, ScopeFlags);
1288 // Parse the condition.
1289 StmtResult InitStmt;
1290 Sema::ConditionResult Cond;
1291 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1292 Sema::ConditionKind::Switch))
1296 Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1298 if (Switch.isInvalid()) {
1299 // Skip the switch body.
1300 // FIXME: This is not optimal recovery, but parsing the body is more
1301 // dangerous due to the presence of case and default statements, which
1302 // will have no place to connect back with the switch.
1303 if (Tok.is(tok::l_brace)) {
1305 SkipUntil(tok::r_brace);
1307 SkipUntil(tok::semi);
1311 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1312 // there is no compound stmt. C90 does not have this clause. We only do this
1313 // if the body isn't a compound statement to avoid push/pop in common cases.
1316 // The substatement in a selection-statement (each substatement, in the else
1317 // form of the if statement) implicitly defines a local scope.
1319 // See comments in ParseIfStatement for why we create a scope for the
1320 // condition and a new scope for substatement in C++.
1322 getCurScope()->AddFlags(Scope::BreakScope);
1323 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1325 // We have incremented the mangling number for the SwitchScope and the
1326 // InnerScope, which is one too many.
1328 getCurScope()->decrementMSManglingNumber();
1330 // Read the body statement.
1331 StmtResult Body(ParseStatement(TrailingElseLoc));
1337 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1340 /// ParseWhileStatement
1341 /// while-statement: [C99 6.8.5.1]
1342 /// 'while' '(' expression ')' statement
1343 /// [C++] 'while' '(' condition ')' statement
1344 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1345 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1346 SourceLocation WhileLoc = Tok.getLocation();
1347 ConsumeToken(); // eat the 'while'.
1349 if (Tok.isNot(tok::l_paren)) {
1350 Diag(Tok, diag::err_expected_lparen_after) << "while";
1351 SkipUntil(tok::semi);
1355 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1357 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1358 // the case for C90. Start the loop scope.
1361 // A name introduced by a declaration in a condition is in scope from its
1362 // point of declaration until the end of the substatements controlled by the
1365 // Names declared in the for-init-statement, and in the condition of if,
1366 // while, for, and switch statements are local to the if, while, for, or
1367 // switch statement (including the controlled statement).
1369 unsigned ScopeFlags;
1371 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1372 Scope::DeclScope | Scope::ControlScope;
1374 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1375 ParseScope WhileScope(this, ScopeFlags);
1377 // Parse the condition.
1378 Sema::ConditionResult Cond;
1379 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1380 Sema::ConditionKind::Boolean))
1383 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1384 // there is no compound stmt. C90 does not have this clause. We only do this
1385 // if the body isn't a compound statement to avoid push/pop in common cases.
1388 // The substatement in an iteration-statement implicitly defines a local scope
1389 // which is entered and exited each time through the loop.
1391 // See comments in ParseIfStatement for why we create a scope for the
1392 // condition and a new scope for substatement in C++.
1394 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1396 // Read the body statement.
1397 StmtResult Body(ParseStatement(TrailingElseLoc));
1399 // Pop the body scope if needed.
1403 if (Cond.isInvalid() || Body.isInvalid())
1406 return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1409 /// ParseDoStatement
1410 /// do-statement: [C99 6.8.5.2]
1411 /// 'do' statement 'while' '(' expression ')' ';'
1412 /// Note: this lets the caller parse the end ';'.
1413 StmtResult Parser::ParseDoStatement() {
1414 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1415 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1417 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1418 // the case for C90. Start the loop scope.
1419 unsigned ScopeFlags;
1420 if (getLangOpts().C99)
1421 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1423 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1425 ParseScope DoScope(this, ScopeFlags);
1427 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1428 // there is no compound stmt. C90 does not have this clause. We only do this
1429 // if the body isn't a compound statement to avoid push/pop in common cases.
1432 // The substatement in an iteration-statement implicitly defines a local scope
1433 // which is entered and exited each time through the loop.
1435 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1436 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1438 // Read the body statement.
1439 StmtResult Body(ParseStatement());
1441 // Pop the body scope if needed.
1444 if (Tok.isNot(tok::kw_while)) {
1445 if (!Body.isInvalid()) {
1446 Diag(Tok, diag::err_expected_while);
1447 Diag(DoLoc, diag::note_matching) << "'do'";
1448 SkipUntil(tok::semi, StopBeforeMatch);
1452 SourceLocation WhileLoc = ConsumeToken();
1454 if (Tok.isNot(tok::l_paren)) {
1455 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1456 SkipUntil(tok::semi, StopBeforeMatch);
1460 // Parse the parenthesized expression.
1461 BalancedDelimiterTracker T(*this, tok::l_paren);
1464 // A do-while expression is not a condition, so can't have attributes.
1465 DiagnoseAndSkipCXX11Attributes();
1467 ExprResult Cond = ParseExpression();
1468 // Correct the typos in condition before closing the scope.
1469 if (Cond.isUsable())
1470 Cond = Actions.CorrectDelayedTyposInExpr(Cond);
1474 if (Cond.isInvalid() || Body.isInvalid())
1477 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1478 Cond.get(), T.getCloseLocation());
1481 bool Parser::isForRangeIdentifier() {
1482 assert(Tok.is(tok::identifier));
1484 const Token &Next = NextToken();
1485 if (Next.is(tok::colon))
1488 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1489 TentativeParsingAction PA(*this);
1491 SkipCXX11Attributes();
1492 bool Result = Tok.is(tok::colon);
1500 /// ParseForStatement
1501 /// for-statement: [C99 6.8.5.3]
1502 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1503 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1504 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1507 /// 'co_await'[opt] [Coroutines]
1508 /// '(' for-range-declaration ':' for-range-initializer ')'
1510 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1511 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1513 /// [C++] for-init-statement:
1514 /// [C++] expression-statement
1515 /// [C++] simple-declaration
1517 /// [C++0x] for-range-declaration:
1518 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1519 /// [C++0x] for-range-initializer:
1520 /// [C++0x] expression
1521 /// [C++0x] braced-init-list [TODO]
1522 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1523 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1524 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1526 SourceLocation CoawaitLoc;
1527 if (Tok.is(tok::kw_co_await))
1528 CoawaitLoc = ConsumeToken();
1530 if (Tok.isNot(tok::l_paren)) {
1531 Diag(Tok, diag::err_expected_lparen_after) << "for";
1532 SkipUntil(tok::semi);
1536 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1537 getLangOpts().ObjC1;
1539 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1540 // the case for C90. Start the loop scope.
1543 // A name introduced by a declaration in a condition is in scope from its
1544 // point of declaration until the end of the substatements controlled by the
1547 // Names declared in the for-init-statement, and in the condition of if,
1548 // while, for, and switch statements are local to the if, while, for, or
1549 // switch statement (including the controlled statement).
1551 // Names declared in the for-init-statement are in the same declarative-region
1552 // as those declared in the condition.
1554 unsigned ScopeFlags = 0;
1556 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1558 ParseScope ForScope(this, ScopeFlags);
1560 BalancedDelimiterTracker T(*this, tok::l_paren);
1565 bool ForEach = false, ForRange = false;
1566 StmtResult FirstPart;
1567 Sema::ConditionResult SecondPart;
1568 ExprResult Collection;
1569 ForRangeInit ForRangeInit;
1570 FullExprArg ThirdPart(Actions);
1572 if (Tok.is(tok::code_completion)) {
1573 Actions.CodeCompleteOrdinaryName(getCurScope(),
1574 C99orCXXorObjC? Sema::PCC_ForInit
1575 : Sema::PCC_Expression);
1580 ParsedAttributesWithRange attrs(AttrFactory);
1581 MaybeParseCXX11Attributes(attrs);
1583 // Parse the first part of the for specifier.
1584 if (Tok.is(tok::semi)) { // for (;
1585 ProhibitAttributes(attrs);
1586 // no first part, eat the ';'.
1588 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1589 isForRangeIdentifier()) {
1590 ProhibitAttributes(attrs);
1591 IdentifierInfo *Name = Tok.getIdentifierInfo();
1592 SourceLocation Loc = ConsumeToken();
1593 MaybeParseCXX11Attributes(attrs);
1595 ForRangeInit.ColonLoc = ConsumeToken();
1596 if (Tok.is(tok::l_brace))
1597 ForRangeInit.RangeExpr = ParseBraceInitializer();
1599 ForRangeInit.RangeExpr = ParseExpression();
1601 Diag(Loc, diag::err_for_range_identifier)
1602 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
1603 ? FixItHint::CreateInsertion(Loc, "auto &&")
1606 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1607 attrs, attrs.Range.getEnd());
1609 } else if (isForInitDeclaration()) { // for (int X = 4;
1610 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1612 // Parse declaration, which eats the ';'.
1613 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
1614 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1615 Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
1618 // In C++0x, "for (T NS:a" might not be a typo for ::
1619 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1620 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1622 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1623 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1624 DeclaratorContext::ForContext, DeclEnd, attrs, false,
1625 MightBeForRangeStmt ? &ForRangeInit : nullptr);
1626 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1627 if (ForRangeInit.ParsedForRangeDecl()) {
1628 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1629 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1632 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1634 } else if ((ForEach = isTokIdentifier_in())) {
1635 Actions.ActOnForEachDeclStmt(DG);
1636 // ObjC: for (id x in expr)
1637 ConsumeToken(); // consume 'in'
1639 if (Tok.is(tok::code_completion)) {
1640 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1644 Collection = ParseExpression();
1646 Diag(Tok, diag::err_expected_semi_for);
1649 ProhibitAttributes(attrs);
1650 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1652 ForEach = isTokIdentifier_in();
1654 // Turn the expression into a stmt.
1655 if (!Value.isInvalid()) {
1657 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1659 FirstPart = Actions.ActOnExprStmt(Value);
1662 if (Tok.is(tok::semi)) {
1664 } else if (ForEach) {
1665 ConsumeToken(); // consume 'in'
1667 if (Tok.is(tok::code_completion)) {
1668 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1672 Collection = ParseExpression();
1673 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1674 // User tried to write the reasonable, but ill-formed, for-range-statement
1675 // for (expr : expr) { ... }
1676 Diag(Tok, diag::err_for_range_expected_decl)
1677 << FirstPart.get()->getSourceRange();
1678 SkipUntil(tok::r_paren, StopBeforeMatch);
1679 SecondPart = Sema::ConditionError();
1681 if (!Value.isInvalid()) {
1682 Diag(Tok, diag::err_expected_semi_for);
1684 // Skip until semicolon or rparen, don't consume it.
1685 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1686 if (Tok.is(tok::semi))
1692 // Parse the second part of the for specifier.
1693 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1694 if (!ForEach && !ForRange && !SecondPart.isInvalid()) {
1695 // Parse the second part of the for specifier.
1696 if (Tok.is(tok::semi)) { // for (...;;
1698 } else if (Tok.is(tok::r_paren)) {
1699 // missing both semicolons.
1701 if (getLangOpts().CPlusPlus)
1703 ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean);
1705 ExprResult SecondExpr = ParseExpression();
1706 if (SecondExpr.isInvalid())
1707 SecondPart = Sema::ConditionError();
1710 Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1711 Sema::ConditionKind::Boolean);
1715 if (Tok.isNot(tok::semi)) {
1716 if (!SecondPart.isInvalid())
1717 Diag(Tok, diag::err_expected_semi_for);
1719 // Skip until semicolon or rparen, don't consume it.
1720 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1723 if (Tok.is(tok::semi)) {
1727 // Parse the third part of the for specifier.
1728 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1729 ExprResult Third = ParseExpression();
1730 // FIXME: The C++11 standard doesn't actually say that this is a
1731 // discarded-value expression, but it clearly should be.
1732 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
1738 // C++ Coroutines [stmt.iter]:
1739 // 'co_await' can only be used for a range-based for statement.
1740 if (CoawaitLoc.isValid() && !ForRange) {
1741 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
1742 CoawaitLoc = SourceLocation();
1745 // We need to perform most of the semantic analysis for a C++0x for-range
1746 // statememt before parsing the body, in order to be able to deduce the type
1747 // of an auto-typed loop variable.
1748 StmtResult ForRangeStmt;
1749 StmtResult ForEachStmt;
1752 ExprResult CorrectedRange =
1753 Actions.CorrectDelayedTyposInExpr(ForRangeInit.RangeExpr.get());
1754 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
1755 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
1756 ForRangeInit.ColonLoc, CorrectedRange.get(),
1757 T.getCloseLocation(), Sema::BFRK_Build);
1759 // Similarly, we need to do the semantic analysis for a for-range
1760 // statement immediately in order to close over temporaries correctly.
1761 } else if (ForEach) {
1762 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1765 T.getCloseLocation());
1767 // In OpenMP loop region loop control variable must be captured and be
1768 // private. Perform analysis of first part (if any).
1769 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
1770 Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
1774 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
1775 // there is no compound stmt. C90 does not have this clause. We only do this
1776 // if the body isn't a compound statement to avoid push/pop in common cases.
1779 // The substatement in an iteration-statement implicitly defines a local scope
1780 // which is entered and exited each time through the loop.
1782 // See comments in ParseIfStatement for why we create a scope for
1783 // for-init-statement/condition and a new scope for substatement in C++.
1785 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
1786 Tok.is(tok::l_brace));
1788 // The body of the for loop has the same local mangling number as the
1789 // for-init-statement.
1790 // It will only be incremented if the body contains other things that would
1791 // normally increment the mangling number (like a compound statement).
1793 getCurScope()->decrementMSManglingNumber();
1795 // Read the body statement.
1796 StmtResult Body(ParseStatement(TrailingElseLoc));
1798 // Pop the body scope if needed.
1801 // Leave the for-scope.
1804 if (Body.isInvalid())
1808 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
1812 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
1814 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
1815 SecondPart, ThirdPart, T.getCloseLocation(),
1819 /// ParseGotoStatement
1821 /// 'goto' identifier ';'
1822 /// [GNU] 'goto' '*' expression ';'
1824 /// Note: this lets the caller parse the end ';'.
1826 StmtResult Parser::ParseGotoStatement() {
1827 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1828 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1831 if (Tok.is(tok::identifier)) {
1832 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1834 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1836 } else if (Tok.is(tok::star)) {
1837 // GNU indirect goto extension.
1838 Diag(Tok, diag::ext_gnu_indirect_goto);
1839 SourceLocation StarLoc = ConsumeToken();
1840 ExprResult R(ParseExpression());
1841 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1842 SkipUntil(tok::semi, StopBeforeMatch);
1845 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
1847 Diag(Tok, diag::err_expected) << tok::identifier;
1854 /// ParseContinueStatement
1858 /// Note: this lets the caller parse the end ';'.
1860 StmtResult Parser::ParseContinueStatement() {
1861 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1862 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1865 /// ParseBreakStatement
1869 /// Note: this lets the caller parse the end ';'.
1871 StmtResult Parser::ParseBreakStatement() {
1872 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1873 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1876 /// ParseReturnStatement
1878 /// 'return' expression[opt] ';'
1879 /// 'return' braced-init-list ';'
1880 /// 'co_return' expression[opt] ';'
1881 /// 'co_return' braced-init-list ';'
1882 StmtResult Parser::ParseReturnStatement() {
1883 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
1884 "Not a return stmt!");
1885 bool IsCoreturn = Tok.is(tok::kw_co_return);
1886 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1889 if (Tok.isNot(tok::semi)) {
1890 // FIXME: Code completion for co_return.
1891 if (Tok.is(tok::code_completion) && !IsCoreturn) {
1892 Actions.CodeCompleteReturn(getCurScope());
1897 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1898 R = ParseInitializer();
1900 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1901 diag::warn_cxx98_compat_generalized_initializer_lists :
1902 diag::ext_generalized_initializer_lists)
1903 << R.get()->getSourceRange();
1905 R = ParseExpression();
1906 if (R.isInvalid()) {
1907 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1912 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
1913 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
1916 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
1917 AllowedConstructsKind Allowed,
1918 SourceLocation *TrailingElseLoc,
1919 ParsedAttributesWithRange &Attrs) {
1920 // Create temporary attribute list.
1921 ParsedAttributesWithRange TempAttrs(AttrFactory);
1923 // Get loop hints and consume annotated token.
1924 while (Tok.is(tok::annot_pragma_loop_hint)) {
1926 if (!HandlePragmaLoopHint(Hint))
1929 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
1930 ArgsUnion(Hint.ValueExpr)};
1931 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
1932 Hint.PragmaNameLoc->Loc, ArgHints, 4,
1933 ParsedAttr::AS_Pragma);
1936 // Get the next statement.
1937 MaybeParseCXX11Attributes(Attrs);
1939 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
1940 Stmts, Allowed, TrailingElseLoc, Attrs);
1942 Attrs.takeAllFrom(TempAttrs);
1946 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1947 assert(Tok.is(tok::l_brace));
1948 SourceLocation LBraceLoc = Tok.getLocation();
1950 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
1951 "parsing function body");
1953 // Save and reset current vtordisp stack if we have entered a C++ method body.
1955 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1956 Sema::PragmaStackSentinelRAII
1957 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1959 // Do not enter a scope for the brace, as the arguments are in the same scope
1960 // (the function body) as the body itself. Instead, just read the statement
1961 // list and put it into a CompoundStmt for safe keeping.
1962 StmtResult FnBody(ParseCompoundStatementBody());
1964 // If the function body could not be parsed, make a bogus compoundstmt.
1965 if (FnBody.isInvalid()) {
1966 Sema::CompoundScopeRAII CompoundScope(Actions);
1967 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
1971 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
1974 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1976 /// function-try-block:
1977 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1979 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1980 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1981 SourceLocation TryLoc = ConsumeToken();
1983 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
1984 "parsing function try block");
1986 // Constructor initializer list?
1987 if (Tok.is(tok::colon))
1988 ParseConstructorInitializer(Decl);
1990 Actions.ActOnDefaultCtorInitializers(Decl);
1992 // Save and reset current vtordisp stack if we have entered a C++ method body.
1994 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
1995 Sema::PragmaStackSentinelRAII
1996 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
1998 SourceLocation LBraceLoc = Tok.getLocation();
1999 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2000 // If we failed to parse the try-catch, we just give the function an empty
2001 // compound statement as the body.
2002 if (FnBody.isInvalid()) {
2003 Sema::CompoundScopeRAII CompoundScope(Actions);
2004 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2008 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2011 bool Parser::trySkippingFunctionBody() {
2012 assert(SkipFunctionBodies &&
2013 "Should only be called when SkipFunctionBodies is enabled");
2014 if (!PP.isCodeCompletionEnabled()) {
2019 // We're in code-completion mode. Skip parsing for all function bodies unless
2020 // the body contains the code-completion point.
2021 TentativeParsingAction PA(*this);
2022 bool IsTryCatch = Tok.is(tok::kw_try);
2024 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2025 if (llvm::any_of(Toks, [](const Token &Tok) {
2026 return Tok.is(tok::code_completion);
2031 if (ErrorInPrologue) {
2033 SkipMalformedDecl();
2036 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2040 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2041 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2042 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2051 /// ParseCXXTryBlock - Parse a C++ try-block.
2054 /// 'try' compound-statement handler-seq
2056 StmtResult Parser::ParseCXXTryBlock() {
2057 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2059 SourceLocation TryLoc = ConsumeToken();
2060 return ParseCXXTryBlockCommon(TryLoc);
2063 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2064 /// function-try-block.
2067 /// 'try' compound-statement handler-seq
2069 /// function-try-block:
2070 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2073 /// handler handler-seq[opt]
2075 /// [Borland] try-block:
2076 /// 'try' compound-statement seh-except-block
2077 /// 'try' compound-statement seh-finally-block
2079 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2080 if (Tok.isNot(tok::l_brace))
2081 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2083 StmtResult TryBlock(ParseCompoundStatement(
2084 /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2085 Scope::CompoundStmtScope |
2086 (FnTry ? Scope::FnTryCatchScope : 0)));
2087 if (TryBlock.isInvalid())
2090 // Borland allows SEH-handlers with 'try'
2092 if ((Tok.is(tok::identifier) &&
2093 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2094 Tok.is(tok::kw___finally)) {
2095 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2097 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2098 SourceLocation Loc = ConsumeToken();
2099 Handler = ParseSEHExceptBlock(Loc);
2102 SourceLocation Loc = ConsumeToken();
2103 Handler = ParseSEHFinallyBlock(Loc);
2105 if(Handler.isInvalid())
2108 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2114 StmtVector Handlers;
2116 // C++11 attributes can't appear here, despite this context seeming
2118 DiagnoseAndSkipCXX11Attributes();
2120 if (Tok.isNot(tok::kw_catch))
2121 return StmtError(Diag(Tok, diag::err_expected_catch));
2122 while (Tok.is(tok::kw_catch)) {
2123 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2124 if (!Handler.isInvalid())
2125 Handlers.push_back(Handler.get());
2127 // Don't bother creating the full statement if we don't have any usable
2129 if (Handlers.empty())
2132 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2136 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2139 /// 'catch' '(' exception-declaration ')' compound-statement
2141 /// exception-declaration:
2142 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2143 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2146 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2147 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2149 SourceLocation CatchLoc = ConsumeToken();
2151 BalancedDelimiterTracker T(*this, tok::l_paren);
2152 if (T.expectAndConsume())
2156 // The name in a catch exception-declaration is local to the handler and
2157 // shall not be redeclared in the outermost block of the handler.
2158 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2159 (FnCatch ? Scope::FnTryCatchScope : 0));
2161 // exception-declaration is equivalent to '...' or a parameter-declaration
2162 // without default arguments.
2163 Decl *ExceptionDecl = nullptr;
2164 if (Tok.isNot(tok::ellipsis)) {
2165 ParsedAttributesWithRange Attributes(AttrFactory);
2166 MaybeParseCXX11Attributes(Attributes);
2168 DeclSpec DS(AttrFactory);
2169 DS.takeAttributesFrom(Attributes);
2171 if (ParseCXXTypeSpecifierSeq(DS))
2174 Declarator ExDecl(DS, DeclaratorContext::CXXCatchContext);
2175 ParseDeclarator(ExDecl);
2176 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2181 if (T.getCloseLocation().isInvalid())
2184 if (Tok.isNot(tok::l_brace))
2185 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2187 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2188 StmtResult Block(ParseCompoundStatement());
2189 if (Block.isInvalid())
2192 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2195 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2196 IfExistsCondition Result;
2197 if (ParseMicrosoftIfExistsCondition(Result))
2200 // Handle dependent statements by parsing the braces as a compound statement.
2201 // This is not the same behavior as Visual C++, which don't treat this as a
2202 // compound statement, but for Clang's type checking we can't have anything
2203 // inside these braces escaping to the surrounding code.
2204 if (Result.Behavior == IEB_Dependent) {
2205 if (!Tok.is(tok::l_brace)) {
2206 Diag(Tok, diag::err_expected) << tok::l_brace;
2210 StmtResult Compound = ParseCompoundStatement();
2211 if (Compound.isInvalid())
2214 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2219 if (DepResult.isUsable())
2220 Stmts.push_back(DepResult.get());
2224 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2225 if (Braces.consumeOpen()) {
2226 Diag(Tok, diag::err_expected) << tok::l_brace;
2230 switch (Result.Behavior) {
2232 // Parse the statements below.
2236 llvm_unreachable("Dependent case handled above");
2243 // Condition is true, parse the statements.
2244 while (Tok.isNot(tok::r_brace)) {
2245 StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2247 Stmts.push_back(R.get());
2249 Braces.consumeClose();
2252 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2253 MaybeParseGNUAttributes(Attrs);
2258 if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
2261 if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2262 Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);