1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Statement and Block portions of the Parser
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/PrettyDeclStackTrace.h"
15 #include "clang/Basic/Attributes.h"
16 #include "clang/Basic/PrettyStackTrace.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/TokenKinds.h"
19 #include "clang/Parse/LoopHint.h"
20 #include "clang/Parse/Parser.h"
21 #include "clang/Parse/RAIIObjectsForParser.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/EnterExpressionEvaluationContext.h"
24 #include "clang/Sema/Scope.h"
25 #include "clang/Sema/TypoCorrection.h"
26 #include "llvm/ADT/STLExtras.h"
29 using namespace clang
;
31 //===----------------------------------------------------------------------===//
32 // C99 6.8: Statements and Blocks.
33 //===----------------------------------------------------------------------===//
35 /// Parse a standalone statement (for instance, as the body of an 'if',
36 /// 'while', or 'for').
37 StmtResult
Parser::ParseStatement(SourceLocation
*TrailingElseLoc
,
38 ParsedStmtContext StmtCtx
) {
41 // We may get back a null statement if we found a #pragma. Keep going until
42 // we get an actual statement.
45 Res
= ParseStatementOrDeclaration(Stmts
, StmtCtx
, TrailingElseLoc
);
46 } while (!Res
.isInvalid() && !Res
.get());
51 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
52 /// StatementOrDeclaration:
58 /// compound-statement
59 /// expression-statement
60 /// selection-statement
61 /// iteration-statement
63 /// [C++] declaration-statement
65 /// [MS] seh-try-block
66 /// [OBC] objc-throw-statement
67 /// [OBC] objc-try-catch-statement
68 /// [OBC] objc-synchronized-statement
69 /// [GNU] asm-statement
70 /// [OMP] openmp-construct [TODO]
72 /// labeled-statement:
73 /// identifier ':' statement
74 /// 'case' constant-expression ':' statement
75 /// 'default' ':' statement
77 /// selection-statement:
81 /// iteration-statement:
86 /// expression-statement:
87 /// expression[opt] ';'
90 /// 'goto' identifier ';'
93 /// 'return' expression[opt] ';'
94 /// [GNU] 'goto' '*' expression ';'
96 /// [OBC] objc-throw-statement:
97 /// [OBC] '@' 'throw' expression ';'
98 /// [OBC] '@' 'throw' ';'
101 Parser::ParseStatementOrDeclaration(StmtVector
&Stmts
,
102 ParsedStmtContext StmtCtx
,
103 SourceLocation
*TrailingElseLoc
) {
105 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
107 // Because we're parsing either a statement or a declaration, the order of
108 // attribute parsing is important. [[]] attributes at the start of a
109 // statement are different from [[]] attributes that follow an __attribute__
110 // at the start of the statement. Thus, we're not using MaybeParseAttributes
111 // here because we don't want to allow arbitrary orderings.
112 ParsedAttributes
CXX11Attrs(AttrFactory
);
113 MaybeParseCXX11Attributes(CXX11Attrs
, /*MightBeObjCMessageSend*/ true);
114 ParsedAttributes
GNUAttrs(AttrFactory
);
115 if (getLangOpts().OpenCL
)
116 MaybeParseGNUAttributes(GNUAttrs
);
118 StmtResult Res
= ParseStatementOrDeclarationAfterAttributes(
119 Stmts
, StmtCtx
, TrailingElseLoc
, CXX11Attrs
, GNUAttrs
);
120 MaybeDestroyTemplateIds();
122 // Attributes that are left should all go on the statement, so concatenate the
124 ParsedAttributes
Attrs(AttrFactory
);
125 takeAndConcatenateAttrs(CXX11Attrs
, GNUAttrs
, Attrs
);
127 assert((Attrs
.empty() || Res
.isInvalid() || Res
.isUsable()) &&
128 "attributes on empty statement");
130 if (Attrs
.empty() || Res
.isInvalid())
133 return Actions
.ActOnAttributedStmt(Attrs
, Res
.get());
137 class StatementFilterCCC final
: public CorrectionCandidateCallback
{
139 StatementFilterCCC(Token nextTok
) : NextToken(nextTok
) {
140 WantTypeSpecifiers
= nextTok
.isOneOf(tok::l_paren
, tok::less
, tok::l_square
,
141 tok::identifier
, tok::star
, tok::amp
);
142 WantExpressionKeywords
=
143 nextTok
.isOneOf(tok::l_paren
, tok::identifier
, tok::arrow
, tok::period
);
144 WantRemainingKeywords
=
145 nextTok
.isOneOf(tok::l_paren
, tok::semi
, tok::identifier
, tok::l_brace
);
146 WantCXXNamedCasts
= false;
149 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
150 if (FieldDecl
*FD
= candidate
.getCorrectionDeclAs
<FieldDecl
>())
151 return !candidate
.getCorrectionSpecifier() || isa
<ObjCIvarDecl
>(FD
);
152 if (NextToken
.is(tok::equal
))
153 return candidate
.getCorrectionDeclAs
<VarDecl
>();
154 if (NextToken
.is(tok::period
) &&
155 candidate
.getCorrectionDeclAs
<NamespaceDecl
>())
157 return CorrectionCandidateCallback::ValidateCandidate(candidate
);
160 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
161 return std::make_unique
<StatementFilterCCC
>(*this);
169 StmtResult
Parser::ParseStatementOrDeclarationAfterAttributes(
170 StmtVector
&Stmts
, ParsedStmtContext StmtCtx
,
171 SourceLocation
*TrailingElseLoc
, ParsedAttributes
&CXX11Attrs
,
172 ParsedAttributes
&GNUAttrs
) {
173 const char *SemiError
= nullptr;
175 SourceLocation GNUAttributeLoc
;
177 // Cases in this switch statement should fall through if the parser expects
178 // the token to end in a semicolon (in which case SemiError should be set),
179 // or they directly 'return;' if not.
181 tok::TokenKind Kind
= Tok
.getKind();
182 SourceLocation AtLoc
;
184 case tok::at
: // May be a @try or @throw statement
186 AtLoc
= ConsumeToken(); // consume @
187 return ParseObjCAtStatement(AtLoc
, StmtCtx
);
190 case tok::code_completion
:
192 Actions
.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement
);
195 case tok::identifier
:
197 Token Next
= NextToken();
198 if (Next
.is(tok::colon
)) { // C99 6.8.1: labeled-statement
199 // Both C++11 and GNU attributes preceding the label appertain to the
200 // label, so put them in a single list to pass on to
201 // ParseLabeledStatement().
202 ParsedAttributes
Attrs(AttrFactory
);
203 takeAndConcatenateAttrs(CXX11Attrs
, GNUAttrs
, Attrs
);
205 // identifier ':' statement
206 return ParseLabeledStatement(Attrs
, StmtCtx
);
209 // Look up the identifier, and typo-correct it to a keyword if it's not
211 if (Next
.isNot(tok::coloncolon
)) {
212 // Try to limit which sets of keywords should be included in typo
213 // correction based on what the next token is.
214 StatementFilterCCC
CCC(Next
);
215 if (TryAnnotateName(&CCC
) == ANK_Error
) {
216 // Handle errors here by skipping up to the next semicolon or '}', and
217 // eat the semicolon if that's what stopped us.
218 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
219 if (Tok
.is(tok::semi
))
224 // If the identifier was typo-corrected, try again.
225 if (Tok
.isNot(tok::identifier
))
234 bool HaveAttrs
= !CXX11Attrs
.empty() || !GNUAttrs
.empty();
235 auto IsStmtAttr
= [](ParsedAttr
&Attr
) { return Attr
.isStmtAttr(); };
236 bool AllAttrsAreStmtAttrs
= llvm::all_of(CXX11Attrs
, IsStmtAttr
) &&
237 llvm::all_of(GNUAttrs
, IsStmtAttr
);
238 if ((getLangOpts().CPlusPlus
|| getLangOpts().MicrosoftExt
||
239 (StmtCtx
& ParsedStmtContext::AllowDeclarationsInC
) !=
240 ParsedStmtContext()) &&
241 ((GNUAttributeLoc
.isValid() && !(HaveAttrs
&& AllAttrsAreStmtAttrs
)) ||
242 isDeclarationStatement())) {
243 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
245 if (GNUAttributeLoc
.isValid()) {
246 DeclStart
= GNUAttributeLoc
;
247 Decl
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
, CXX11Attrs
,
248 GNUAttrs
, &GNUAttributeLoc
);
250 Decl
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
, CXX11Attrs
,
253 if (CXX11Attrs
.Range
.getBegin().isValid()) {
254 // The caller must guarantee that the CXX11Attrs appear before the
255 // GNUAttrs, and we rely on that here.
256 assert(GNUAttrs
.Range
.getBegin().isInvalid() ||
257 GNUAttrs
.Range
.getBegin() > CXX11Attrs
.Range
.getBegin());
258 DeclStart
= CXX11Attrs
.Range
.getBegin();
259 } else if (GNUAttrs
.Range
.getBegin().isValid())
260 DeclStart
= GNUAttrs
.Range
.getBegin();
261 return Actions
.ActOnDeclStmt(Decl
, DeclStart
, DeclEnd
);
264 if (Tok
.is(tok::r_brace
)) {
265 Diag(Tok
, diag::err_expected_statement
);
269 switch (Tok
.getKind()) {
270 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
271 #include "clang/Basic/TransformTypeTraits.def"
272 if (NextToken().is(tok::less
)) {
273 Tok
.setKind(tok::identifier
);
274 Diag(Tok
, diag::ext_keyword_as_ident
)
275 << Tok
.getIdentifierInfo()->getName() << 0;
276 goto ParseIdentifier
;
280 return ParseExprStatement(StmtCtx
);
284 case tok::kw___attribute
: {
285 GNUAttributeLoc
= Tok
.getLocation();
286 ParseGNUAttributes(GNUAttrs
);
290 case tok::kw_case
: // C99 6.8.1: labeled-statement
291 return ParseCaseStatement(StmtCtx
);
292 case tok::kw_default
: // C99 6.8.1: labeled-statement
293 return ParseDefaultStatement(StmtCtx
);
295 case tok::l_brace
: // C99 6.8.2: compound-statement
296 return ParseCompoundStatement();
297 case tok::semi
: { // C99 6.8.3p3: expression[opt] ';'
298 bool HasLeadingEmptyMacro
= Tok
.hasLeadingEmptyMacro();
299 return Actions
.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro
);
302 case tok::kw_if
: // C99 6.8.4.1: if-statement
303 return ParseIfStatement(TrailingElseLoc
);
304 case tok::kw_switch
: // C99 6.8.4.2: switch-statement
305 return ParseSwitchStatement(TrailingElseLoc
);
307 case tok::kw_while
: // C99 6.8.5.1: while-statement
308 return ParseWhileStatement(TrailingElseLoc
);
309 case tok::kw_do
: // C99 6.8.5.2: do-statement
310 Res
= ParseDoStatement();
311 SemiError
= "do/while";
313 case tok::kw_for
: // C99 6.8.5.3: for-statement
314 return ParseForStatement(TrailingElseLoc
);
316 case tok::kw_goto
: // C99 6.8.6.1: goto-statement
317 Res
= ParseGotoStatement();
320 case tok::kw_continue
: // C99 6.8.6.2: continue-statement
321 Res
= ParseContinueStatement();
322 SemiError
= "continue";
324 case tok::kw_break
: // C99 6.8.6.3: break-statement
325 Res
= ParseBreakStatement();
328 case tok::kw_return
: // C99 6.8.6.4: return-statement
329 Res
= ParseReturnStatement();
330 SemiError
= "return";
332 case tok::kw_co_return
: // C++ Coroutines: co_return statement
333 Res
= ParseReturnStatement();
334 SemiError
= "co_return";
338 for (const ParsedAttr
&AL
: CXX11Attrs
)
339 // Could be relaxed if asm-related regular keyword attributes are
341 (AL
.isRegularKeywordAttribute()
342 ? Diag(AL
.getRange().getBegin(), diag::err_keyword_not_allowed
)
343 : Diag(AL
.getRange().getBegin(), diag::warn_attribute_ignored
))
345 // Prevent these from being interpreted as statement attributes later on.
347 ProhibitAttributes(GNUAttrs
);
349 Res
= ParseAsmStatement(msAsm
);
350 if (msAsm
) return Res
;
355 case tok::kw___if_exists
:
356 case tok::kw___if_not_exists
:
357 ProhibitAttributes(CXX11Attrs
);
358 ProhibitAttributes(GNUAttrs
);
359 ParseMicrosoftIfExistsStatement(Stmts
);
360 // An __if_exists block is like a compound statement, but it doesn't create
364 case tok::kw_try
: // C++ 15: try-block
365 return ParseCXXTryBlock();
368 ProhibitAttributes(CXX11Attrs
);
369 ProhibitAttributes(GNUAttrs
);
370 return ParseSEHTryBlock();
372 case tok::kw___leave
:
373 Res
= ParseSEHLeaveStatement();
374 SemiError
= "__leave";
377 case tok::annot_pragma_vis
:
378 ProhibitAttributes(CXX11Attrs
);
379 ProhibitAttributes(GNUAttrs
);
380 HandlePragmaVisibility();
383 case tok::annot_pragma_pack
:
384 ProhibitAttributes(CXX11Attrs
);
385 ProhibitAttributes(GNUAttrs
);
389 case tok::annot_pragma_msstruct
:
390 ProhibitAttributes(CXX11Attrs
);
391 ProhibitAttributes(GNUAttrs
);
392 HandlePragmaMSStruct();
395 case tok::annot_pragma_align
:
396 ProhibitAttributes(CXX11Attrs
);
397 ProhibitAttributes(GNUAttrs
);
401 case tok::annot_pragma_weak
:
402 ProhibitAttributes(CXX11Attrs
);
403 ProhibitAttributes(GNUAttrs
);
407 case tok::annot_pragma_weakalias
:
408 ProhibitAttributes(CXX11Attrs
);
409 ProhibitAttributes(GNUAttrs
);
410 HandlePragmaWeakAlias();
413 case tok::annot_pragma_redefine_extname
:
414 ProhibitAttributes(CXX11Attrs
);
415 ProhibitAttributes(GNUAttrs
);
416 HandlePragmaRedefineExtname();
419 case tok::annot_pragma_fp_contract
:
420 ProhibitAttributes(CXX11Attrs
);
421 ProhibitAttributes(GNUAttrs
);
422 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "fp_contract";
423 ConsumeAnnotationToken();
426 case tok::annot_pragma_fp
:
427 ProhibitAttributes(CXX11Attrs
);
428 ProhibitAttributes(GNUAttrs
);
429 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "clang fp";
430 ConsumeAnnotationToken();
433 case tok::annot_pragma_fenv_access
:
434 case tok::annot_pragma_fenv_access_ms
:
435 ProhibitAttributes(CXX11Attrs
);
436 ProhibitAttributes(GNUAttrs
);
437 Diag(Tok
, diag::err_pragma_file_or_compound_scope
)
438 << (Kind
== tok::annot_pragma_fenv_access
? "STDC FENV_ACCESS"
440 ConsumeAnnotationToken();
443 case tok::annot_pragma_fenv_round
:
444 ProhibitAttributes(CXX11Attrs
);
445 ProhibitAttributes(GNUAttrs
);
446 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "STDC FENV_ROUND";
447 ConsumeAnnotationToken();
450 case tok::annot_pragma_float_control
:
451 ProhibitAttributes(CXX11Attrs
);
452 ProhibitAttributes(GNUAttrs
);
453 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "float_control";
454 ConsumeAnnotationToken();
457 case tok::annot_pragma_opencl_extension
:
458 ProhibitAttributes(CXX11Attrs
);
459 ProhibitAttributes(GNUAttrs
);
460 HandlePragmaOpenCLExtension();
463 case tok::annot_pragma_captured
:
464 ProhibitAttributes(CXX11Attrs
);
465 ProhibitAttributes(GNUAttrs
);
466 return HandlePragmaCaptured();
468 case tok::annot_pragma_openmp
:
469 // Prohibit attributes that are not OpenMP attributes, but only before
470 // processing a #pragma omp clause.
471 ProhibitAttributes(CXX11Attrs
);
472 ProhibitAttributes(GNUAttrs
);
474 case tok::annot_attr_openmp
:
475 // Do not prohibit attributes if they were OpenMP attributes.
476 return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx
);
478 case tok::annot_pragma_ms_pointers_to_members
:
479 ProhibitAttributes(CXX11Attrs
);
480 ProhibitAttributes(GNUAttrs
);
481 HandlePragmaMSPointersToMembers();
484 case tok::annot_pragma_ms_pragma
:
485 ProhibitAttributes(CXX11Attrs
);
486 ProhibitAttributes(GNUAttrs
);
487 HandlePragmaMSPragma();
490 case tok::annot_pragma_ms_vtordisp
:
491 ProhibitAttributes(CXX11Attrs
);
492 ProhibitAttributes(GNUAttrs
);
493 HandlePragmaMSVtorDisp();
496 case tok::annot_pragma_loop_hint
:
497 ProhibitAttributes(CXX11Attrs
);
498 ProhibitAttributes(GNUAttrs
);
499 return ParsePragmaLoopHint(Stmts
, StmtCtx
, TrailingElseLoc
, CXX11Attrs
);
501 case tok::annot_pragma_dump
:
505 case tok::annot_pragma_attribute
:
506 HandlePragmaAttribute();
510 // If we reached this code, the statement must end in a semicolon.
511 if (!TryConsumeToken(tok::semi
) && !Res
.isInvalid()) {
512 // If the result was valid, then we do want to diagnose this. Use
513 // ExpectAndConsume to emit the diagnostic, even though we know it won't
515 ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_stmt
, SemiError
);
516 // Skip until we see a } or ;, but don't eat it.
517 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
523 /// Parse an expression statement.
524 StmtResult
Parser::ParseExprStatement(ParsedStmtContext StmtCtx
) {
525 // If a case keyword is missing, this is where it should be inserted.
526 Token OldToken
= Tok
;
528 ExprStatementTokLoc
= Tok
.getLocation();
530 // expression[opt] ';'
531 ExprResult
Expr(ParseExpression());
532 if (Expr
.isInvalid()) {
533 // If the expression is invalid, skip ahead to the next semicolon or '}'.
534 // Not doing this opens us up to the possibility of infinite loops if
535 // ParseExpression does not consume any tokens.
536 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
537 if (Tok
.is(tok::semi
))
539 return Actions
.ActOnExprStmtError();
542 if (Tok
.is(tok::colon
) && getCurScope()->isSwitchScope() &&
543 Actions
.CheckCaseExpression(Expr
.get())) {
544 // If a constant expression is followed by a colon inside a switch block,
545 // suggest a missing case keyword.
546 Diag(OldToken
, diag::err_expected_case_before_expression
)
547 << FixItHint::CreateInsertion(OldToken
.getLocation(), "case ");
549 // Recover parsing as a case statement.
550 return ParseCaseStatement(StmtCtx
, /*MissingCase=*/true, Expr
);
553 Token
*CurTok
= nullptr;
554 // If the semicolon is missing at the end of REPL input, consider if
555 // we want to do value printing. Note this is only enabled in C++ mode
556 // since part of the implementation requires C++ language features.
557 // Note we shouldn't eat the token since the callback needs it.
558 if (Tok
.is(tok::annot_repl_input_end
) && Actions
.getLangOpts().CPlusPlus
)
561 // Otherwise, eat the semicolon.
562 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr
);
564 StmtResult R
= handleExprStmt(Expr
, StmtCtx
);
565 if (CurTok
&& !R
.isInvalid())
566 CurTok
->setAnnotationValue(R
.get());
571 /// ParseSEHTryBlockCommon
574 /// '__try' compound-statement seh-handler
578 /// seh-finally-block
580 StmtResult
Parser::ParseSEHTryBlock() {
581 assert(Tok
.is(tok::kw___try
) && "Expected '__try'");
582 SourceLocation TryLoc
= ConsumeToken();
584 if (Tok
.isNot(tok::l_brace
))
585 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
587 StmtResult
TryBlock(ParseCompoundStatement(
588 /*isStmtExpr=*/false,
589 Scope::DeclScope
| Scope::CompoundStmtScope
| Scope::SEHTryScope
));
590 if (TryBlock
.isInvalid())
594 if (Tok
.is(tok::identifier
) &&
595 Tok
.getIdentifierInfo() == getSEHExceptKeyword()) {
596 SourceLocation Loc
= ConsumeToken();
597 Handler
= ParseSEHExceptBlock(Loc
);
598 } else if (Tok
.is(tok::kw___finally
)) {
599 SourceLocation Loc
= ConsumeToken();
600 Handler
= ParseSEHFinallyBlock(Loc
);
602 return StmtError(Diag(Tok
, diag::err_seh_expected_handler
));
605 if(Handler
.isInvalid())
608 return Actions
.ActOnSEHTryBlock(false /* IsCXXTry */,
614 /// ParseSEHExceptBlock - Handle __except
616 /// seh-except-block:
617 /// '__except' '(' seh-filter-expression ')' compound-statement
619 StmtResult
Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc
) {
620 PoisonIdentifierRAIIObject
raii(Ident__exception_code
, false),
621 raii2(Ident___exception_code
, false),
622 raii3(Ident_GetExceptionCode
, false);
624 if (ExpectAndConsume(tok::l_paren
))
627 ParseScope
ExpectScope(this, Scope::DeclScope
| Scope::ControlScope
|
628 Scope::SEHExceptScope
);
630 if (getLangOpts().Borland
) {
631 Ident__exception_info
->setIsPoisoned(false);
632 Ident___exception_info
->setIsPoisoned(false);
633 Ident_GetExceptionInfo
->setIsPoisoned(false);
636 ExprResult FilterExpr
;
638 ParseScopeFlags
FilterScope(this, getCurScope()->getFlags() |
639 Scope::SEHFilterScope
);
640 FilterExpr
= Actions
.CorrectDelayedTyposInExpr(ParseExpression());
643 if (getLangOpts().Borland
) {
644 Ident__exception_info
->setIsPoisoned(true);
645 Ident___exception_info
->setIsPoisoned(true);
646 Ident_GetExceptionInfo
->setIsPoisoned(true);
649 if(FilterExpr
.isInvalid())
652 if (ExpectAndConsume(tok::r_paren
))
655 if (Tok
.isNot(tok::l_brace
))
656 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
658 StmtResult
Block(ParseCompoundStatement());
660 if(Block
.isInvalid())
663 return Actions
.ActOnSEHExceptBlock(ExceptLoc
, FilterExpr
.get(), Block
.get());
666 /// ParseSEHFinallyBlock - Handle __finally
668 /// seh-finally-block:
669 /// '__finally' compound-statement
671 StmtResult
Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc
) {
672 PoisonIdentifierRAIIObject
raii(Ident__abnormal_termination
, false),
673 raii2(Ident___abnormal_termination
, false),
674 raii3(Ident_AbnormalTermination
, false);
676 if (Tok
.isNot(tok::l_brace
))
677 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
679 ParseScope
FinallyScope(this, 0);
680 Actions
.ActOnStartSEHFinallyBlock();
682 StmtResult
Block(ParseCompoundStatement());
683 if(Block
.isInvalid()) {
684 Actions
.ActOnAbortSEHFinallyBlock();
688 return Actions
.ActOnFinishSEHFinallyBlock(FinallyLoc
, Block
.get());
693 /// seh-leave-statement:
696 StmtResult
Parser::ParseSEHLeaveStatement() {
697 SourceLocation LeaveLoc
= ConsumeToken(); // eat the '__leave'.
698 return Actions
.ActOnSEHLeaveStmt(LeaveLoc
, getCurScope());
701 /// ParseLabeledStatement - We have an identifier and a ':' after it.
705 /// [GNU] identifier ':' attributes[opt]
707 /// labeled-statement:
710 StmtResult
Parser::ParseLabeledStatement(ParsedAttributes
&Attrs
,
711 ParsedStmtContext StmtCtx
) {
712 assert(Tok
.is(tok::identifier
) && Tok
.getIdentifierInfo() &&
713 "Not an identifier!");
715 // The substatement is always a 'statement', not a 'declaration', but is
716 // otherwise in the same context as the labeled-statement.
717 StmtCtx
&= ~ParsedStmtContext::AllowDeclarationsInC
;
719 Token IdentTok
= Tok
; // Save the whole token.
720 ConsumeToken(); // eat the identifier.
722 assert(Tok
.is(tok::colon
) && "Not a label!");
724 // identifier ':' statement
725 SourceLocation ColonLoc
= ConsumeToken();
727 // Read label attributes, if present.
729 if (Tok
.is(tok::kw___attribute
)) {
730 ParsedAttributes
TempAttrs(AttrFactory
);
731 ParseGNUAttributes(TempAttrs
);
733 // In C++, GNU attributes only apply to the label if they are followed by a
734 // semicolon, to disambiguate label attributes from attributes on a labeled
737 // This doesn't quite match what GCC does; if the attribute list is empty
738 // and followed by a semicolon, GCC will reject (it appears to parse the
739 // attributes as part of a statement in that case). That looks like a bug.
740 if (!getLangOpts().CPlusPlus
|| Tok
.is(tok::semi
))
741 Attrs
.takeAllFrom(TempAttrs
);
744 ParsedAttributes
EmptyCXX11Attrs(AttrFactory
);
745 SubStmt
= ParseStatementOrDeclarationAfterAttributes(
746 Stmts
, StmtCtx
, nullptr, EmptyCXX11Attrs
, TempAttrs
);
747 if (!TempAttrs
.empty() && !SubStmt
.isInvalid())
748 SubStmt
= Actions
.ActOnAttributedStmt(TempAttrs
, SubStmt
.get());
752 // The label may have no statement following it
753 if (SubStmt
.isUnset() && Tok
.is(tok::r_brace
)) {
754 DiagnoseLabelAtEndOfCompoundStatement();
755 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
758 // If we've not parsed a statement yet, parse one now.
759 if (!SubStmt
.isInvalid() && !SubStmt
.isUsable())
760 SubStmt
= ParseStatement(nullptr, StmtCtx
);
762 // Broken substmt shouldn't prevent the label from being added to the AST.
763 if (SubStmt
.isInvalid())
764 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
766 LabelDecl
*LD
= Actions
.LookupOrCreateLabel(IdentTok
.getIdentifierInfo(),
767 IdentTok
.getLocation());
768 Actions
.ProcessDeclAttributeList(Actions
.CurScope
, LD
, Attrs
);
771 return Actions
.ActOnLabelStmt(IdentTok
.getLocation(), LD
, ColonLoc
,
775 /// ParseCaseStatement
776 /// labeled-statement:
777 /// 'case' constant-expression ':' statement
778 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
780 StmtResult
Parser::ParseCaseStatement(ParsedStmtContext StmtCtx
,
781 bool MissingCase
, ExprResult Expr
) {
782 assert((MissingCase
|| Tok
.is(tok::kw_case
)) && "Not a case stmt!");
784 // The substatement is always a 'statement', not a 'declaration', but is
785 // otherwise in the same context as the labeled-statement.
786 StmtCtx
&= ~ParsedStmtContext::AllowDeclarationsInC
;
788 // It is very common for code to contain many case statements recursively
789 // nested, as in (but usually without indentation):
796 // Parsing this naively works, but is both inefficient and can cause us to run
797 // out of stack space in our recursive descent parser. As a special case,
798 // flatten this recursion into an iterative loop. This is complex and gross,
799 // but all the grossness is constrained to ParseCaseStatement (and some
800 // weirdness in the actions), so this is just local grossness :).
802 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
804 StmtResult
TopLevelCase(true);
806 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
807 // gets updated each time a new case is parsed, and whose body is unset so
808 // far. When parsing 'case 4', this is the 'case 3' node.
809 Stmt
*DeepestParsedCaseStmt
= nullptr;
811 // While we have case statements, eat and stack them.
812 SourceLocation ColonLoc
;
814 SourceLocation CaseLoc
= MissingCase
? Expr
.get()->getExprLoc() :
815 ConsumeToken(); // eat the 'case'.
816 ColonLoc
= SourceLocation();
818 if (Tok
.is(tok::code_completion
)) {
820 Actions
.CodeCompleteCase(getCurScope());
824 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
825 /// Disable this form of error recovery while we're parsing the case
827 ColonProtectionRAIIObject
ColonProtection(*this);
831 LHS
= ParseCaseExpression(CaseLoc
);
832 if (LHS
.isInvalid()) {
833 // If constant-expression is parsed unsuccessfully, recover by skipping
834 // current case statement (moving to the colon that ends it).
835 if (!SkipUntil(tok::colon
, tok::r_brace
, StopAtSemi
| StopBeforeMatch
))
843 // GNU case range extension.
844 SourceLocation DotDotDotLoc
;
846 if (TryConsumeToken(tok::ellipsis
, DotDotDotLoc
)) {
847 Diag(DotDotDotLoc
, diag::ext_gnu_case_range
);
848 RHS
= ParseCaseExpression(CaseLoc
);
849 if (RHS
.isInvalid()) {
850 if (!SkipUntil(tok::colon
, tok::r_brace
, StopAtSemi
| StopBeforeMatch
))
855 ColonProtection
.restore();
857 if (TryConsumeToken(tok::colon
, ColonLoc
)) {
858 } else if (TryConsumeToken(tok::semi
, ColonLoc
) ||
859 TryConsumeToken(tok::coloncolon
, ColonLoc
)) {
860 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
861 Diag(ColonLoc
, diag::err_expected_after
)
862 << "'case'" << tok::colon
863 << FixItHint::CreateReplacement(ColonLoc
, ":");
865 SourceLocation ExpectedLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
866 Diag(ExpectedLoc
, diag::err_expected_after
)
867 << "'case'" << tok::colon
868 << FixItHint::CreateInsertion(ExpectedLoc
, ":");
869 ColonLoc
= ExpectedLoc
;
873 Actions
.ActOnCaseStmt(CaseLoc
, LHS
, DotDotDotLoc
, RHS
, ColonLoc
);
875 // If we had a sema error parsing this case, then just ignore it and
876 // continue parsing the sub-stmt.
877 if (Case
.isInvalid()) {
878 if (TopLevelCase
.isInvalid()) // No parsed case stmts.
879 return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
880 // Otherwise, just don't add it as a nested case.
882 // If this is the first case statement we parsed, it becomes TopLevelCase.
883 // Otherwise we link it into the current chain.
884 Stmt
*NextDeepest
= Case
.get();
885 if (TopLevelCase
.isInvalid())
888 Actions
.ActOnCaseStmtBody(DeepestParsedCaseStmt
, Case
.get());
889 DeepestParsedCaseStmt
= NextDeepest
;
892 // Handle all case statements.
893 } while (Tok
.is(tok::kw_case
));
895 // If we found a non-case statement, start by parsing it.
898 if (Tok
.is(tok::r_brace
)) {
899 // "switch (X) { case 4: }", is valid and is treated as if label was
900 // followed by a null statement.
901 DiagnoseLabelAtEndOfCompoundStatement();
902 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
904 SubStmt
= ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
907 // Install the body into the most deeply-nested case.
908 if (DeepestParsedCaseStmt
) {
909 // Broken sub-stmt shouldn't prevent forming the case statement properly.
910 if (SubStmt
.isInvalid())
911 SubStmt
= Actions
.ActOnNullStmt(SourceLocation());
912 Actions
.ActOnCaseStmtBody(DeepestParsedCaseStmt
, SubStmt
.get());
915 // Return the top level parsed statement tree.
919 /// ParseDefaultStatement
920 /// labeled-statement:
921 /// 'default' ':' statement
922 /// Note that this does not parse the 'statement' at the end.
924 StmtResult
Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx
) {
925 assert(Tok
.is(tok::kw_default
) && "Not a default stmt!");
927 // The substatement is always a 'statement', not a 'declaration', but is
928 // otherwise in the same context as the labeled-statement.
929 StmtCtx
&= ~ParsedStmtContext::AllowDeclarationsInC
;
931 SourceLocation DefaultLoc
= ConsumeToken(); // eat the 'default'.
933 SourceLocation ColonLoc
;
934 if (TryConsumeToken(tok::colon
, ColonLoc
)) {
935 } else if (TryConsumeToken(tok::semi
, ColonLoc
)) {
936 // Treat "default;" as a typo for "default:".
937 Diag(ColonLoc
, diag::err_expected_after
)
938 << "'default'" << tok::colon
939 << FixItHint::CreateReplacement(ColonLoc
, ":");
941 SourceLocation ExpectedLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
942 Diag(ExpectedLoc
, diag::err_expected_after
)
943 << "'default'" << tok::colon
944 << FixItHint::CreateInsertion(ExpectedLoc
, ":");
945 ColonLoc
= ExpectedLoc
;
950 if (Tok
.is(tok::r_brace
)) {
951 // "switch (X) {... default: }", is valid and is treated as if label was
952 // followed by a null statement.
953 DiagnoseLabelAtEndOfCompoundStatement();
954 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
956 SubStmt
= ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
959 // Broken sub-stmt shouldn't prevent forming the case statement properly.
960 if (SubStmt
.isInvalid())
961 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
963 return Actions
.ActOnDefaultStmt(DefaultLoc
, ColonLoc
,
964 SubStmt
.get(), getCurScope());
967 StmtResult
Parser::ParseCompoundStatement(bool isStmtExpr
) {
968 return ParseCompoundStatement(isStmtExpr
,
969 Scope::DeclScope
| Scope::CompoundStmtScope
);
972 /// ParseCompoundStatement - Parse a "{}" block.
974 /// compound-statement: [C99 6.8.2]
975 /// { block-item-list[opt] }
976 /// [GNU] { label-declarations block-item-list } [TODO]
980 /// block-item-list block-item
984 /// [GNU] '__extension__' declaration
987 /// [GNU] label-declarations:
988 /// [GNU] label-declaration
989 /// [GNU] label-declarations label-declaration
991 /// [GNU] label-declaration:
992 /// [GNU] '__label__' identifier-list ';'
994 StmtResult
Parser::ParseCompoundStatement(bool isStmtExpr
,
995 unsigned ScopeFlags
) {
996 assert(Tok
.is(tok::l_brace
) && "Not a compound stmt!");
998 // Enter a scope to hold everything within the compound stmt. Compound
999 // statements can always hold declarations.
1000 ParseScope
CompoundScope(this, ScopeFlags
);
1002 // Parse the statements in the body.
1003 return ParseCompoundStatementBody(isStmtExpr
);
1006 /// Parse any pragmas at the start of the compound expression. We handle these
1007 /// separately since some pragmas (FP_CONTRACT) must appear before any C
1008 /// statement in the compound, but may be intermingled with other pragmas.
1009 void Parser::ParseCompoundStatementLeadingPragmas() {
1010 bool checkForPragmas
= true;
1011 while (checkForPragmas
) {
1012 switch (Tok
.getKind()) {
1013 case tok::annot_pragma_vis
:
1014 HandlePragmaVisibility();
1016 case tok::annot_pragma_pack
:
1019 case tok::annot_pragma_msstruct
:
1020 HandlePragmaMSStruct();
1022 case tok::annot_pragma_align
:
1023 HandlePragmaAlign();
1025 case tok::annot_pragma_weak
:
1028 case tok::annot_pragma_weakalias
:
1029 HandlePragmaWeakAlias();
1031 case tok::annot_pragma_redefine_extname
:
1032 HandlePragmaRedefineExtname();
1034 case tok::annot_pragma_opencl_extension
:
1035 HandlePragmaOpenCLExtension();
1037 case tok::annot_pragma_fp_contract
:
1038 HandlePragmaFPContract();
1040 case tok::annot_pragma_fp
:
1043 case tok::annot_pragma_fenv_access
:
1044 case tok::annot_pragma_fenv_access_ms
:
1045 HandlePragmaFEnvAccess();
1047 case tok::annot_pragma_fenv_round
:
1048 HandlePragmaFEnvRound();
1050 case tok::annot_pragma_float_control
:
1051 HandlePragmaFloatControl();
1053 case tok::annot_pragma_ms_pointers_to_members
:
1054 HandlePragmaMSPointersToMembers();
1056 case tok::annot_pragma_ms_pragma
:
1057 HandlePragmaMSPragma();
1059 case tok::annot_pragma_ms_vtordisp
:
1060 HandlePragmaMSVtorDisp();
1062 case tok::annot_pragma_dump
:
1066 checkForPragmas
= false;
1073 void Parser::DiagnoseLabelAtEndOfCompoundStatement() {
1074 if (getLangOpts().CPlusPlus
) {
1075 Diag(Tok
, getLangOpts().CPlusPlus23
1076 ? diag::warn_cxx20_compat_label_end_of_compound_statement
1077 : diag::ext_cxx_label_end_of_compound_statement
);
1079 Diag(Tok
, getLangOpts().C23
1080 ? diag::warn_c23_compat_label_end_of_compound_statement
1081 : diag::ext_c_label_end_of_compound_statement
);
1085 /// Consume any extra semi-colons resulting in null statements,
1086 /// returning true if any tok::semi were consumed.
1087 bool Parser::ConsumeNullStmt(StmtVector
&Stmts
) {
1088 if (!Tok
.is(tok::semi
))
1091 SourceLocation StartLoc
= Tok
.getLocation();
1092 SourceLocation EndLoc
;
1094 while (Tok
.is(tok::semi
) && !Tok
.hasLeadingEmptyMacro() &&
1095 Tok
.getLocation().isValid() && !Tok
.getLocation().isMacroID()) {
1096 EndLoc
= Tok
.getLocation();
1098 // Don't just ConsumeToken() this tok::semi, do store it in AST.
1100 ParseStatementOrDeclaration(Stmts
, ParsedStmtContext::SubStmt
);
1102 Stmts
.push_back(R
.get());
1105 // Did not consume any extra semi.
1106 if (EndLoc
.isInvalid())
1109 Diag(StartLoc
, diag::warn_null_statement
)
1110 << FixItHint::CreateRemoval(SourceRange(StartLoc
, EndLoc
));
1114 StmtResult
Parser::handleExprStmt(ExprResult E
, ParsedStmtContext StmtCtx
) {
1115 bool IsStmtExprResult
= false;
1116 if ((StmtCtx
& ParsedStmtContext::InStmtExpr
) != ParsedStmtContext()) {
1117 // For GCC compatibility we skip past NullStmts.
1118 unsigned LookAhead
= 0;
1119 while (GetLookAheadToken(LookAhead
).is(tok::semi
)) {
1122 // Then look to see if the next two tokens close the statement expression;
1123 // if so, this expression statement is the last statement in a statement
1125 IsStmtExprResult
= GetLookAheadToken(LookAhead
).is(tok::r_brace
) &&
1126 GetLookAheadToken(LookAhead
+ 1).is(tok::r_paren
);
1129 if (IsStmtExprResult
)
1130 E
= Actions
.ActOnStmtExprResult(E
);
1131 return Actions
.ActOnExprStmt(E
, /*DiscardedValue=*/!IsStmtExprResult
);
1134 /// ParseCompoundStatementBody - Parse a sequence of statements optionally
1135 /// followed by a label and invoke the ActOnCompoundStmt action. This expects
1136 /// the '{' to be the current token, and consume the '}' at the end of the
1137 /// block. It does not manipulate the scope stack.
1138 StmtResult
Parser::ParseCompoundStatementBody(bool isStmtExpr
) {
1139 PrettyStackTraceLoc
CrashInfo(PP
.getSourceManager(),
1141 "in compound statement ('{}')");
1143 // Record the current FPFeatures, restore on leaving the
1144 // compound statement.
1145 Sema::FPFeaturesStateRAII
SaveFPFeatures(Actions
);
1147 InMessageExpressionRAIIObject
InMessage(*this, false);
1148 BalancedDelimiterTracker
T(*this, tok::l_brace
);
1149 if (T
.consumeOpen())
1152 Sema::CompoundScopeRAII
CompoundScope(Actions
, isStmtExpr
);
1154 // Parse any pragmas at the beginning of the compound statement.
1155 ParseCompoundStatementLeadingPragmas();
1156 Actions
.ActOnAfterCompoundStatementLeadingPragmas();
1160 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1161 // only allowed at the start of a compound stmt regardless of the language.
1162 while (Tok
.is(tok::kw___label__
)) {
1163 SourceLocation LabelLoc
= ConsumeToken();
1165 SmallVector
<Decl
*, 8> DeclsInGroup
;
1167 if (Tok
.isNot(tok::identifier
)) {
1168 Diag(Tok
, diag::err_expected
) << tok::identifier
;
1172 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1173 SourceLocation IdLoc
= ConsumeToken();
1174 DeclsInGroup
.push_back(Actions
.LookupOrCreateLabel(II
, IdLoc
, LabelLoc
));
1176 if (!TryConsumeToken(tok::comma
))
1180 DeclSpec
DS(AttrFactory
);
1181 DeclGroupPtrTy Res
=
1182 Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
, DeclsInGroup
);
1183 StmtResult R
= Actions
.ActOnDeclStmt(Res
, LabelLoc
, Tok
.getLocation());
1185 ExpectAndConsumeSemi(diag::err_expected_semi_declaration
);
1187 Stmts
.push_back(R
.get());
1190 ParsedStmtContext SubStmtCtx
=
1191 ParsedStmtContext::Compound
|
1192 (isStmtExpr
? ParsedStmtContext::InStmtExpr
: ParsedStmtContext());
1194 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
1195 Tok
.isNot(tok::eof
)) {
1196 if (Tok
.is(tok::annot_pragma_unused
)) {
1197 HandlePragmaUnused();
1201 if (ConsumeNullStmt(Stmts
))
1205 if (Tok
.isNot(tok::kw___extension__
)) {
1206 R
= ParseStatementOrDeclaration(Stmts
, SubStmtCtx
);
1208 // __extension__ can start declarations and it can also be a unary
1209 // operator for expressions. Consume multiple __extension__ markers here
1210 // until we can determine which is which.
1211 // FIXME: This loses extension expressions in the AST!
1212 SourceLocation ExtLoc
= ConsumeToken();
1213 while (Tok
.is(tok::kw___extension__
))
1216 ParsedAttributes
attrs(AttrFactory
);
1217 MaybeParseCXX11Attributes(attrs
, /*MightBeObjCMessageSend*/ true);
1219 // If this is the start of a declaration, parse it as such.
1220 if (isDeclarationStatement()) {
1221 // __extension__ silences extension warnings in the subdeclaration.
1222 // FIXME: Save the __extension__ on the decl as a node somehow?
1223 ExtensionRAIIObject
O(Diags
);
1225 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
1226 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
1227 DeclGroupPtrTy Res
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
,
1228 attrs
, DeclSpecAttrs
);
1229 R
= Actions
.ActOnDeclStmt(Res
, DeclStart
, DeclEnd
);
1231 // Otherwise this was a unary __extension__ marker.
1232 ExprResult
Res(ParseExpressionWithLeadingExtension(ExtLoc
));
1234 if (Res
.isInvalid()) {
1235 SkipUntil(tok::semi
);
1239 // Eat the semicolon at the end of stmt and convert the expr into a
1241 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr
);
1242 R
= handleExprStmt(Res
, SubStmtCtx
);
1244 R
= Actions
.ActOnAttributedStmt(attrs
, R
.get());
1249 Stmts
.push_back(R
.get());
1251 // Warn the user that using option `-ffp-eval-method=source` on a
1252 // 32-bit target and feature `sse` disabled, or using
1253 // `pragma clang fp eval_method=source` and feature `sse` disabled, is not
1255 if (!PP
.getTargetInfo().supportSourceEvalMethod() &&
1256 (PP
.getLastFPEvalPragmaLocation().isValid() ||
1257 PP
.getCurrentFPEvalMethod() ==
1258 LangOptions::FPEvalMethodKind::FEM_Source
))
1259 Diag(Tok
.getLocation(),
1260 diag::warn_no_support_for_eval_method_source_on_m32
);
1262 SourceLocation CloseLoc
= Tok
.getLocation();
1264 // We broke out of the while loop because we found a '}' or EOF.
1265 if (!T
.consumeClose()) {
1266 // If this is the '})' of a statement expression, check that it's written
1267 // in a sensible way.
1268 if (isStmtExpr
&& Tok
.is(tok::r_paren
))
1269 checkCompoundToken(CloseLoc
, tok::r_brace
, CompoundToken::StmtExprEnd
);
1271 // Recover by creating a compound statement with what we parsed so far,
1272 // instead of dropping everything and returning StmtError().
1275 if (T
.getCloseLocation().isValid())
1276 CloseLoc
= T
.getCloseLocation();
1278 return Actions
.ActOnCompoundStmt(T
.getOpenLocation(), CloseLoc
,
1282 /// ParseParenExprOrCondition:
1283 /// [C ] '(' expression ')'
1284 /// [C++] '(' condition ')'
1285 /// [C++1z] '(' init-statement[opt] condition ')'
1287 /// This function parses and performs error recovery on the specified condition
1288 /// or expression (depending on whether we're in C++ or C mode). This function
1289 /// goes out of its way to recover well. It returns true if there was a parser
1290 /// error (the right paren couldn't be found), which indicates that the caller
1291 /// should try to recover harder. It returns false if the condition is
1292 /// successfully parsed. Note that a successful parse can still have semantic
1293 /// errors in the condition.
1294 /// Additionally, it will assign the location of the outer-most '(' and ')',
1295 /// to LParenLoc and RParenLoc, respectively.
1296 bool Parser::ParseParenExprOrCondition(StmtResult
*InitStmt
,
1297 Sema::ConditionResult
&Cond
,
1299 Sema::ConditionKind CK
,
1300 SourceLocation
&LParenLoc
,
1301 SourceLocation
&RParenLoc
) {
1302 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1304 SourceLocation Start
= Tok
.getLocation();
1306 if (getLangOpts().CPlusPlus
) {
1307 Cond
= ParseCXXCondition(InitStmt
, Loc
, CK
, false);
1309 ExprResult CondExpr
= ParseExpression();
1311 // If required, convert to a boolean value.
1312 if (CondExpr
.isInvalid())
1313 Cond
= Sema::ConditionError();
1315 Cond
= Actions
.ActOnCondition(getCurScope(), Loc
, CondExpr
.get(), CK
,
1316 /*MissingOK=*/false);
1319 // If the parser was confused by the condition and we don't have a ')', try to
1320 // recover by skipping ahead to a semi and bailing out. If condexp is
1321 // semantically invalid but we have well formed code, keep going.
1322 if (Cond
.isInvalid() && Tok
.isNot(tok::r_paren
)) {
1323 SkipUntil(tok::semi
);
1324 // Skipping may have stopped if it found the containing ')'. If so, we can
1325 // continue parsing the if statement.
1326 if (Tok
.isNot(tok::r_paren
))
1330 if (Cond
.isInvalid()) {
1331 ExprResult CondExpr
= Actions
.CreateRecoveryExpr(
1332 Start
, Tok
.getLocation() == Start
? Start
: PrevTokLocation
, {},
1333 Actions
.PreferredConditionType(CK
));
1334 if (!CondExpr
.isInvalid())
1335 Cond
= Actions
.ActOnCondition(getCurScope(), Loc
, CondExpr
.get(), CK
,
1336 /*MissingOK=*/false);
1339 // Either the condition is valid or the rparen is present.
1341 LParenLoc
= T
.getOpenLocation();
1342 RParenLoc
= T
.getCloseLocation();
1344 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1345 // that all callers are looking for a statement after the condition, so ")"
1347 while (Tok
.is(tok::r_paren
)) {
1348 Diag(Tok
, diag::err_extraneous_rparen_in_condition
)
1349 << FixItHint::CreateRemoval(Tok
.getLocation());
1358 enum MisleadingStatementKind
{ MSK_if
, MSK_else
, MSK_for
, MSK_while
};
1360 struct MisleadingIndentationChecker
{
1362 SourceLocation StmtLoc
;
1363 SourceLocation PrevLoc
;
1364 unsigned NumDirectives
;
1365 MisleadingStatementKind Kind
;
1367 MisleadingIndentationChecker(Parser
&P
, MisleadingStatementKind K
,
1369 : P(P
), StmtLoc(SL
), PrevLoc(P
.getCurToken().getLocation()),
1370 NumDirectives(P
.getPreprocessor().getNumDirectives()), Kind(K
),
1371 ShouldSkip(P
.getCurToken().is(tok::l_brace
)) {
1372 if (!P
.MisleadingIndentationElseLoc
.isInvalid()) {
1373 StmtLoc
= P
.MisleadingIndentationElseLoc
;
1374 P
.MisleadingIndentationElseLoc
= SourceLocation();
1376 if (Kind
== MSK_else
&& !ShouldSkip
)
1377 P
.MisleadingIndentationElseLoc
= SL
;
1380 /// Compute the column number will aligning tabs on TabStop (-ftabstop), this
1381 /// gives the visual indentation of the SourceLocation.
1382 static unsigned getVisualIndentation(SourceManager
&SM
, SourceLocation Loc
) {
1383 unsigned TabStop
= SM
.getDiagnostics().getDiagnosticOptions().TabStop
;
1385 unsigned ColNo
= SM
.getSpellingColumnNumber(Loc
);
1386 if (ColNo
== 0 || TabStop
== 1)
1389 std::pair
<FileID
, unsigned> FIDAndOffset
= SM
.getDecomposedLoc(Loc
);
1392 StringRef BufData
= SM
.getBufferData(FIDAndOffset
.first
, &Invalid
);
1396 const char *EndPos
= BufData
.data() + FIDAndOffset
.second
;
1397 // FileOffset are 0-based and Column numbers are 1-based
1398 assert(FIDAndOffset
.second
+ 1 >= ColNo
&&
1399 "Column number smaller than file offset?");
1401 unsigned VisualColumn
= 0; // Stored as 0-based column, here.
1402 // Loop from beginning of line up to Loc's file position, counting columns,
1404 for (const char *CurPos
= EndPos
- (ColNo
- 1); CurPos
!= EndPos
;
1406 if (*CurPos
== '\t')
1407 // Advance visual column to next tabstop.
1408 VisualColumn
+= (TabStop
- VisualColumn
% TabStop
);
1412 return VisualColumn
+ 1;
1416 Token Tok
= P
.getCurToken();
1417 if (P
.getActions().getDiagnostics().isIgnored(
1418 diag::warn_misleading_indentation
, Tok
.getLocation()) ||
1419 ShouldSkip
|| NumDirectives
!= P
.getPreprocessor().getNumDirectives() ||
1420 Tok
.isOneOf(tok::semi
, tok::r_brace
) || Tok
.isAnnotation() ||
1421 Tok
.getLocation().isMacroID() || PrevLoc
.isMacroID() ||
1422 StmtLoc
.isMacroID() ||
1423 (Kind
== MSK_else
&& P
.MisleadingIndentationElseLoc
.isInvalid())) {
1424 P
.MisleadingIndentationElseLoc
= SourceLocation();
1427 if (Kind
== MSK_else
)
1428 P
.MisleadingIndentationElseLoc
= SourceLocation();
1430 SourceManager
&SM
= P
.getPreprocessor().getSourceManager();
1431 unsigned PrevColNum
= getVisualIndentation(SM
, PrevLoc
);
1432 unsigned CurColNum
= getVisualIndentation(SM
, Tok
.getLocation());
1433 unsigned StmtColNum
= getVisualIndentation(SM
, StmtLoc
);
1435 if (PrevColNum
!= 0 && CurColNum
!= 0 && StmtColNum
!= 0 &&
1436 ((PrevColNum
> StmtColNum
&& PrevColNum
== CurColNum
) ||
1437 !Tok
.isAtStartOfLine()) &&
1438 SM
.getPresumedLineNumber(StmtLoc
) !=
1439 SM
.getPresumedLineNumber(Tok
.getLocation()) &&
1440 (Tok
.isNot(tok::identifier
) ||
1441 P
.getPreprocessor().LookAhead(0).isNot(tok::colon
))) {
1442 P
.Diag(Tok
.getLocation(), diag::warn_misleading_indentation
) << Kind
;
1443 P
.Diag(StmtLoc
, diag::note_previous_statement
);
1450 /// ParseIfStatement
1451 /// if-statement: [C99 6.8.4.1]
1452 /// 'if' '(' expression ')' statement
1453 /// 'if' '(' expression ')' statement 'else' statement
1454 /// [C++] 'if' '(' condition ')' statement
1455 /// [C++] 'if' '(' condition ')' statement 'else' statement
1456 /// [C++23] 'if' '!' [opt] consteval compound-statement
1457 /// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement
1459 StmtResult
Parser::ParseIfStatement(SourceLocation
*TrailingElseLoc
) {
1460 assert(Tok
.is(tok::kw_if
) && "Not an if stmt!");
1461 SourceLocation IfLoc
= ConsumeToken(); // eat the 'if'.
1463 bool IsConstexpr
= false;
1464 bool IsConsteval
= false;
1465 SourceLocation NotLocation
;
1466 SourceLocation ConstevalLoc
;
1468 if (Tok
.is(tok::kw_constexpr
)) {
1469 Diag(Tok
, getLangOpts().CPlusPlus17
? diag::warn_cxx14_compat_constexpr_if
1470 : diag::ext_constexpr_if
);
1474 if (Tok
.is(tok::exclaim
)) {
1475 NotLocation
= ConsumeToken();
1478 if (Tok
.is(tok::kw_consteval
)) {
1479 Diag(Tok
, getLangOpts().CPlusPlus23
? diag::warn_cxx20_compat_consteval_if
1480 : diag::ext_consteval_if
);
1482 ConstevalLoc
= ConsumeToken();
1485 if (!IsConsteval
&& (NotLocation
.isValid() || Tok
.isNot(tok::l_paren
))) {
1486 Diag(Tok
, diag::err_expected_lparen_after
) << "if";
1487 SkipUntil(tok::semi
);
1491 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1493 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1494 // the case for C90.
1497 // A name introduced by a declaration in a condition is in scope from its
1498 // point of declaration until the end of the substatements controlled by the
1501 // Names declared in the for-init-statement, and in the condition of if,
1502 // while, for, and switch statements are local to the if, while, for, or
1503 // switch statement (including the controlled statement).
1505 ParseScope
IfScope(this, Scope::DeclScope
| Scope::ControlScope
, C99orCXX
);
1507 // Parse the condition.
1508 StmtResult InitStmt
;
1509 Sema::ConditionResult Cond
;
1510 SourceLocation LParen
;
1511 SourceLocation RParen
;
1512 std::optional
<bool> ConstexprCondition
;
1515 if (ParseParenExprOrCondition(&InitStmt
, Cond
, IfLoc
,
1516 IsConstexpr
? Sema::ConditionKind::ConstexprIf
1517 : Sema::ConditionKind::Boolean
,
1522 ConstexprCondition
= Cond
.getKnownValue();
1525 bool IsBracedThen
= Tok
.is(tok::l_brace
);
1527 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1528 // there is no compound stmt. C90 does not have this clause. We only do this
1529 // if the body isn't a compound statement to avoid push/pop in common cases.
1532 // The substatement in a selection-statement (each substatement, in the else
1533 // form of the if statement) implicitly defines a local scope.
1535 // For C++ we create a scope for the condition and a new scope for
1536 // substatements because:
1537 // -When the 'then' scope exits, we want the condition declaration to still be
1538 // active for the 'else' scope too.
1539 // -Sema will detect name clashes by considering declarations of a
1540 // 'ControlScope' as part of its direct subscope.
1541 // -If we wanted the condition and substatement to be in the same scope, we
1542 // would have to notify ParseStatement not to create a new scope. It's
1543 // simpler to let it create a new scope.
1545 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, IsBracedThen
);
1547 MisleadingIndentationChecker
MIChecker(*this, MSK_if
, IfLoc
);
1549 // Read the 'then' stmt.
1550 SourceLocation ThenStmtLoc
= Tok
.getLocation();
1552 SourceLocation InnerStatementTrailingElseLoc
;
1553 StmtResult ThenStmt
;
1555 bool ShouldEnter
= ConstexprCondition
&& !*ConstexprCondition
;
1556 Sema::ExpressionEvaluationContext Context
=
1557 Sema::ExpressionEvaluationContext::DiscardedStatement
;
1558 if (NotLocation
.isInvalid() && IsConsteval
) {
1559 Context
= Sema::ExpressionEvaluationContext::ImmediateFunctionContext
;
1563 EnterExpressionEvaluationContext
PotentiallyDiscarded(
1564 Actions
, Context
, nullptr,
1565 Sema::ExpressionEvaluationContextRecord::EK_Other
, ShouldEnter
);
1566 ThenStmt
= ParseStatement(&InnerStatementTrailingElseLoc
);
1569 if (Tok
.isNot(tok::kw_else
))
1572 // Pop the 'if' scope if needed.
1575 // If it has an else, parse it.
1576 SourceLocation ElseLoc
;
1577 SourceLocation ElseStmtLoc
;
1578 StmtResult ElseStmt
;
1580 if (Tok
.is(tok::kw_else
)) {
1581 if (TrailingElseLoc
)
1582 *TrailingElseLoc
= Tok
.getLocation();
1584 ElseLoc
= ConsumeToken();
1585 ElseStmtLoc
= Tok
.getLocation();
1587 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1588 // there is no compound stmt. C90 does not have this clause. We only do
1589 // this if the body isn't a compound statement to avoid push/pop in common
1593 // The substatement in a selection-statement (each substatement, in the else
1594 // form of the if statement) implicitly defines a local scope.
1596 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
,
1597 Tok
.is(tok::l_brace
));
1599 MisleadingIndentationChecker
MIChecker(*this, MSK_else
, ElseLoc
);
1600 bool ShouldEnter
= ConstexprCondition
&& *ConstexprCondition
;
1601 Sema::ExpressionEvaluationContext Context
=
1602 Sema::ExpressionEvaluationContext::DiscardedStatement
;
1603 if (NotLocation
.isValid() && IsConsteval
) {
1604 Context
= Sema::ExpressionEvaluationContext::ImmediateFunctionContext
;
1608 EnterExpressionEvaluationContext
PotentiallyDiscarded(
1609 Actions
, Context
, nullptr,
1610 Sema::ExpressionEvaluationContextRecord::EK_Other
, ShouldEnter
);
1611 ElseStmt
= ParseStatement();
1613 if (ElseStmt
.isUsable())
1616 // Pop the 'else' scope if needed.
1618 } else if (Tok
.is(tok::code_completion
)) {
1620 Actions
.CodeCompleteAfterIf(getCurScope(), IsBracedThen
);
1622 } else if (InnerStatementTrailingElseLoc
.isValid()) {
1623 Diag(InnerStatementTrailingElseLoc
, diag::warn_dangling_else
);
1628 // If the then or else stmt is invalid and the other is valid (and present),
1629 // turn the invalid one into a null stmt to avoid dropping the other
1630 // part. If both are invalid, return error.
1631 if ((ThenStmt
.isInvalid() && ElseStmt
.isInvalid()) ||
1632 (ThenStmt
.isInvalid() && ElseStmt
.get() == nullptr) ||
1633 (ThenStmt
.get() == nullptr && ElseStmt
.isInvalid())) {
1634 // Both invalid, or one is invalid and other is non-present: return error.
1639 auto IsCompoundStatement
= [](const Stmt
*S
) {
1640 if (const auto *Outer
= dyn_cast_if_present
<AttributedStmt
>(S
))
1641 S
= Outer
->getSubStmt();
1642 return isa_and_nonnull
<clang::CompoundStmt
>(S
);
1645 if (!IsCompoundStatement(ThenStmt
.get())) {
1646 Diag(ConstevalLoc
, diag::err_expected_after
) << "consteval"
1650 if (!ElseStmt
.isUnset() && !IsCompoundStatement(ElseStmt
.get())) {
1651 Diag(ElseLoc
, diag::err_expected_after
) << "else"
1657 // Now if either are invalid, replace with a ';'.
1658 if (ThenStmt
.isInvalid())
1659 ThenStmt
= Actions
.ActOnNullStmt(ThenStmtLoc
);
1660 if (ElseStmt
.isInvalid())
1661 ElseStmt
= Actions
.ActOnNullStmt(ElseStmtLoc
);
1663 IfStatementKind Kind
= IfStatementKind::Ordinary
;
1665 Kind
= IfStatementKind::Constexpr
;
1666 else if (IsConsteval
)
1667 Kind
= NotLocation
.isValid() ? IfStatementKind::ConstevalNegated
1668 : IfStatementKind::ConstevalNonNegated
;
1670 return Actions
.ActOnIfStmt(IfLoc
, Kind
, LParen
, InitStmt
.get(), Cond
, RParen
,
1671 ThenStmt
.get(), ElseLoc
, ElseStmt
.get());
1674 /// ParseSwitchStatement
1675 /// switch-statement:
1676 /// 'switch' '(' expression ')' statement
1677 /// [C++] 'switch' '(' condition ')' statement
1678 StmtResult
Parser::ParseSwitchStatement(SourceLocation
*TrailingElseLoc
) {
1679 assert(Tok
.is(tok::kw_switch
) && "Not a switch stmt!");
1680 SourceLocation SwitchLoc
= ConsumeToken(); // eat the 'switch'.
1682 if (Tok
.isNot(tok::l_paren
)) {
1683 Diag(Tok
, diag::err_expected_lparen_after
) << "switch";
1684 SkipUntil(tok::semi
);
1688 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1690 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1691 // not the case for C90. Start the switch scope.
1694 // A name introduced by a declaration in a condition is in scope from its
1695 // point of declaration until the end of the substatements controlled by the
1698 // Names declared in the for-init-statement, and in the condition of if,
1699 // while, for, and switch statements are local to the if, while, for, or
1700 // switch statement (including the controlled statement).
1702 unsigned ScopeFlags
= Scope::SwitchScope
;
1704 ScopeFlags
|= Scope::DeclScope
| Scope::ControlScope
;
1705 ParseScope
SwitchScope(this, ScopeFlags
);
1707 // Parse the condition.
1708 StmtResult InitStmt
;
1709 Sema::ConditionResult Cond
;
1710 SourceLocation LParen
;
1711 SourceLocation RParen
;
1712 if (ParseParenExprOrCondition(&InitStmt
, Cond
, SwitchLoc
,
1713 Sema::ConditionKind::Switch
, LParen
, RParen
))
1716 StmtResult Switch
= Actions
.ActOnStartOfSwitchStmt(
1717 SwitchLoc
, LParen
, InitStmt
.get(), Cond
, RParen
);
1719 if (Switch
.isInvalid()) {
1720 // Skip the switch body.
1721 // FIXME: This is not optimal recovery, but parsing the body is more
1722 // dangerous due to the presence of case and default statements, which
1723 // will have no place to connect back with the switch.
1724 if (Tok
.is(tok::l_brace
)) {
1726 SkipUntil(tok::r_brace
);
1728 SkipUntil(tok::semi
);
1732 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1733 // there is no compound stmt. C90 does not have this clause. We only do this
1734 // if the body isn't a compound statement to avoid push/pop in common cases.
1737 // The substatement in a selection-statement (each substatement, in the else
1738 // form of the if statement) implicitly defines a local scope.
1740 // See comments in ParseIfStatement for why we create a scope for the
1741 // condition and a new scope for substatement in C++.
1743 getCurScope()->AddFlags(Scope::BreakScope
);
1744 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1746 // We have incremented the mangling number for the SwitchScope and the
1747 // InnerScope, which is one too many.
1749 getCurScope()->decrementMSManglingNumber();
1751 // Read the body statement.
1752 StmtResult
Body(ParseStatement(TrailingElseLoc
));
1758 return Actions
.ActOnFinishSwitchStmt(SwitchLoc
, Switch
.get(), Body
.get());
1761 /// ParseWhileStatement
1762 /// while-statement: [C99 6.8.5.1]
1763 /// 'while' '(' expression ')' statement
1764 /// [C++] 'while' '(' condition ')' statement
1765 StmtResult
Parser::ParseWhileStatement(SourceLocation
*TrailingElseLoc
) {
1766 assert(Tok
.is(tok::kw_while
) && "Not a while stmt!");
1767 SourceLocation WhileLoc
= Tok
.getLocation();
1768 ConsumeToken(); // eat the 'while'.
1770 if (Tok
.isNot(tok::l_paren
)) {
1771 Diag(Tok
, diag::err_expected_lparen_after
) << "while";
1772 SkipUntil(tok::semi
);
1776 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1778 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1779 // the case for C90. Start the loop scope.
1782 // A name introduced by a declaration in a condition is in scope from its
1783 // point of declaration until the end of the substatements controlled by the
1786 // Names declared in the for-init-statement, and in the condition of if,
1787 // while, for, and switch statements are local to the if, while, for, or
1788 // switch statement (including the controlled statement).
1790 unsigned ScopeFlags
;
1792 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
|
1793 Scope::DeclScope
| Scope::ControlScope
;
1795 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
1796 ParseScope
WhileScope(this, ScopeFlags
);
1798 // Parse the condition.
1799 Sema::ConditionResult Cond
;
1800 SourceLocation LParen
;
1801 SourceLocation RParen
;
1802 if (ParseParenExprOrCondition(nullptr, Cond
, WhileLoc
,
1803 Sema::ConditionKind::Boolean
, LParen
, RParen
))
1806 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1807 // there is no compound stmt. C90 does not have this clause. We only do this
1808 // if the body isn't a compound statement to avoid push/pop in common cases.
1811 // The substatement in an iteration-statement implicitly defines a local scope
1812 // which is entered and exited each time through the loop.
1814 // See comments in ParseIfStatement for why we create a scope for the
1815 // condition and a new scope for substatement in C++.
1817 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1819 MisleadingIndentationChecker
MIChecker(*this, MSK_while
, WhileLoc
);
1821 // Read the body statement.
1822 StmtResult
Body(ParseStatement(TrailingElseLoc
));
1824 if (Body
.isUsable())
1826 // Pop the body scope if needed.
1830 if (Cond
.isInvalid() || Body
.isInvalid())
1833 return Actions
.ActOnWhileStmt(WhileLoc
, LParen
, Cond
, RParen
, Body
.get());
1836 /// ParseDoStatement
1837 /// do-statement: [C99 6.8.5.2]
1838 /// 'do' statement 'while' '(' expression ')' ';'
1839 /// Note: this lets the caller parse the end ';'.
1840 StmtResult
Parser::ParseDoStatement() {
1841 assert(Tok
.is(tok::kw_do
) && "Not a do stmt!");
1842 SourceLocation DoLoc
= ConsumeToken(); // eat the 'do'.
1844 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1845 // the case for C90. Start the loop scope.
1846 unsigned ScopeFlags
;
1847 if (getLangOpts().C99
)
1848 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
| Scope::DeclScope
;
1850 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
1852 ParseScope
DoScope(this, ScopeFlags
);
1854 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1855 // there is no compound stmt. C90 does not have this clause. We only do this
1856 // if the body isn't a compound statement to avoid push/pop in common cases.
1859 // The substatement in an iteration-statement implicitly defines a local scope
1860 // which is entered and exited each time through the loop.
1862 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1863 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1865 // Read the body statement.
1866 StmtResult
Body(ParseStatement());
1868 // Pop the body scope if needed.
1871 if (Tok
.isNot(tok::kw_while
)) {
1872 if (!Body
.isInvalid()) {
1873 Diag(Tok
, diag::err_expected_while
);
1874 Diag(DoLoc
, diag::note_matching
) << "'do'";
1875 SkipUntil(tok::semi
, StopBeforeMatch
);
1879 SourceLocation WhileLoc
= ConsumeToken();
1881 if (Tok
.isNot(tok::l_paren
)) {
1882 Diag(Tok
, diag::err_expected_lparen_after
) << "do/while";
1883 SkipUntil(tok::semi
, StopBeforeMatch
);
1887 // Parse the parenthesized expression.
1888 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1891 // A do-while expression is not a condition, so can't have attributes.
1892 DiagnoseAndSkipCXX11Attributes();
1894 SourceLocation Start
= Tok
.getLocation();
1895 ExprResult Cond
= ParseExpression();
1896 // Correct the typos in condition before closing the scope.
1897 if (Cond
.isUsable())
1898 Cond
= Actions
.CorrectDelayedTyposInExpr(Cond
, /*InitDecl=*/nullptr,
1899 /*RecoverUncorrectedTypos=*/true);
1901 if (!Tok
.isOneOf(tok::r_paren
, tok::r_square
, tok::r_brace
))
1902 SkipUntil(tok::semi
);
1903 Cond
= Actions
.CreateRecoveryExpr(
1904 Start
, Start
== Tok
.getLocation() ? Start
: PrevTokLocation
, {},
1905 Actions
.getASTContext().BoolTy
);
1910 if (Cond
.isInvalid() || Body
.isInvalid())
1913 return Actions
.ActOnDoStmt(DoLoc
, Body
.get(), WhileLoc
, T
.getOpenLocation(),
1914 Cond
.get(), T
.getCloseLocation());
1917 bool Parser::isForRangeIdentifier() {
1918 assert(Tok
.is(tok::identifier
));
1920 const Token
&Next
= NextToken();
1921 if (Next
.is(tok::colon
))
1924 if (Next
.isOneOf(tok::l_square
, tok::kw_alignas
)) {
1925 TentativeParsingAction
PA(*this);
1927 SkipCXX11Attributes();
1928 bool Result
= Tok
.is(tok::colon
);
1936 /// ParseForStatement
1937 /// for-statement: [C99 6.8.5.3]
1938 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1939 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1940 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1943 /// 'co_await'[opt] [Coroutines]
1944 /// '(' for-range-declaration ':' for-range-initializer ')'
1946 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1947 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1949 /// [C++] for-init-statement:
1950 /// [C++] expression-statement
1951 /// [C++] simple-declaration
1952 /// [C++23] alias-declaration
1954 /// [C++0x] for-range-declaration:
1955 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1956 /// [C++0x] for-range-initializer:
1957 /// [C++0x] expression
1958 /// [C++0x] braced-init-list [TODO]
1959 StmtResult
Parser::ParseForStatement(SourceLocation
*TrailingElseLoc
) {
1960 assert(Tok
.is(tok::kw_for
) && "Not a for stmt!");
1961 SourceLocation ForLoc
= ConsumeToken(); // eat the 'for'.
1963 SourceLocation CoawaitLoc
;
1964 if (Tok
.is(tok::kw_co_await
))
1965 CoawaitLoc
= ConsumeToken();
1967 if (Tok
.isNot(tok::l_paren
)) {
1968 Diag(Tok
, diag::err_expected_lparen_after
) << "for";
1969 SkipUntil(tok::semi
);
1973 bool C99orCXXorObjC
= getLangOpts().C99
|| getLangOpts().CPlusPlus
||
1976 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1977 // the case for C90. Start the loop scope.
1980 // A name introduced by a declaration in a condition is in scope from its
1981 // point of declaration until the end of the substatements controlled by the
1984 // Names declared in the for-init-statement, and in the condition of if,
1985 // while, for, and switch statements are local to the if, while, for, or
1986 // switch statement (including the controlled statement).
1988 // Names declared in the for-init-statement are in the same declarative-region
1989 // as those declared in the condition.
1991 unsigned ScopeFlags
= 0;
1993 ScopeFlags
= Scope::DeclScope
| Scope::ControlScope
;
1995 ParseScope
ForScope(this, ScopeFlags
);
1997 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2002 bool ForEach
= false;
2003 StmtResult FirstPart
;
2004 Sema::ConditionResult SecondPart
;
2005 ExprResult Collection
;
2006 ForRangeInfo ForRangeInfo
;
2007 FullExprArg
ThirdPart(Actions
);
2009 if (Tok
.is(tok::code_completion
)) {
2011 Actions
.CodeCompleteOrdinaryName(getCurScope(),
2012 C99orCXXorObjC
? Sema::PCC_ForInit
2013 : Sema::PCC_Expression
);
2017 ParsedAttributes
attrs(AttrFactory
);
2018 MaybeParseCXX11Attributes(attrs
);
2020 SourceLocation EmptyInitStmtSemiLoc
;
2022 // Parse the first part of the for specifier.
2023 if (Tok
.is(tok::semi
)) { // for (;
2024 ProhibitAttributes(attrs
);
2025 // no first part, eat the ';'.
2026 SourceLocation SemiLoc
= Tok
.getLocation();
2027 if (!Tok
.hasLeadingEmptyMacro() && !SemiLoc
.isMacroID())
2028 EmptyInitStmtSemiLoc
= SemiLoc
;
2030 } else if (getLangOpts().CPlusPlus
&& Tok
.is(tok::identifier
) &&
2031 isForRangeIdentifier()) {
2032 ProhibitAttributes(attrs
);
2033 IdentifierInfo
*Name
= Tok
.getIdentifierInfo();
2034 SourceLocation Loc
= ConsumeToken();
2035 MaybeParseCXX11Attributes(attrs
);
2037 ForRangeInfo
.ColonLoc
= ConsumeToken();
2038 if (Tok
.is(tok::l_brace
))
2039 ForRangeInfo
.RangeExpr
= ParseBraceInitializer();
2041 ForRangeInfo
.RangeExpr
= ParseExpression();
2043 Diag(Loc
, diag::err_for_range_identifier
)
2044 << ((getLangOpts().CPlusPlus11
&& !getLangOpts().CPlusPlus17
)
2045 ? FixItHint::CreateInsertion(Loc
, "auto &&")
2048 ForRangeInfo
.LoopVar
=
2049 Actions
.ActOnCXXForRangeIdentifier(getCurScope(), Loc
, Name
, attrs
);
2050 } else if (isForInitDeclaration()) { // for (int X = 4;
2051 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
2053 // Parse declaration, which eats the ';'.
2054 if (!C99orCXXorObjC
) { // Use of C99-style for loops in C90 mode?
2055 Diag(Tok
, diag::ext_c99_variable_decl_in_for_loop
);
2056 Diag(Tok
, diag::warn_gcc_variable_decl_in_for_loop
);
2059 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
2060 if (Tok
.is(tok::kw_using
)) {
2061 DG
= ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit
,
2063 FirstPart
= Actions
.ActOnDeclStmt(DG
, DeclStart
, Tok
.getLocation());
2065 // In C++0x, "for (T NS:a" might not be a typo for ::
2066 bool MightBeForRangeStmt
= getLangOpts().CPlusPlus
;
2067 ColonProtectionRAIIObject
ColonProtection(*this, MightBeForRangeStmt
);
2068 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
2069 DG
= ParseSimpleDeclaration(
2070 DeclaratorContext::ForInit
, DeclEnd
, attrs
, DeclSpecAttrs
, false,
2071 MightBeForRangeStmt
? &ForRangeInfo
: nullptr);
2072 FirstPart
= Actions
.ActOnDeclStmt(DG
, DeclStart
, Tok
.getLocation());
2073 if (ForRangeInfo
.ParsedForRangeDecl()) {
2074 Diag(ForRangeInfo
.ColonLoc
, getLangOpts().CPlusPlus11
2075 ? diag::warn_cxx98_compat_for_range
2076 : diag::ext_for_range
);
2077 ForRangeInfo
.LoopVar
= FirstPart
;
2078 FirstPart
= StmtResult();
2079 } else if (Tok
.is(tok::semi
)) { // for (int x = 4;
2081 } else if ((ForEach
= isTokIdentifier_in())) {
2082 Actions
.ActOnForEachDeclStmt(DG
);
2083 // ObjC: for (id x in expr)
2084 ConsumeToken(); // consume 'in'
2086 if (Tok
.is(tok::code_completion
)) {
2088 Actions
.CodeCompleteObjCForCollection(getCurScope(), DG
);
2091 Collection
= ParseExpression();
2093 Diag(Tok
, diag::err_expected_semi_for
);
2097 ProhibitAttributes(attrs
);
2098 Value
= Actions
.CorrectDelayedTyposInExpr(ParseExpression());
2100 ForEach
= isTokIdentifier_in();
2102 // Turn the expression into a stmt.
2103 if (!Value
.isInvalid()) {
2105 FirstPart
= Actions
.ActOnForEachLValueExpr(Value
.get());
2107 // We already know this is not an init-statement within a for loop, so
2108 // if we are parsing a C++11 range-based for loop, we should treat this
2109 // expression statement as being a discarded value expression because
2110 // we will err below. This way we do not warn on an unused expression
2111 // that was an error in the first place, like with: for (expr : expr);
2112 bool IsRangeBasedFor
=
2113 getLangOpts().CPlusPlus11
&& !ForEach
&& Tok
.is(tok::colon
);
2114 FirstPart
= Actions
.ActOnExprStmt(Value
, !IsRangeBasedFor
);
2118 if (Tok
.is(tok::semi
)) {
2120 } else if (ForEach
) {
2121 ConsumeToken(); // consume 'in'
2123 if (Tok
.is(tok::code_completion
)) {
2125 Actions
.CodeCompleteObjCForCollection(getCurScope(), nullptr);
2128 Collection
= ParseExpression();
2129 } else if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::colon
) && FirstPart
.get()) {
2130 // User tried to write the reasonable, but ill-formed, for-range-statement
2131 // for (expr : expr) { ... }
2132 Diag(Tok
, diag::err_for_range_expected_decl
)
2133 << FirstPart
.get()->getSourceRange();
2134 SkipUntil(tok::r_paren
, StopBeforeMatch
);
2135 SecondPart
= Sema::ConditionError();
2137 if (!Value
.isInvalid()) {
2138 Diag(Tok
, diag::err_expected_semi_for
);
2140 // Skip until semicolon or rparen, don't consume it.
2141 SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
);
2142 if (Tok
.is(tok::semi
))
2148 // Parse the second part of the for specifier.
2149 if (!ForEach
&& !ForRangeInfo
.ParsedForRangeDecl() &&
2150 !SecondPart
.isInvalid()) {
2151 // Parse the second part of the for specifier.
2152 if (Tok
.is(tok::semi
)) { // for (...;;
2154 } else if (Tok
.is(tok::r_paren
)) {
2155 // missing both semicolons.
2157 if (getLangOpts().CPlusPlus
) {
2158 // C++2a: We've parsed an init-statement; we might have a
2159 // for-range-declaration next.
2160 bool MightBeForRangeStmt
= !ForRangeInfo
.ParsedForRangeDecl();
2161 ColonProtectionRAIIObject
ColonProtection(*this, MightBeForRangeStmt
);
2162 SourceLocation SecondPartStart
= Tok
.getLocation();
2163 Sema::ConditionKind CK
= Sema::ConditionKind::Boolean
;
2164 SecondPart
= ParseCXXCondition(
2165 /*InitStmt=*/nullptr, ForLoc
, CK
,
2166 // FIXME: recovery if we don't see another semi!
2167 /*MissingOK=*/true, MightBeForRangeStmt
? &ForRangeInfo
: nullptr,
2168 /*EnterForConditionScope=*/true);
2170 if (ForRangeInfo
.ParsedForRangeDecl()) {
2171 Diag(FirstPart
.get() ? FirstPart
.get()->getBeginLoc()
2172 : ForRangeInfo
.ColonLoc
,
2173 getLangOpts().CPlusPlus20
2174 ? diag::warn_cxx17_compat_for_range_init_stmt
2175 : diag::ext_for_range_init_stmt
)
2176 << (FirstPart
.get() ? FirstPart
.get()->getSourceRange()
2178 if (EmptyInitStmtSemiLoc
.isValid()) {
2179 Diag(EmptyInitStmtSemiLoc
, diag::warn_empty_init_statement
)
2181 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc
);
2185 if (SecondPart
.isInvalid()) {
2186 ExprResult CondExpr
= Actions
.CreateRecoveryExpr(
2188 Tok
.getLocation() == SecondPartStart
? SecondPartStart
2190 {}, Actions
.PreferredConditionType(CK
));
2191 if (!CondExpr
.isInvalid())
2192 SecondPart
= Actions
.ActOnCondition(getCurScope(), ForLoc
,
2194 /*MissingOK=*/false);
2198 // We permit 'continue' and 'break' in the condition of a for loop.
2199 getCurScope()->AddFlags(Scope::BreakScope
| Scope::ContinueScope
);
2201 ExprResult SecondExpr
= ParseExpression();
2202 if (SecondExpr
.isInvalid())
2203 SecondPart
= Sema::ConditionError();
2205 SecondPart
= Actions
.ActOnCondition(
2206 getCurScope(), ForLoc
, SecondExpr
.get(),
2207 Sema::ConditionKind::Boolean
, /*MissingOK=*/true);
2212 // Enter a break / continue scope, if we didn't already enter one while
2213 // parsing the second part.
2214 if (!getCurScope()->isContinueScope())
2215 getCurScope()->AddFlags(Scope::BreakScope
| Scope::ContinueScope
);
2217 // Parse the third part of the for statement.
2218 if (!ForEach
&& !ForRangeInfo
.ParsedForRangeDecl()) {
2219 if (Tok
.isNot(tok::semi
)) {
2220 if (!SecondPart
.isInvalid())
2221 Diag(Tok
, diag::err_expected_semi_for
);
2222 SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
);
2225 if (Tok
.is(tok::semi
)) {
2229 if (Tok
.isNot(tok::r_paren
)) { // for (...;...;)
2230 ExprResult Third
= ParseExpression();
2231 // FIXME: The C++11 standard doesn't actually say that this is a
2232 // discarded-value expression, but it clearly should be.
2233 ThirdPart
= Actions
.MakeFullDiscardedValueExpr(Third
.get());
2239 // C++ Coroutines [stmt.iter]:
2240 // 'co_await' can only be used for a range-based for statement.
2241 if (CoawaitLoc
.isValid() && !ForRangeInfo
.ParsedForRangeDecl()) {
2242 Diag(CoawaitLoc
, diag::err_for_co_await_not_range_for
);
2243 CoawaitLoc
= SourceLocation();
2246 if (CoawaitLoc
.isValid() && getLangOpts().CPlusPlus20
)
2247 Diag(CoawaitLoc
, diag::warn_deprecated_for_co_await
);
2249 // We need to perform most of the semantic analysis for a C++0x for-range
2250 // statememt before parsing the body, in order to be able to deduce the type
2251 // of an auto-typed loop variable.
2252 StmtResult ForRangeStmt
;
2253 StmtResult ForEachStmt
;
2255 if (ForRangeInfo
.ParsedForRangeDecl()) {
2256 ExprResult CorrectedRange
=
2257 Actions
.CorrectDelayedTyposInExpr(ForRangeInfo
.RangeExpr
.get());
2258 ForRangeStmt
= Actions
.ActOnCXXForRangeStmt(
2259 getCurScope(), ForLoc
, CoawaitLoc
, FirstPart
.get(),
2260 ForRangeInfo
.LoopVar
.get(), ForRangeInfo
.ColonLoc
, CorrectedRange
.get(),
2261 T
.getCloseLocation(), Sema::BFRK_Build
);
2263 // Similarly, we need to do the semantic analysis for a for-range
2264 // statement immediately in order to close over temporaries correctly.
2265 } else if (ForEach
) {
2266 ForEachStmt
= Actions
.ActOnObjCForCollectionStmt(ForLoc
,
2269 T
.getCloseLocation());
2271 // In OpenMP loop region loop control variable must be captured and be
2272 // private. Perform analysis of first part (if any).
2273 if (getLangOpts().OpenMP
&& FirstPart
.isUsable()) {
2274 Actions
.ActOnOpenMPLoopInitialization(ForLoc
, FirstPart
.get());
2278 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2279 // there is no compound stmt. C90 does not have this clause. We only do this
2280 // if the body isn't a compound statement to avoid push/pop in common cases.
2283 // The substatement in an iteration-statement implicitly defines a local scope
2284 // which is entered and exited each time through the loop.
2286 // See comments in ParseIfStatement for why we create a scope for
2287 // for-init-statement/condition and a new scope for substatement in C++.
2289 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXXorObjC
,
2290 Tok
.is(tok::l_brace
));
2292 // The body of the for loop has the same local mangling number as the
2293 // for-init-statement.
2294 // It will only be incremented if the body contains other things that would
2295 // normally increment the mangling number (like a compound statement).
2297 getCurScope()->decrementMSManglingNumber();
2299 MisleadingIndentationChecker
MIChecker(*this, MSK_for
, ForLoc
);
2301 // Read the body statement.
2302 StmtResult
Body(ParseStatement(TrailingElseLoc
));
2304 if (Body
.isUsable())
2307 // Pop the body scope if needed.
2310 // Leave the for-scope.
2313 if (Body
.isInvalid())
2317 return Actions
.FinishObjCForCollectionStmt(ForEachStmt
.get(),
2320 if (ForRangeInfo
.ParsedForRangeDecl())
2321 return Actions
.FinishCXXForRangeStmt(ForRangeStmt
.get(), Body
.get());
2323 return Actions
.ActOnForStmt(ForLoc
, T
.getOpenLocation(), FirstPart
.get(),
2324 SecondPart
, ThirdPart
, T
.getCloseLocation(),
2328 /// ParseGotoStatement
2330 /// 'goto' identifier ';'
2331 /// [GNU] 'goto' '*' expression ';'
2333 /// Note: this lets the caller parse the end ';'.
2335 StmtResult
Parser::ParseGotoStatement() {
2336 assert(Tok
.is(tok::kw_goto
) && "Not a goto stmt!");
2337 SourceLocation GotoLoc
= ConsumeToken(); // eat the 'goto'.
2340 if (Tok
.is(tok::identifier
)) {
2341 LabelDecl
*LD
= Actions
.LookupOrCreateLabel(Tok
.getIdentifierInfo(),
2343 Res
= Actions
.ActOnGotoStmt(GotoLoc
, Tok
.getLocation(), LD
);
2345 } else if (Tok
.is(tok::star
)) {
2346 // GNU indirect goto extension.
2347 Diag(Tok
, diag::ext_gnu_indirect_goto
);
2348 SourceLocation StarLoc
= ConsumeToken();
2349 ExprResult
R(ParseExpression());
2350 if (R
.isInvalid()) { // Skip to the semicolon, but don't consume it.
2351 SkipUntil(tok::semi
, StopBeforeMatch
);
2354 Res
= Actions
.ActOnIndirectGotoStmt(GotoLoc
, StarLoc
, R
.get());
2356 Diag(Tok
, diag::err_expected
) << tok::identifier
;
2363 /// ParseContinueStatement
2367 /// Note: this lets the caller parse the end ';'.
2369 StmtResult
Parser::ParseContinueStatement() {
2370 SourceLocation ContinueLoc
= ConsumeToken(); // eat the 'continue'.
2371 return Actions
.ActOnContinueStmt(ContinueLoc
, getCurScope());
2374 /// ParseBreakStatement
2378 /// Note: this lets the caller parse the end ';'.
2380 StmtResult
Parser::ParseBreakStatement() {
2381 SourceLocation BreakLoc
= ConsumeToken(); // eat the 'break'.
2382 return Actions
.ActOnBreakStmt(BreakLoc
, getCurScope());
2385 /// ParseReturnStatement
2387 /// 'return' expression[opt] ';'
2388 /// 'return' braced-init-list ';'
2389 /// 'co_return' expression[opt] ';'
2390 /// 'co_return' braced-init-list ';'
2391 StmtResult
Parser::ParseReturnStatement() {
2392 assert((Tok
.is(tok::kw_return
) || Tok
.is(tok::kw_co_return
)) &&
2393 "Not a return stmt!");
2394 bool IsCoreturn
= Tok
.is(tok::kw_co_return
);
2395 SourceLocation ReturnLoc
= ConsumeToken(); // eat the 'return'.
2398 if (Tok
.isNot(tok::semi
)) {
2400 PreferredType
.enterReturn(Actions
, Tok
.getLocation());
2401 // FIXME: Code completion for co_return.
2402 if (Tok
.is(tok::code_completion
) && !IsCoreturn
) {
2404 Actions
.CodeCompleteExpression(getCurScope(),
2405 PreferredType
.get(Tok
.getLocation()));
2409 if (Tok
.is(tok::l_brace
) && getLangOpts().CPlusPlus
) {
2410 R
= ParseInitializer();
2412 Diag(R
.get()->getBeginLoc(),
2413 getLangOpts().CPlusPlus11
2414 ? diag::warn_cxx98_compat_generalized_initializer_lists
2415 : diag::ext_generalized_initializer_lists
)
2416 << R
.get()->getSourceRange();
2418 R
= ParseExpression();
2419 if (R
.isInvalid()) {
2420 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
2425 return Actions
.ActOnCoreturnStmt(getCurScope(), ReturnLoc
, R
.get());
2426 return Actions
.ActOnReturnStmt(ReturnLoc
, R
.get(), getCurScope());
2429 StmtResult
Parser::ParsePragmaLoopHint(StmtVector
&Stmts
,
2430 ParsedStmtContext StmtCtx
,
2431 SourceLocation
*TrailingElseLoc
,
2432 ParsedAttributes
&Attrs
) {
2433 // Create temporary attribute list.
2434 ParsedAttributes
TempAttrs(AttrFactory
);
2436 SourceLocation StartLoc
= Tok
.getLocation();
2438 // Get loop hints and consume annotated token.
2439 while (Tok
.is(tok::annot_pragma_loop_hint
)) {
2441 if (!HandlePragmaLoopHint(Hint
))
2444 ArgsUnion ArgHints
[] = {Hint
.PragmaNameLoc
, Hint
.OptionLoc
, Hint
.StateLoc
,
2445 ArgsUnion(Hint
.ValueExpr
)};
2446 TempAttrs
.addNew(Hint
.PragmaNameLoc
->Ident
, Hint
.Range
, nullptr,
2447 Hint
.PragmaNameLoc
->Loc
, ArgHints
, 4,
2448 ParsedAttr::Form::Pragma());
2451 // Get the next statement.
2452 MaybeParseCXX11Attributes(Attrs
);
2454 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
2455 StmtResult S
= ParseStatementOrDeclarationAfterAttributes(
2456 Stmts
, StmtCtx
, TrailingElseLoc
, Attrs
, EmptyDeclSpecAttrs
);
2458 Attrs
.takeAllFrom(TempAttrs
);
2460 // Start of attribute range may already be set for some invalid input.
2462 if (Attrs
.Range
.getBegin().isInvalid())
2463 Attrs
.Range
.setBegin(StartLoc
);
2468 Decl
*Parser::ParseFunctionStatementBody(Decl
*Decl
, ParseScope
&BodyScope
) {
2469 assert(Tok
.is(tok::l_brace
));
2470 SourceLocation LBraceLoc
= Tok
.getLocation();
2472 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, Decl
, LBraceLoc
,
2473 "parsing function body");
2475 // Save and reset current vtordisp stack if we have entered a C++ method body.
2477 getLangOpts().CPlusPlus
&& Decl
&& isa
<CXXMethodDecl
>(Decl
);
2478 Sema::PragmaStackSentinelRAII
2479 PragmaStackSentinel(Actions
, "InternalPragmaState", IsCXXMethod
);
2481 // Do not enter a scope for the brace, as the arguments are in the same scope
2482 // (the function body) as the body itself. Instead, just read the statement
2483 // list and put it into a CompoundStmt for safe keeping.
2484 StmtResult
FnBody(ParseCompoundStatementBody());
2486 // If the function body could not be parsed, make a bogus compoundstmt.
2487 if (FnBody
.isInvalid()) {
2488 Sema::CompoundScopeRAII
CompoundScope(Actions
);
2490 Actions
.ActOnCompoundStmt(LBraceLoc
, LBraceLoc
, std::nullopt
, false);
2494 return Actions
.ActOnFinishFunctionBody(Decl
, FnBody
.get());
2497 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
2499 /// function-try-block:
2500 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2502 Decl
*Parser::ParseFunctionTryBlock(Decl
*Decl
, ParseScope
&BodyScope
) {
2503 assert(Tok
.is(tok::kw_try
) && "Expected 'try'");
2504 SourceLocation TryLoc
= ConsumeToken();
2506 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, Decl
, TryLoc
,
2507 "parsing function try block");
2509 // Constructor initializer list?
2510 if (Tok
.is(tok::colon
))
2511 ParseConstructorInitializer(Decl
);
2513 Actions
.ActOnDefaultCtorInitializers(Decl
);
2515 // Save and reset current vtordisp stack if we have entered a C++ method body.
2517 getLangOpts().CPlusPlus
&& Decl
&& isa
<CXXMethodDecl
>(Decl
);
2518 Sema::PragmaStackSentinelRAII
2519 PragmaStackSentinel(Actions
, "InternalPragmaState", IsCXXMethod
);
2521 SourceLocation LBraceLoc
= Tok
.getLocation();
2522 StmtResult
FnBody(ParseCXXTryBlockCommon(TryLoc
, /*FnTry*/true));
2523 // If we failed to parse the try-catch, we just give the function an empty
2524 // compound statement as the body.
2525 if (FnBody
.isInvalid()) {
2526 Sema::CompoundScopeRAII
CompoundScope(Actions
);
2528 Actions
.ActOnCompoundStmt(LBraceLoc
, LBraceLoc
, std::nullopt
, false);
2532 return Actions
.ActOnFinishFunctionBody(Decl
, FnBody
.get());
2535 bool Parser::trySkippingFunctionBody() {
2536 assert(SkipFunctionBodies
&&
2537 "Should only be called when SkipFunctionBodies is enabled");
2538 if (!PP
.isCodeCompletionEnabled()) {
2543 // We're in code-completion mode. Skip parsing for all function bodies unless
2544 // the body contains the code-completion point.
2545 TentativeParsingAction
PA(*this);
2546 bool IsTryCatch
= Tok
.is(tok::kw_try
);
2548 bool ErrorInPrologue
= ConsumeAndStoreFunctionPrologue(Toks
);
2549 if (llvm::any_of(Toks
, [](const Token
&Tok
) {
2550 return Tok
.is(tok::code_completion
);
2555 if (ErrorInPrologue
) {
2557 SkipMalformedDecl();
2560 if (!SkipUntil(tok::r_brace
, StopAtCodeCompletion
)) {
2564 while (IsTryCatch
&& Tok
.is(tok::kw_catch
)) {
2565 if (!SkipUntil(tok::l_brace
, StopAtCodeCompletion
) ||
2566 !SkipUntil(tok::r_brace
, StopAtCodeCompletion
)) {
2575 /// ParseCXXTryBlock - Parse a C++ try-block.
2578 /// 'try' compound-statement handler-seq
2580 StmtResult
Parser::ParseCXXTryBlock() {
2581 assert(Tok
.is(tok::kw_try
) && "Expected 'try'");
2583 SourceLocation TryLoc
= ConsumeToken();
2584 return ParseCXXTryBlockCommon(TryLoc
);
2587 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2588 /// function-try-block.
2591 /// 'try' compound-statement handler-seq
2593 /// function-try-block:
2594 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2597 /// handler handler-seq[opt]
2599 /// [Borland] try-block:
2600 /// 'try' compound-statement seh-except-block
2601 /// 'try' compound-statement seh-finally-block
2603 StmtResult
Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc
, bool FnTry
) {
2604 if (Tok
.isNot(tok::l_brace
))
2605 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
2607 StmtResult
TryBlock(ParseCompoundStatement(
2608 /*isStmtExpr=*/false, Scope::DeclScope
| Scope::TryScope
|
2609 Scope::CompoundStmtScope
|
2610 (FnTry
? Scope::FnTryCatchScope
: 0)));
2611 if (TryBlock
.isInvalid())
2614 // Borland allows SEH-handlers with 'try'
2616 if ((Tok
.is(tok::identifier
) &&
2617 Tok
.getIdentifierInfo() == getSEHExceptKeyword()) ||
2618 Tok
.is(tok::kw___finally
)) {
2619 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2621 if(Tok
.getIdentifierInfo() == getSEHExceptKeyword()) {
2622 SourceLocation Loc
= ConsumeToken();
2623 Handler
= ParseSEHExceptBlock(Loc
);
2626 SourceLocation Loc
= ConsumeToken();
2627 Handler
= ParseSEHFinallyBlock(Loc
);
2629 if(Handler
.isInvalid())
2632 return Actions
.ActOnSEHTryBlock(true /* IsCXXTry */,
2638 StmtVector Handlers
;
2640 // C++11 attributes can't appear here, despite this context seeming
2642 DiagnoseAndSkipCXX11Attributes();
2644 if (Tok
.isNot(tok::kw_catch
))
2645 return StmtError(Diag(Tok
, diag::err_expected_catch
));
2646 while (Tok
.is(tok::kw_catch
)) {
2647 StmtResult
Handler(ParseCXXCatchBlock(FnTry
));
2648 if (!Handler
.isInvalid())
2649 Handlers
.push_back(Handler
.get());
2651 // Don't bother creating the full statement if we don't have any usable
2653 if (Handlers
.empty())
2656 return Actions
.ActOnCXXTryBlock(TryLoc
, TryBlock
.get(), Handlers
);
2660 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2663 /// 'catch' '(' exception-declaration ')' compound-statement
2665 /// exception-declaration:
2666 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2667 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2670 StmtResult
Parser::ParseCXXCatchBlock(bool FnCatch
) {
2671 assert(Tok
.is(tok::kw_catch
) && "Expected 'catch'");
2673 SourceLocation CatchLoc
= ConsumeToken();
2675 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2676 if (T
.expectAndConsume())
2680 // The name in a catch exception-declaration is local to the handler and
2681 // shall not be redeclared in the outermost block of the handler.
2682 ParseScope
CatchScope(this, Scope::DeclScope
| Scope::ControlScope
|
2684 (FnCatch
? Scope::FnTryCatchScope
: 0));
2686 // exception-declaration is equivalent to '...' or a parameter-declaration
2687 // without default arguments.
2688 Decl
*ExceptionDecl
= nullptr;
2689 if (Tok
.isNot(tok::ellipsis
)) {
2690 ParsedAttributes
Attributes(AttrFactory
);
2691 MaybeParseCXX11Attributes(Attributes
);
2693 DeclSpec
DS(AttrFactory
);
2695 if (ParseCXXTypeSpecifierSeq(DS
))
2698 Declarator
ExDecl(DS
, Attributes
, DeclaratorContext::CXXCatch
);
2699 ParseDeclarator(ExDecl
);
2700 ExceptionDecl
= Actions
.ActOnExceptionDeclarator(getCurScope(), ExDecl
);
2705 if (T
.getCloseLocation().isInvalid())
2708 if (Tok
.isNot(tok::l_brace
))
2709 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
2711 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2712 StmtResult
Block(ParseCompoundStatement());
2713 if (Block
.isInvalid())
2716 return Actions
.ActOnCXXCatchBlock(CatchLoc
, ExceptionDecl
, Block
.get());
2719 void Parser::ParseMicrosoftIfExistsStatement(StmtVector
&Stmts
) {
2720 IfExistsCondition Result
;
2721 if (ParseMicrosoftIfExistsCondition(Result
))
2724 // Handle dependent statements by parsing the braces as a compound statement.
2725 // This is not the same behavior as Visual C++, which don't treat this as a
2726 // compound statement, but for Clang's type checking we can't have anything
2727 // inside these braces escaping to the surrounding code.
2728 if (Result
.Behavior
== IEB_Dependent
) {
2729 if (!Tok
.is(tok::l_brace
)) {
2730 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
2734 StmtResult Compound
= ParseCompoundStatement();
2735 if (Compound
.isInvalid())
2738 StmtResult DepResult
= Actions
.ActOnMSDependentExistsStmt(Result
.KeywordLoc
,
2743 if (DepResult
.isUsable())
2744 Stmts
.push_back(DepResult
.get());
2748 BalancedDelimiterTracker
Braces(*this, tok::l_brace
);
2749 if (Braces
.consumeOpen()) {
2750 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
2754 switch (Result
.Behavior
) {
2756 // Parse the statements below.
2760 llvm_unreachable("Dependent case handled above");
2767 // Condition is true, parse the statements.
2768 while (Tok
.isNot(tok::r_brace
)) {
2770 ParseStatementOrDeclaration(Stmts
, ParsedStmtContext::Compound
);
2772 Stmts
.push_back(R
.get());
2774 Braces
.consumeClose();