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/TokenKinds.h"
18 #include "clang/Parse/LoopHint.h"
19 #include "clang/Parse/Parser.h"
20 #include "clang/Parse/RAIIObjectsForParser.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/EnterExpressionEvaluationContext.h"
23 #include "clang/Sema/Scope.h"
24 #include "clang/Sema/TypoCorrection.h"
25 #include "llvm/ADT/STLExtras.h"
28 using namespace clang
;
30 //===----------------------------------------------------------------------===//
31 // C99 6.8: Statements and Blocks.
32 //===----------------------------------------------------------------------===//
34 /// Parse a standalone statement (for instance, as the body of an 'if',
35 /// 'while', or 'for').
36 StmtResult
Parser::ParseStatement(SourceLocation
*TrailingElseLoc
,
37 ParsedStmtContext StmtCtx
) {
40 // We may get back a null statement if we found a #pragma. Keep going until
41 // we get an actual statement.
44 Res
= ParseStatementOrDeclaration(Stmts
, StmtCtx
, TrailingElseLoc
);
45 } while (!Res
.isInvalid() && !Res
.get());
50 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
51 /// StatementOrDeclaration:
57 /// compound-statement
58 /// expression-statement
59 /// selection-statement
60 /// iteration-statement
62 /// [C++] declaration-statement
64 /// [MS] seh-try-block
65 /// [OBC] objc-throw-statement
66 /// [OBC] objc-try-catch-statement
67 /// [OBC] objc-synchronized-statement
68 /// [GNU] asm-statement
69 /// [OMP] openmp-construct [TODO]
71 /// labeled-statement:
72 /// identifier ':' statement
73 /// 'case' constant-expression ':' statement
74 /// 'default' ':' statement
76 /// selection-statement:
80 /// iteration-statement:
85 /// expression-statement:
86 /// expression[opt] ';'
89 /// 'goto' identifier ';'
92 /// 'return' expression[opt] ';'
93 /// [GNU] 'goto' '*' expression ';'
95 /// [OBC] objc-throw-statement:
96 /// [OBC] '@' 'throw' expression ';'
97 /// [OBC] '@' 'throw' ';'
100 Parser::ParseStatementOrDeclaration(StmtVector
&Stmts
,
101 ParsedStmtContext StmtCtx
,
102 SourceLocation
*TrailingElseLoc
) {
104 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
106 // Because we're parsing either a statement or a declaration, the order of
107 // attribute parsing is important. [[]] attributes at the start of a
108 // statement are different from [[]] attributes that follow an __attribute__
109 // at the start of the statement. Thus, we're not using MaybeParseAttributes
110 // here because we don't want to allow arbitrary orderings.
111 ParsedAttributes
CXX11Attrs(AttrFactory
);
112 MaybeParseCXX11Attributes(CXX11Attrs
, /*MightBeObjCMessageSend*/ true);
113 ParsedAttributes
GNUAttrs(AttrFactory
);
114 if (getLangOpts().OpenCL
)
115 MaybeParseGNUAttributes(GNUAttrs
);
117 StmtResult Res
= ParseStatementOrDeclarationAfterAttributes(
118 Stmts
, StmtCtx
, TrailingElseLoc
, CXX11Attrs
, GNUAttrs
);
119 MaybeDestroyTemplateIds();
121 // Attributes that are left should all go on the statement, so concatenate the
123 ParsedAttributes
Attrs(AttrFactory
);
124 takeAndConcatenateAttrs(CXX11Attrs
, GNUAttrs
, Attrs
);
126 assert((Attrs
.empty() || Res
.isInvalid() || Res
.isUsable()) &&
127 "attributes on empty statement");
129 if (Attrs
.empty() || Res
.isInvalid())
132 return Actions
.ActOnAttributedStmt(Attrs
, Res
.get());
136 class StatementFilterCCC final
: public CorrectionCandidateCallback
{
138 StatementFilterCCC(Token nextTok
) : NextToken(nextTok
) {
139 WantTypeSpecifiers
= nextTok
.isOneOf(tok::l_paren
, tok::less
, tok::l_square
,
140 tok::identifier
, tok::star
, tok::amp
);
141 WantExpressionKeywords
=
142 nextTok
.isOneOf(tok::l_paren
, tok::identifier
, tok::arrow
, tok::period
);
143 WantRemainingKeywords
=
144 nextTok
.isOneOf(tok::l_paren
, tok::semi
, tok::identifier
, tok::l_brace
);
145 WantCXXNamedCasts
= false;
148 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
149 if (FieldDecl
*FD
= candidate
.getCorrectionDeclAs
<FieldDecl
>())
150 return !candidate
.getCorrectionSpecifier() || isa
<ObjCIvarDecl
>(FD
);
151 if (NextToken
.is(tok::equal
))
152 return candidate
.getCorrectionDeclAs
<VarDecl
>();
153 if (NextToken
.is(tok::period
) &&
154 candidate
.getCorrectionDeclAs
<NamespaceDecl
>())
156 return CorrectionCandidateCallback::ValidateCandidate(candidate
);
159 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
160 return std::make_unique
<StatementFilterCCC
>(*this);
168 StmtResult
Parser::ParseStatementOrDeclarationAfterAttributes(
169 StmtVector
&Stmts
, ParsedStmtContext StmtCtx
,
170 SourceLocation
*TrailingElseLoc
, ParsedAttributes
&CXX11Attrs
,
171 ParsedAttributes
&GNUAttrs
) {
172 const char *SemiError
= nullptr;
174 SourceLocation GNUAttributeLoc
;
176 // Cases in this switch statement should fall through if the parser expects
177 // the token to end in a semicolon (in which case SemiError should be set),
178 // or they directly 'return;' if not.
180 tok::TokenKind Kind
= Tok
.getKind();
181 SourceLocation AtLoc
;
183 case tok::at
: // May be a @try or @throw statement
185 AtLoc
= ConsumeToken(); // consume @
186 return ParseObjCAtStatement(AtLoc
, StmtCtx
);
189 case tok::code_completion
:
191 Actions
.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement
);
194 case tok::identifier
:
196 Token Next
= NextToken();
197 if (Next
.is(tok::colon
)) { // C99 6.8.1: labeled-statement
198 // Both C++11 and GNU attributes preceding the label appertain to the
199 // label, so put them in a single list to pass on to
200 // ParseLabeledStatement().
201 ParsedAttributes
Attrs(AttrFactory
);
202 takeAndConcatenateAttrs(CXX11Attrs
, GNUAttrs
, Attrs
);
204 // identifier ':' statement
205 return ParseLabeledStatement(Attrs
, StmtCtx
);
208 // Look up the identifier, and typo-correct it to a keyword if it's not
210 if (Next
.isNot(tok::coloncolon
)) {
211 // Try to limit which sets of keywords should be included in typo
212 // correction based on what the next token is.
213 StatementFilterCCC
CCC(Next
);
214 if (TryAnnotateName(&CCC
) == ANK_Error
) {
215 // Handle errors here by skipping up to the next semicolon or '}', and
216 // eat the semicolon if that's what stopped us.
217 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
218 if (Tok
.is(tok::semi
))
223 // If the identifier was typo-corrected, try again.
224 if (Tok
.isNot(tok::identifier
))
233 bool HaveAttrs
= !CXX11Attrs
.empty() || !GNUAttrs
.empty();
234 auto IsStmtAttr
= [](ParsedAttr
&Attr
) { return Attr
.isStmtAttr(); };
235 bool AllAttrsAreStmtAttrs
= llvm::all_of(CXX11Attrs
, IsStmtAttr
) &&
236 llvm::all_of(GNUAttrs
, IsStmtAttr
);
237 if ((getLangOpts().CPlusPlus
|| getLangOpts().MicrosoftExt
||
238 (StmtCtx
& ParsedStmtContext::AllowDeclarationsInC
) !=
239 ParsedStmtContext()) &&
240 ((GNUAttributeLoc
.isValid() && !(HaveAttrs
&& AllAttrsAreStmtAttrs
)) ||
241 isDeclarationStatement())) {
242 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
244 if (GNUAttributeLoc
.isValid()) {
245 DeclStart
= GNUAttributeLoc
;
246 Decl
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
, CXX11Attrs
,
247 GNUAttrs
, &GNUAttributeLoc
);
249 Decl
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
, CXX11Attrs
,
252 if (CXX11Attrs
.Range
.getBegin().isValid()) {
253 // The caller must guarantee that the CXX11Attrs appear before the
254 // GNUAttrs, and we rely on that here.
255 assert(GNUAttrs
.Range
.getBegin().isInvalid() ||
256 GNUAttrs
.Range
.getBegin() > CXX11Attrs
.Range
.getBegin());
257 DeclStart
= CXX11Attrs
.Range
.getBegin();
258 } else if (GNUAttrs
.Range
.getBegin().isValid())
259 DeclStart
= GNUAttrs
.Range
.getBegin();
260 return Actions
.ActOnDeclStmt(Decl
, DeclStart
, DeclEnd
);
263 if (Tok
.is(tok::r_brace
)) {
264 Diag(Tok
, diag::err_expected_statement
);
268 switch (Tok
.getKind()) {
269 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
270 #include "clang/Basic/TransformTypeTraits.def"
271 if (NextToken().is(tok::less
)) {
272 Tok
.setKind(tok::identifier
);
273 Diag(Tok
, diag::ext_keyword_as_ident
)
274 << Tok
.getIdentifierInfo()->getName() << 0;
275 goto ParseIdentifier
;
279 return ParseExprStatement(StmtCtx
);
283 case tok::kw___attribute
: {
284 GNUAttributeLoc
= Tok
.getLocation();
285 ParseGNUAttributes(GNUAttrs
);
289 case tok::kw_case
: // C99 6.8.1: labeled-statement
290 return ParseCaseStatement(StmtCtx
);
291 case tok::kw_default
: // C99 6.8.1: labeled-statement
292 return ParseDefaultStatement(StmtCtx
);
294 case tok::l_brace
: // C99 6.8.2: compound-statement
295 return ParseCompoundStatement();
296 case tok::semi
: { // C99 6.8.3p3: expression[opt] ';'
297 bool HasLeadingEmptyMacro
= Tok
.hasLeadingEmptyMacro();
298 return Actions
.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro
);
301 case tok::kw_if
: // C99 6.8.4.1: if-statement
302 return ParseIfStatement(TrailingElseLoc
);
303 case tok::kw_switch
: // C99 6.8.4.2: switch-statement
304 return ParseSwitchStatement(TrailingElseLoc
);
306 case tok::kw_while
: // C99 6.8.5.1: while-statement
307 return ParseWhileStatement(TrailingElseLoc
);
308 case tok::kw_do
: // C99 6.8.5.2: do-statement
309 Res
= ParseDoStatement();
310 SemiError
= "do/while";
312 case tok::kw_for
: // C99 6.8.5.3: for-statement
313 return ParseForStatement(TrailingElseLoc
);
315 case tok::kw_goto
: // C99 6.8.6.1: goto-statement
316 Res
= ParseGotoStatement();
319 case tok::kw_continue
: // C99 6.8.6.2: continue-statement
320 Res
= ParseContinueStatement();
321 SemiError
= "continue";
323 case tok::kw_break
: // C99 6.8.6.3: break-statement
324 Res
= ParseBreakStatement();
327 case tok::kw_return
: // C99 6.8.6.4: return-statement
328 Res
= ParseReturnStatement();
329 SemiError
= "return";
331 case tok::kw_co_return
: // C++ Coroutines: co_return statement
332 Res
= ParseReturnStatement();
333 SemiError
= "co_return";
337 for (const ParsedAttr
&AL
: CXX11Attrs
)
338 // Could be relaxed if asm-related regular keyword attributes are
340 (AL
.isRegularKeywordAttribute()
341 ? Diag(AL
.getRange().getBegin(), diag::err_keyword_not_allowed
)
342 : Diag(AL
.getRange().getBegin(), diag::warn_attribute_ignored
))
344 // Prevent these from being interpreted as statement attributes later on.
346 ProhibitAttributes(GNUAttrs
);
348 Res
= ParseAsmStatement(msAsm
);
349 if (msAsm
) return Res
;
354 case tok::kw___if_exists
:
355 case tok::kw___if_not_exists
:
356 ProhibitAttributes(CXX11Attrs
);
357 ProhibitAttributes(GNUAttrs
);
358 ParseMicrosoftIfExistsStatement(Stmts
);
359 // An __if_exists block is like a compound statement, but it doesn't create
363 case tok::kw_try
: // C++ 15: try-block
364 return ParseCXXTryBlock();
367 ProhibitAttributes(CXX11Attrs
);
368 ProhibitAttributes(GNUAttrs
);
369 return ParseSEHTryBlock();
371 case tok::kw___leave
:
372 Res
= ParseSEHLeaveStatement();
373 SemiError
= "__leave";
376 case tok::annot_pragma_vis
:
377 ProhibitAttributes(CXX11Attrs
);
378 ProhibitAttributes(GNUAttrs
);
379 HandlePragmaVisibility();
382 case tok::annot_pragma_pack
:
383 ProhibitAttributes(CXX11Attrs
);
384 ProhibitAttributes(GNUAttrs
);
388 case tok::annot_pragma_msstruct
:
389 ProhibitAttributes(CXX11Attrs
);
390 ProhibitAttributes(GNUAttrs
);
391 HandlePragmaMSStruct();
394 case tok::annot_pragma_align
:
395 ProhibitAttributes(CXX11Attrs
);
396 ProhibitAttributes(GNUAttrs
);
400 case tok::annot_pragma_weak
:
401 ProhibitAttributes(CXX11Attrs
);
402 ProhibitAttributes(GNUAttrs
);
406 case tok::annot_pragma_weakalias
:
407 ProhibitAttributes(CXX11Attrs
);
408 ProhibitAttributes(GNUAttrs
);
409 HandlePragmaWeakAlias();
412 case tok::annot_pragma_redefine_extname
:
413 ProhibitAttributes(CXX11Attrs
);
414 ProhibitAttributes(GNUAttrs
);
415 HandlePragmaRedefineExtname();
418 case tok::annot_pragma_fp_contract
:
419 ProhibitAttributes(CXX11Attrs
);
420 ProhibitAttributes(GNUAttrs
);
421 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "fp_contract";
422 ConsumeAnnotationToken();
425 case tok::annot_pragma_fp
:
426 ProhibitAttributes(CXX11Attrs
);
427 ProhibitAttributes(GNUAttrs
);
428 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "clang fp";
429 ConsumeAnnotationToken();
432 case tok::annot_pragma_fenv_access
:
433 case tok::annot_pragma_fenv_access_ms
:
434 ProhibitAttributes(CXX11Attrs
);
435 ProhibitAttributes(GNUAttrs
);
436 Diag(Tok
, diag::err_pragma_file_or_compound_scope
)
437 << (Kind
== tok::annot_pragma_fenv_access
? "STDC FENV_ACCESS"
439 ConsumeAnnotationToken();
442 case tok::annot_pragma_fenv_round
:
443 ProhibitAttributes(CXX11Attrs
);
444 ProhibitAttributes(GNUAttrs
);
445 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "STDC FENV_ROUND";
446 ConsumeAnnotationToken();
449 case tok::annot_pragma_float_control
:
450 ProhibitAttributes(CXX11Attrs
);
451 ProhibitAttributes(GNUAttrs
);
452 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "float_control";
453 ConsumeAnnotationToken();
456 case tok::annot_pragma_opencl_extension
:
457 ProhibitAttributes(CXX11Attrs
);
458 ProhibitAttributes(GNUAttrs
);
459 HandlePragmaOpenCLExtension();
462 case tok::annot_pragma_captured
:
463 ProhibitAttributes(CXX11Attrs
);
464 ProhibitAttributes(GNUAttrs
);
465 return HandlePragmaCaptured();
467 case tok::annot_pragma_openmp
:
468 // Prohibit attributes that are not OpenMP attributes, but only before
469 // processing a #pragma omp clause.
470 ProhibitAttributes(CXX11Attrs
);
471 ProhibitAttributes(GNUAttrs
);
473 case tok::annot_attr_openmp
:
474 // Do not prohibit attributes if they were OpenMP attributes.
475 return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx
);
477 case tok::annot_pragma_ms_pointers_to_members
:
478 ProhibitAttributes(CXX11Attrs
);
479 ProhibitAttributes(GNUAttrs
);
480 HandlePragmaMSPointersToMembers();
483 case tok::annot_pragma_ms_pragma
:
484 ProhibitAttributes(CXX11Attrs
);
485 ProhibitAttributes(GNUAttrs
);
486 HandlePragmaMSPragma();
489 case tok::annot_pragma_ms_vtordisp
:
490 ProhibitAttributes(CXX11Attrs
);
491 ProhibitAttributes(GNUAttrs
);
492 HandlePragmaMSVtorDisp();
495 case tok::annot_pragma_loop_hint
:
496 ProhibitAttributes(CXX11Attrs
);
497 ProhibitAttributes(GNUAttrs
);
498 return ParsePragmaLoopHint(Stmts
, StmtCtx
, TrailingElseLoc
, CXX11Attrs
);
500 case tok::annot_pragma_dump
:
504 case tok::annot_pragma_attribute
:
505 HandlePragmaAttribute();
509 // If we reached this code, the statement must end in a semicolon.
510 if (!TryConsumeToken(tok::semi
) && !Res
.isInvalid()) {
511 // If the result was valid, then we do want to diagnose this. Use
512 // ExpectAndConsume to emit the diagnostic, even though we know it won't
514 ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_stmt
, SemiError
);
515 // Skip until we see a } or ;, but don't eat it.
516 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
522 /// Parse an expression statement.
523 StmtResult
Parser::ParseExprStatement(ParsedStmtContext StmtCtx
) {
524 // If a case keyword is missing, this is where it should be inserted.
525 Token OldToken
= Tok
;
527 ExprStatementTokLoc
= Tok
.getLocation();
529 // expression[opt] ';'
530 ExprResult
Expr(ParseExpression());
531 if (Expr
.isInvalid()) {
532 // If the expression is invalid, skip ahead to the next semicolon or '}'.
533 // Not doing this opens us up to the possibility of infinite loops if
534 // ParseExpression does not consume any tokens.
535 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
536 if (Tok
.is(tok::semi
))
538 return Actions
.ActOnExprStmtError();
541 if (Tok
.is(tok::colon
) && getCurScope()->isSwitchScope() &&
542 Actions
.CheckCaseExpression(Expr
.get())) {
543 // If a constant expression is followed by a colon inside a switch block,
544 // suggest a missing case keyword.
545 Diag(OldToken
, diag::err_expected_case_before_expression
)
546 << FixItHint::CreateInsertion(OldToken
.getLocation(), "case ");
548 // Recover parsing as a case statement.
549 return ParseCaseStatement(StmtCtx
, /*MissingCase=*/true, Expr
);
552 Token
*CurTok
= nullptr;
553 // If the semicolon is missing at the end of REPL input, consider if
554 // we want to do value printing. Note this is only enabled in C++ mode
555 // since part of the implementation requires C++ language features.
556 // Note we shouldn't eat the token since the callback needs it.
557 if (Tok
.is(tok::annot_repl_input_end
) && Actions
.getLangOpts().CPlusPlus
)
560 // Otherwise, eat the semicolon.
561 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr
);
563 StmtResult R
= handleExprStmt(Expr
, StmtCtx
);
564 if (CurTok
&& !R
.isInvalid())
565 CurTok
->setAnnotationValue(R
.get());
570 /// ParseSEHTryBlockCommon
573 /// '__try' compound-statement seh-handler
577 /// seh-finally-block
579 StmtResult
Parser::ParseSEHTryBlock() {
580 assert(Tok
.is(tok::kw___try
) && "Expected '__try'");
581 SourceLocation TryLoc
= ConsumeToken();
583 if (Tok
.isNot(tok::l_brace
))
584 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
586 StmtResult
TryBlock(ParseCompoundStatement(
587 /*isStmtExpr=*/false,
588 Scope::DeclScope
| Scope::CompoundStmtScope
| Scope::SEHTryScope
));
589 if (TryBlock
.isInvalid())
593 if (Tok
.is(tok::identifier
) &&
594 Tok
.getIdentifierInfo() == getSEHExceptKeyword()) {
595 SourceLocation Loc
= ConsumeToken();
596 Handler
= ParseSEHExceptBlock(Loc
);
597 } else if (Tok
.is(tok::kw___finally
)) {
598 SourceLocation Loc
= ConsumeToken();
599 Handler
= ParseSEHFinallyBlock(Loc
);
601 return StmtError(Diag(Tok
, diag::err_seh_expected_handler
));
604 if(Handler
.isInvalid())
607 return Actions
.ActOnSEHTryBlock(false /* IsCXXTry */,
613 /// ParseSEHExceptBlock - Handle __except
615 /// seh-except-block:
616 /// '__except' '(' seh-filter-expression ')' compound-statement
618 StmtResult
Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc
) {
619 PoisonIdentifierRAIIObject
raii(Ident__exception_code
, false),
620 raii2(Ident___exception_code
, false),
621 raii3(Ident_GetExceptionCode
, false);
623 if (ExpectAndConsume(tok::l_paren
))
626 ParseScope
ExpectScope(this, Scope::DeclScope
| Scope::ControlScope
|
627 Scope::SEHExceptScope
);
629 if (getLangOpts().Borland
) {
630 Ident__exception_info
->setIsPoisoned(false);
631 Ident___exception_info
->setIsPoisoned(false);
632 Ident_GetExceptionInfo
->setIsPoisoned(false);
635 ExprResult FilterExpr
;
637 ParseScopeFlags
FilterScope(this, getCurScope()->getFlags() |
638 Scope::SEHFilterScope
);
639 FilterExpr
= Actions
.CorrectDelayedTyposInExpr(ParseExpression());
642 if (getLangOpts().Borland
) {
643 Ident__exception_info
->setIsPoisoned(true);
644 Ident___exception_info
->setIsPoisoned(true);
645 Ident_GetExceptionInfo
->setIsPoisoned(true);
648 if(FilterExpr
.isInvalid())
651 if (ExpectAndConsume(tok::r_paren
))
654 if (Tok
.isNot(tok::l_brace
))
655 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
657 StmtResult
Block(ParseCompoundStatement());
659 if(Block
.isInvalid())
662 return Actions
.ActOnSEHExceptBlock(ExceptLoc
, FilterExpr
.get(), Block
.get());
665 /// ParseSEHFinallyBlock - Handle __finally
667 /// seh-finally-block:
668 /// '__finally' compound-statement
670 StmtResult
Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc
) {
671 PoisonIdentifierRAIIObject
raii(Ident__abnormal_termination
, false),
672 raii2(Ident___abnormal_termination
, false),
673 raii3(Ident_AbnormalTermination
, false);
675 if (Tok
.isNot(tok::l_brace
))
676 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
678 ParseScope
FinallyScope(this, 0);
679 Actions
.ActOnStartSEHFinallyBlock();
681 StmtResult
Block(ParseCompoundStatement());
682 if(Block
.isInvalid()) {
683 Actions
.ActOnAbortSEHFinallyBlock();
687 return Actions
.ActOnFinishSEHFinallyBlock(FinallyLoc
, Block
.get());
692 /// seh-leave-statement:
695 StmtResult
Parser::ParseSEHLeaveStatement() {
696 SourceLocation LeaveLoc
= ConsumeToken(); // eat the '__leave'.
697 return Actions
.ActOnSEHLeaveStmt(LeaveLoc
, getCurScope());
700 /// ParseLabeledStatement - We have an identifier and a ':' after it.
704 /// [GNU] identifier ':' attributes[opt]
706 /// labeled-statement:
709 StmtResult
Parser::ParseLabeledStatement(ParsedAttributes
&Attrs
,
710 ParsedStmtContext StmtCtx
) {
711 assert(Tok
.is(tok::identifier
) && Tok
.getIdentifierInfo() &&
712 "Not an identifier!");
714 // The substatement is always a 'statement', not a 'declaration', but is
715 // otherwise in the same context as the labeled-statement.
716 StmtCtx
&= ~ParsedStmtContext::AllowDeclarationsInC
;
718 Token IdentTok
= Tok
; // Save the whole token.
719 ConsumeToken(); // eat the identifier.
721 assert(Tok
.is(tok::colon
) && "Not a label!");
723 // identifier ':' statement
724 SourceLocation ColonLoc
= ConsumeToken();
726 // Read label attributes, if present.
728 if (Tok
.is(tok::kw___attribute
)) {
729 ParsedAttributes
TempAttrs(AttrFactory
);
730 ParseGNUAttributes(TempAttrs
);
732 // In C++, GNU attributes only apply to the label if they are followed by a
733 // semicolon, to disambiguate label attributes from attributes on a labeled
736 // This doesn't quite match what GCC does; if the attribute list is empty
737 // and followed by a semicolon, GCC will reject (it appears to parse the
738 // attributes as part of a statement in that case). That looks like a bug.
739 if (!getLangOpts().CPlusPlus
|| Tok
.is(tok::semi
))
740 Attrs
.takeAllFrom(TempAttrs
);
743 ParsedAttributes
EmptyCXX11Attrs(AttrFactory
);
744 SubStmt
= ParseStatementOrDeclarationAfterAttributes(
745 Stmts
, StmtCtx
, nullptr, EmptyCXX11Attrs
, TempAttrs
);
746 if (!TempAttrs
.empty() && !SubStmt
.isInvalid())
747 SubStmt
= Actions
.ActOnAttributedStmt(TempAttrs
, SubStmt
.get());
751 // The label may have no statement following it
752 if (SubStmt
.isUnset() && Tok
.is(tok::r_brace
)) {
753 DiagnoseLabelAtEndOfCompoundStatement();
754 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
757 // If we've not parsed a statement yet, parse one now.
758 if (!SubStmt
.isInvalid() && !SubStmt
.isUsable())
759 SubStmt
= ParseStatement(nullptr, StmtCtx
);
761 // Broken substmt shouldn't prevent the label from being added to the AST.
762 if (SubStmt
.isInvalid())
763 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
765 LabelDecl
*LD
= Actions
.LookupOrCreateLabel(IdentTok
.getIdentifierInfo(),
766 IdentTok
.getLocation());
767 Actions
.ProcessDeclAttributeList(Actions
.CurScope
, LD
, Attrs
);
770 return Actions
.ActOnLabelStmt(IdentTok
.getLocation(), LD
, ColonLoc
,
774 /// ParseCaseStatement
775 /// labeled-statement:
776 /// 'case' constant-expression ':' statement
777 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
779 StmtResult
Parser::ParseCaseStatement(ParsedStmtContext StmtCtx
,
780 bool MissingCase
, ExprResult Expr
) {
781 assert((MissingCase
|| Tok
.is(tok::kw_case
)) && "Not a case stmt!");
783 // The substatement is always a 'statement', not a 'declaration', but is
784 // otherwise in the same context as the labeled-statement.
785 StmtCtx
&= ~ParsedStmtContext::AllowDeclarationsInC
;
787 // It is very common for code to contain many case statements recursively
788 // nested, as in (but usually without indentation):
795 // Parsing this naively works, but is both inefficient and can cause us to run
796 // out of stack space in our recursive descent parser. As a special case,
797 // flatten this recursion into an iterative loop. This is complex and gross,
798 // but all the grossness is constrained to ParseCaseStatement (and some
799 // weirdness in the actions), so this is just local grossness :).
801 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
803 StmtResult
TopLevelCase(true);
805 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
806 // gets updated each time a new case is parsed, and whose body is unset so
807 // far. When parsing 'case 4', this is the 'case 3' node.
808 Stmt
*DeepestParsedCaseStmt
= nullptr;
810 // While we have case statements, eat and stack them.
811 SourceLocation ColonLoc
;
813 SourceLocation CaseLoc
= MissingCase
? Expr
.get()->getExprLoc() :
814 ConsumeToken(); // eat the 'case'.
815 ColonLoc
= SourceLocation();
817 if (Tok
.is(tok::code_completion
)) {
819 Actions
.CodeCompleteCase(getCurScope());
823 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
824 /// Disable this form of error recovery while we're parsing the case
826 ColonProtectionRAIIObject
ColonProtection(*this);
830 LHS
= ParseCaseExpression(CaseLoc
);
831 if (LHS
.isInvalid()) {
832 // If constant-expression is parsed unsuccessfully, recover by skipping
833 // current case statement (moving to the colon that ends it).
834 if (!SkipUntil(tok::colon
, tok::r_brace
, StopAtSemi
| StopBeforeMatch
))
842 // GNU case range extension.
843 SourceLocation DotDotDotLoc
;
845 if (TryConsumeToken(tok::ellipsis
, DotDotDotLoc
)) {
846 Diag(DotDotDotLoc
, diag::ext_gnu_case_range
);
847 RHS
= ParseCaseExpression(CaseLoc
);
848 if (RHS
.isInvalid()) {
849 if (!SkipUntil(tok::colon
, tok::r_brace
, StopAtSemi
| StopBeforeMatch
))
854 ColonProtection
.restore();
856 if (TryConsumeToken(tok::colon
, ColonLoc
)) {
857 } else if (TryConsumeToken(tok::semi
, ColonLoc
) ||
858 TryConsumeToken(tok::coloncolon
, ColonLoc
)) {
859 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
860 Diag(ColonLoc
, diag::err_expected_after
)
861 << "'case'" << tok::colon
862 << FixItHint::CreateReplacement(ColonLoc
, ":");
864 SourceLocation ExpectedLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
865 Diag(ExpectedLoc
, diag::err_expected_after
)
866 << "'case'" << tok::colon
867 << FixItHint::CreateInsertion(ExpectedLoc
, ":");
868 ColonLoc
= ExpectedLoc
;
872 Actions
.ActOnCaseStmt(CaseLoc
, LHS
, DotDotDotLoc
, RHS
, ColonLoc
);
874 // If we had a sema error parsing this case, then just ignore it and
875 // continue parsing the sub-stmt.
876 if (Case
.isInvalid()) {
877 if (TopLevelCase
.isInvalid()) // No parsed case stmts.
878 return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
879 // Otherwise, just don't add it as a nested case.
881 // If this is the first case statement we parsed, it becomes TopLevelCase.
882 // Otherwise we link it into the current chain.
883 Stmt
*NextDeepest
= Case
.get();
884 if (TopLevelCase
.isInvalid())
887 Actions
.ActOnCaseStmtBody(DeepestParsedCaseStmt
, Case
.get());
888 DeepestParsedCaseStmt
= NextDeepest
;
891 // Handle all case statements.
892 } while (Tok
.is(tok::kw_case
));
894 // If we found a non-case statement, start by parsing it.
897 if (Tok
.is(tok::r_brace
)) {
898 // "switch (X) { case 4: }", is valid and is treated as if label was
899 // followed by a null statement.
900 DiagnoseLabelAtEndOfCompoundStatement();
901 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
903 SubStmt
= ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
906 // Install the body into the most deeply-nested case.
907 if (DeepestParsedCaseStmt
) {
908 // Broken sub-stmt shouldn't prevent forming the case statement properly.
909 if (SubStmt
.isInvalid())
910 SubStmt
= Actions
.ActOnNullStmt(SourceLocation());
911 Actions
.ActOnCaseStmtBody(DeepestParsedCaseStmt
, SubStmt
.get());
914 // Return the top level parsed statement tree.
918 /// ParseDefaultStatement
919 /// labeled-statement:
920 /// 'default' ':' statement
921 /// Note that this does not parse the 'statement' at the end.
923 StmtResult
Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx
) {
924 assert(Tok
.is(tok::kw_default
) && "Not a default stmt!");
926 // The substatement is always a 'statement', not a 'declaration', but is
927 // otherwise in the same context as the labeled-statement.
928 StmtCtx
&= ~ParsedStmtContext::AllowDeclarationsInC
;
930 SourceLocation DefaultLoc
= ConsumeToken(); // eat the 'default'.
932 SourceLocation ColonLoc
;
933 if (TryConsumeToken(tok::colon
, ColonLoc
)) {
934 } else if (TryConsumeToken(tok::semi
, ColonLoc
)) {
935 // Treat "default;" as a typo for "default:".
936 Diag(ColonLoc
, diag::err_expected_after
)
937 << "'default'" << tok::colon
938 << FixItHint::CreateReplacement(ColonLoc
, ":");
940 SourceLocation ExpectedLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
941 Diag(ExpectedLoc
, diag::err_expected_after
)
942 << "'default'" << tok::colon
943 << FixItHint::CreateInsertion(ExpectedLoc
, ":");
944 ColonLoc
= ExpectedLoc
;
949 if (Tok
.is(tok::r_brace
)) {
950 // "switch (X) {... default: }", is valid and is treated as if label was
951 // followed by a null statement.
952 DiagnoseLabelAtEndOfCompoundStatement();
953 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
955 SubStmt
= ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
958 // Broken sub-stmt shouldn't prevent forming the case statement properly.
959 if (SubStmt
.isInvalid())
960 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
962 return Actions
.ActOnDefaultStmt(DefaultLoc
, ColonLoc
,
963 SubStmt
.get(), getCurScope());
966 StmtResult
Parser::ParseCompoundStatement(bool isStmtExpr
) {
967 return ParseCompoundStatement(isStmtExpr
,
968 Scope::DeclScope
| Scope::CompoundStmtScope
);
971 /// ParseCompoundStatement - Parse a "{}" block.
973 /// compound-statement: [C99 6.8.2]
974 /// { block-item-list[opt] }
975 /// [GNU] { label-declarations block-item-list } [TODO]
979 /// block-item-list block-item
983 /// [GNU] '__extension__' declaration
986 /// [GNU] label-declarations:
987 /// [GNU] label-declaration
988 /// [GNU] label-declarations label-declaration
990 /// [GNU] label-declaration:
991 /// [GNU] '__label__' identifier-list ';'
993 StmtResult
Parser::ParseCompoundStatement(bool isStmtExpr
,
994 unsigned ScopeFlags
) {
995 assert(Tok
.is(tok::l_brace
) && "Not a compound stmt!");
997 // Enter a scope to hold everything within the compound stmt. Compound
998 // statements can always hold declarations.
999 ParseScope
CompoundScope(this, ScopeFlags
);
1001 // Parse the statements in the body.
1002 return ParseCompoundStatementBody(isStmtExpr
);
1005 /// Parse any pragmas at the start of the compound expression. We handle these
1006 /// separately since some pragmas (FP_CONTRACT) must appear before any C
1007 /// statement in the compound, but may be intermingled with other pragmas.
1008 void Parser::ParseCompoundStatementLeadingPragmas() {
1009 bool checkForPragmas
= true;
1010 while (checkForPragmas
) {
1011 switch (Tok
.getKind()) {
1012 case tok::annot_pragma_vis
:
1013 HandlePragmaVisibility();
1015 case tok::annot_pragma_pack
:
1018 case tok::annot_pragma_msstruct
:
1019 HandlePragmaMSStruct();
1021 case tok::annot_pragma_align
:
1022 HandlePragmaAlign();
1024 case tok::annot_pragma_weak
:
1027 case tok::annot_pragma_weakalias
:
1028 HandlePragmaWeakAlias();
1030 case tok::annot_pragma_redefine_extname
:
1031 HandlePragmaRedefineExtname();
1033 case tok::annot_pragma_opencl_extension
:
1034 HandlePragmaOpenCLExtension();
1036 case tok::annot_pragma_fp_contract
:
1037 HandlePragmaFPContract();
1039 case tok::annot_pragma_fp
:
1042 case tok::annot_pragma_fenv_access
:
1043 case tok::annot_pragma_fenv_access_ms
:
1044 HandlePragmaFEnvAccess();
1046 case tok::annot_pragma_fenv_round
:
1047 HandlePragmaFEnvRound();
1049 case tok::annot_pragma_float_control
:
1050 HandlePragmaFloatControl();
1052 case tok::annot_pragma_ms_pointers_to_members
:
1053 HandlePragmaMSPointersToMembers();
1055 case tok::annot_pragma_ms_pragma
:
1056 HandlePragmaMSPragma();
1058 case tok::annot_pragma_ms_vtordisp
:
1059 HandlePragmaMSVtorDisp();
1061 case tok::annot_pragma_dump
:
1065 checkForPragmas
= false;
1072 void Parser::DiagnoseLabelAtEndOfCompoundStatement() {
1073 if (getLangOpts().CPlusPlus
) {
1074 Diag(Tok
, getLangOpts().CPlusPlus23
1075 ? diag::warn_cxx20_compat_label_end_of_compound_statement
1076 : diag::ext_cxx_label_end_of_compound_statement
);
1078 Diag(Tok
, getLangOpts().C23
1079 ? diag::warn_c23_compat_label_end_of_compound_statement
1080 : diag::ext_c_label_end_of_compound_statement
);
1084 /// Consume any extra semi-colons resulting in null statements,
1085 /// returning true if any tok::semi were consumed.
1086 bool Parser::ConsumeNullStmt(StmtVector
&Stmts
) {
1087 if (!Tok
.is(tok::semi
))
1090 SourceLocation StartLoc
= Tok
.getLocation();
1091 SourceLocation EndLoc
;
1093 while (Tok
.is(tok::semi
) && !Tok
.hasLeadingEmptyMacro() &&
1094 Tok
.getLocation().isValid() && !Tok
.getLocation().isMacroID()) {
1095 EndLoc
= Tok
.getLocation();
1097 // Don't just ConsumeToken() this tok::semi, do store it in AST.
1099 ParseStatementOrDeclaration(Stmts
, ParsedStmtContext::SubStmt
);
1101 Stmts
.push_back(R
.get());
1104 // Did not consume any extra semi.
1105 if (EndLoc
.isInvalid())
1108 Diag(StartLoc
, diag::warn_null_statement
)
1109 << FixItHint::CreateRemoval(SourceRange(StartLoc
, EndLoc
));
1113 StmtResult
Parser::handleExprStmt(ExprResult E
, ParsedStmtContext StmtCtx
) {
1114 bool IsStmtExprResult
= false;
1115 if ((StmtCtx
& ParsedStmtContext::InStmtExpr
) != ParsedStmtContext()) {
1116 // For GCC compatibility we skip past NullStmts.
1117 unsigned LookAhead
= 0;
1118 while (GetLookAheadToken(LookAhead
).is(tok::semi
)) {
1121 // Then look to see if the next two tokens close the statement expression;
1122 // if so, this expression statement is the last statement in a statement
1124 IsStmtExprResult
= GetLookAheadToken(LookAhead
).is(tok::r_brace
) &&
1125 GetLookAheadToken(LookAhead
+ 1).is(tok::r_paren
);
1128 if (IsStmtExprResult
)
1129 E
= Actions
.ActOnStmtExprResult(E
);
1130 return Actions
.ActOnExprStmt(E
, /*DiscardedValue=*/!IsStmtExprResult
);
1133 /// ParseCompoundStatementBody - Parse a sequence of statements optionally
1134 /// followed by a label and invoke the ActOnCompoundStmt action. This expects
1135 /// the '{' to be the current token, and consume the '}' at the end of the
1136 /// block. It does not manipulate the scope stack.
1137 StmtResult
Parser::ParseCompoundStatementBody(bool isStmtExpr
) {
1138 PrettyStackTraceLoc
CrashInfo(PP
.getSourceManager(),
1140 "in compound statement ('{}')");
1142 // Record the current FPFeatures, restore on leaving the
1143 // compound statement.
1144 Sema::FPFeaturesStateRAII
SaveFPFeatures(Actions
);
1146 InMessageExpressionRAIIObject
InMessage(*this, false);
1147 BalancedDelimiterTracker
T(*this, tok::l_brace
);
1148 if (T
.consumeOpen())
1151 Sema::CompoundScopeRAII
CompoundScope(Actions
, isStmtExpr
);
1153 // Parse any pragmas at the beginning of the compound statement.
1154 ParseCompoundStatementLeadingPragmas();
1155 Actions
.ActOnAfterCompoundStatementLeadingPragmas();
1159 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1160 // only allowed at the start of a compound stmt regardless of the language.
1161 while (Tok
.is(tok::kw___label__
)) {
1162 SourceLocation LabelLoc
= ConsumeToken();
1164 SmallVector
<Decl
*, 8> DeclsInGroup
;
1166 if (Tok
.isNot(tok::identifier
)) {
1167 Diag(Tok
, diag::err_expected
) << tok::identifier
;
1171 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1172 SourceLocation IdLoc
= ConsumeToken();
1173 DeclsInGroup
.push_back(Actions
.LookupOrCreateLabel(II
, IdLoc
, LabelLoc
));
1175 if (!TryConsumeToken(tok::comma
))
1179 DeclSpec
DS(AttrFactory
);
1180 DeclGroupPtrTy Res
=
1181 Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
, DeclsInGroup
);
1182 StmtResult R
= Actions
.ActOnDeclStmt(Res
, LabelLoc
, Tok
.getLocation());
1184 ExpectAndConsumeSemi(diag::err_expected_semi_declaration
);
1186 Stmts
.push_back(R
.get());
1189 ParsedStmtContext SubStmtCtx
=
1190 ParsedStmtContext::Compound
|
1191 (isStmtExpr
? ParsedStmtContext::InStmtExpr
: ParsedStmtContext());
1193 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
1194 Tok
.isNot(tok::eof
)) {
1195 if (Tok
.is(tok::annot_pragma_unused
)) {
1196 HandlePragmaUnused();
1200 if (ConsumeNullStmt(Stmts
))
1204 if (Tok
.isNot(tok::kw___extension__
)) {
1205 R
= ParseStatementOrDeclaration(Stmts
, SubStmtCtx
);
1207 // __extension__ can start declarations and it can also be a unary
1208 // operator for expressions. Consume multiple __extension__ markers here
1209 // until we can determine which is which.
1210 // FIXME: This loses extension expressions in the AST!
1211 SourceLocation ExtLoc
= ConsumeToken();
1212 while (Tok
.is(tok::kw___extension__
))
1215 ParsedAttributes
attrs(AttrFactory
);
1216 MaybeParseCXX11Attributes(attrs
, /*MightBeObjCMessageSend*/ true);
1218 // If this is the start of a declaration, parse it as such.
1219 if (isDeclarationStatement()) {
1220 // __extension__ silences extension warnings in the subdeclaration.
1221 // FIXME: Save the __extension__ on the decl as a node somehow?
1222 ExtensionRAIIObject
O(Diags
);
1224 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
1225 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
1226 DeclGroupPtrTy Res
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
,
1227 attrs
, DeclSpecAttrs
);
1228 R
= Actions
.ActOnDeclStmt(Res
, DeclStart
, DeclEnd
);
1230 // Otherwise this was a unary __extension__ marker.
1231 ExprResult
Res(ParseExpressionWithLeadingExtension(ExtLoc
));
1233 if (Res
.isInvalid()) {
1234 SkipUntil(tok::semi
);
1238 // Eat the semicolon at the end of stmt and convert the expr into a
1240 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr
);
1241 R
= handleExprStmt(Res
, SubStmtCtx
);
1243 R
= Actions
.ActOnAttributedStmt(attrs
, R
.get());
1248 Stmts
.push_back(R
.get());
1250 // Warn the user that using option `-ffp-eval-method=source` on a
1251 // 32-bit target and feature `sse` disabled, or using
1252 // `pragma clang fp eval_method=source` and feature `sse` disabled, is not
1254 if (!PP
.getTargetInfo().supportSourceEvalMethod() &&
1255 (PP
.getLastFPEvalPragmaLocation().isValid() ||
1256 PP
.getCurrentFPEvalMethod() ==
1257 LangOptions::FPEvalMethodKind::FEM_Source
))
1258 Diag(Tok
.getLocation(),
1259 diag::warn_no_support_for_eval_method_source_on_m32
);
1261 SourceLocation CloseLoc
= Tok
.getLocation();
1263 // We broke out of the while loop because we found a '}' or EOF.
1264 if (!T
.consumeClose()) {
1265 // If this is the '})' of a statement expression, check that it's written
1266 // in a sensible way.
1267 if (isStmtExpr
&& Tok
.is(tok::r_paren
))
1268 checkCompoundToken(CloseLoc
, tok::r_brace
, CompoundToken::StmtExprEnd
);
1270 // Recover by creating a compound statement with what we parsed so far,
1271 // instead of dropping everything and returning StmtError().
1274 if (T
.getCloseLocation().isValid())
1275 CloseLoc
= T
.getCloseLocation();
1277 return Actions
.ActOnCompoundStmt(T
.getOpenLocation(), CloseLoc
,
1281 /// ParseParenExprOrCondition:
1282 /// [C ] '(' expression ')'
1283 /// [C++] '(' condition ')'
1284 /// [C++1z] '(' init-statement[opt] condition ')'
1286 /// This function parses and performs error recovery on the specified condition
1287 /// or expression (depending on whether we're in C++ or C mode). This function
1288 /// goes out of its way to recover well. It returns true if there was a parser
1289 /// error (the right paren couldn't be found), which indicates that the caller
1290 /// should try to recover harder. It returns false if the condition is
1291 /// successfully parsed. Note that a successful parse can still have semantic
1292 /// errors in the condition.
1293 /// Additionally, it will assign the location of the outer-most '(' and ')',
1294 /// to LParenLoc and RParenLoc, respectively.
1295 bool Parser::ParseParenExprOrCondition(StmtResult
*InitStmt
,
1296 Sema::ConditionResult
&Cond
,
1298 Sema::ConditionKind CK
,
1299 SourceLocation
&LParenLoc
,
1300 SourceLocation
&RParenLoc
) {
1301 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1303 SourceLocation Start
= Tok
.getLocation();
1305 if (getLangOpts().CPlusPlus
) {
1306 Cond
= ParseCXXCondition(InitStmt
, Loc
, CK
, false);
1308 ExprResult CondExpr
= ParseExpression();
1310 // If required, convert to a boolean value.
1311 if (CondExpr
.isInvalid())
1312 Cond
= Sema::ConditionError();
1314 Cond
= Actions
.ActOnCondition(getCurScope(), Loc
, CondExpr
.get(), CK
,
1315 /*MissingOK=*/false);
1318 // If the parser was confused by the condition and we don't have a ')', try to
1319 // recover by skipping ahead to a semi and bailing out. If condexp is
1320 // semantically invalid but we have well formed code, keep going.
1321 if (Cond
.isInvalid() && Tok
.isNot(tok::r_paren
)) {
1322 SkipUntil(tok::semi
);
1323 // Skipping may have stopped if it found the containing ')'. If so, we can
1324 // continue parsing the if statement.
1325 if (Tok
.isNot(tok::r_paren
))
1329 if (Cond
.isInvalid()) {
1330 ExprResult CondExpr
= Actions
.CreateRecoveryExpr(
1331 Start
, Tok
.getLocation() == Start
? Start
: PrevTokLocation
, {},
1332 Actions
.PreferredConditionType(CK
));
1333 if (!CondExpr
.isInvalid())
1334 Cond
= Actions
.ActOnCondition(getCurScope(), Loc
, CondExpr
.get(), CK
,
1335 /*MissingOK=*/false);
1338 // Either the condition is valid or the rparen is present.
1340 LParenLoc
= T
.getOpenLocation();
1341 RParenLoc
= T
.getCloseLocation();
1343 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1344 // that all callers are looking for a statement after the condition, so ")"
1346 while (Tok
.is(tok::r_paren
)) {
1347 Diag(Tok
, diag::err_extraneous_rparen_in_condition
)
1348 << FixItHint::CreateRemoval(Tok
.getLocation());
1357 enum MisleadingStatementKind
{ MSK_if
, MSK_else
, MSK_for
, MSK_while
};
1359 struct MisleadingIndentationChecker
{
1361 SourceLocation StmtLoc
;
1362 SourceLocation PrevLoc
;
1363 unsigned NumDirectives
;
1364 MisleadingStatementKind Kind
;
1366 MisleadingIndentationChecker(Parser
&P
, MisleadingStatementKind K
,
1368 : P(P
), StmtLoc(SL
), PrevLoc(P
.getCurToken().getLocation()),
1369 NumDirectives(P
.getPreprocessor().getNumDirectives()), Kind(K
),
1370 ShouldSkip(P
.getCurToken().is(tok::l_brace
)) {
1371 if (!P
.MisleadingIndentationElseLoc
.isInvalid()) {
1372 StmtLoc
= P
.MisleadingIndentationElseLoc
;
1373 P
.MisleadingIndentationElseLoc
= SourceLocation();
1375 if (Kind
== MSK_else
&& !ShouldSkip
)
1376 P
.MisleadingIndentationElseLoc
= SL
;
1379 /// Compute the column number will aligning tabs on TabStop (-ftabstop), this
1380 /// gives the visual indentation of the SourceLocation.
1381 static unsigned getVisualIndentation(SourceManager
&SM
, SourceLocation Loc
) {
1382 unsigned TabStop
= SM
.getDiagnostics().getDiagnosticOptions().TabStop
;
1384 unsigned ColNo
= SM
.getSpellingColumnNumber(Loc
);
1385 if (ColNo
== 0 || TabStop
== 1)
1388 std::pair
<FileID
, unsigned> FIDAndOffset
= SM
.getDecomposedLoc(Loc
);
1391 StringRef BufData
= SM
.getBufferData(FIDAndOffset
.first
, &Invalid
);
1395 const char *EndPos
= BufData
.data() + FIDAndOffset
.second
;
1396 // FileOffset are 0-based and Column numbers are 1-based
1397 assert(FIDAndOffset
.second
+ 1 >= ColNo
&&
1398 "Column number smaller than file offset?");
1400 unsigned VisualColumn
= 0; // Stored as 0-based column, here.
1401 // Loop from beginning of line up to Loc's file position, counting columns,
1403 for (const char *CurPos
= EndPos
- (ColNo
- 1); CurPos
!= EndPos
;
1405 if (*CurPos
== '\t')
1406 // Advance visual column to next tabstop.
1407 VisualColumn
+= (TabStop
- VisualColumn
% TabStop
);
1411 return VisualColumn
+ 1;
1415 Token Tok
= P
.getCurToken();
1416 if (P
.getActions().getDiagnostics().isIgnored(
1417 diag::warn_misleading_indentation
, Tok
.getLocation()) ||
1418 ShouldSkip
|| NumDirectives
!= P
.getPreprocessor().getNumDirectives() ||
1419 Tok
.isOneOf(tok::semi
, tok::r_brace
) || Tok
.isAnnotation() ||
1420 Tok
.getLocation().isMacroID() || PrevLoc
.isMacroID() ||
1421 StmtLoc
.isMacroID() ||
1422 (Kind
== MSK_else
&& P
.MisleadingIndentationElseLoc
.isInvalid())) {
1423 P
.MisleadingIndentationElseLoc
= SourceLocation();
1426 if (Kind
== MSK_else
)
1427 P
.MisleadingIndentationElseLoc
= SourceLocation();
1429 SourceManager
&SM
= P
.getPreprocessor().getSourceManager();
1430 unsigned PrevColNum
= getVisualIndentation(SM
, PrevLoc
);
1431 unsigned CurColNum
= getVisualIndentation(SM
, Tok
.getLocation());
1432 unsigned StmtColNum
= getVisualIndentation(SM
, StmtLoc
);
1434 if (PrevColNum
!= 0 && CurColNum
!= 0 && StmtColNum
!= 0 &&
1435 ((PrevColNum
> StmtColNum
&& PrevColNum
== CurColNum
) ||
1436 !Tok
.isAtStartOfLine()) &&
1437 SM
.getPresumedLineNumber(StmtLoc
) !=
1438 SM
.getPresumedLineNumber(Tok
.getLocation()) &&
1439 (Tok
.isNot(tok::identifier
) ||
1440 P
.getPreprocessor().LookAhead(0).isNot(tok::colon
))) {
1441 P
.Diag(Tok
.getLocation(), diag::warn_misleading_indentation
) << Kind
;
1442 P
.Diag(StmtLoc
, diag::note_previous_statement
);
1449 /// ParseIfStatement
1450 /// if-statement: [C99 6.8.4.1]
1451 /// 'if' '(' expression ')' statement
1452 /// 'if' '(' expression ')' statement 'else' statement
1453 /// [C++] 'if' '(' condition ')' statement
1454 /// [C++] 'if' '(' condition ')' statement 'else' statement
1455 /// [C++23] 'if' '!' [opt] consteval compound-statement
1456 /// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement
1458 StmtResult
Parser::ParseIfStatement(SourceLocation
*TrailingElseLoc
) {
1459 assert(Tok
.is(tok::kw_if
) && "Not an if stmt!");
1460 SourceLocation IfLoc
= ConsumeToken(); // eat the 'if'.
1462 bool IsConstexpr
= false;
1463 bool IsConsteval
= false;
1464 SourceLocation NotLocation
;
1465 SourceLocation ConstevalLoc
;
1467 if (Tok
.is(tok::kw_constexpr
)) {
1468 Diag(Tok
, getLangOpts().CPlusPlus17
? diag::warn_cxx14_compat_constexpr_if
1469 : diag::ext_constexpr_if
);
1473 if (Tok
.is(tok::exclaim
)) {
1474 NotLocation
= ConsumeToken();
1477 if (Tok
.is(tok::kw_consteval
)) {
1478 Diag(Tok
, getLangOpts().CPlusPlus23
? diag::warn_cxx20_compat_consteval_if
1479 : diag::ext_consteval_if
);
1481 ConstevalLoc
= ConsumeToken();
1484 if (!IsConsteval
&& (NotLocation
.isValid() || Tok
.isNot(tok::l_paren
))) {
1485 Diag(Tok
, diag::err_expected_lparen_after
) << "if";
1486 SkipUntil(tok::semi
);
1490 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1492 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1493 // the case for C90.
1496 // A name introduced by a declaration in a condition is in scope from its
1497 // point of declaration until the end of the substatements controlled by the
1500 // Names declared in the for-init-statement, and in the condition of if,
1501 // while, for, and switch statements are local to the if, while, for, or
1502 // switch statement (including the controlled statement).
1504 ParseScope
IfScope(this, Scope::DeclScope
| Scope::ControlScope
, C99orCXX
);
1506 // Parse the condition.
1507 StmtResult InitStmt
;
1508 Sema::ConditionResult Cond
;
1509 SourceLocation LParen
;
1510 SourceLocation RParen
;
1511 std::optional
<bool> ConstexprCondition
;
1514 if (ParseParenExprOrCondition(&InitStmt
, Cond
, IfLoc
,
1515 IsConstexpr
? Sema::ConditionKind::ConstexprIf
1516 : Sema::ConditionKind::Boolean
,
1521 ConstexprCondition
= Cond
.getKnownValue();
1524 bool IsBracedThen
= Tok
.is(tok::l_brace
);
1526 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1527 // there is no compound stmt. C90 does not have this clause. We only do this
1528 // if the body isn't a compound statement to avoid push/pop in common cases.
1531 // The substatement in a selection-statement (each substatement, in the else
1532 // form of the if statement) implicitly defines a local scope.
1534 // For C++ we create a scope for the condition and a new scope for
1535 // substatements because:
1536 // -When the 'then' scope exits, we want the condition declaration to still be
1537 // active for the 'else' scope too.
1538 // -Sema will detect name clashes by considering declarations of a
1539 // 'ControlScope' as part of its direct subscope.
1540 // -If we wanted the condition and substatement to be in the same scope, we
1541 // would have to notify ParseStatement not to create a new scope. It's
1542 // simpler to let it create a new scope.
1544 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, IsBracedThen
);
1546 MisleadingIndentationChecker
MIChecker(*this, MSK_if
, IfLoc
);
1548 // Read the 'then' stmt.
1549 SourceLocation ThenStmtLoc
= Tok
.getLocation();
1551 SourceLocation InnerStatementTrailingElseLoc
;
1552 StmtResult ThenStmt
;
1554 bool ShouldEnter
= ConstexprCondition
&& !*ConstexprCondition
;
1555 Sema::ExpressionEvaluationContext Context
=
1556 Sema::ExpressionEvaluationContext::DiscardedStatement
;
1557 if (NotLocation
.isInvalid() && IsConsteval
) {
1558 Context
= Sema::ExpressionEvaluationContext::ImmediateFunctionContext
;
1562 EnterExpressionEvaluationContext
PotentiallyDiscarded(
1563 Actions
, Context
, nullptr,
1564 Sema::ExpressionEvaluationContextRecord::EK_Other
, ShouldEnter
);
1565 ThenStmt
= ParseStatement(&InnerStatementTrailingElseLoc
);
1568 if (Tok
.isNot(tok::kw_else
))
1571 // Pop the 'if' scope if needed.
1574 // If it has an else, parse it.
1575 SourceLocation ElseLoc
;
1576 SourceLocation ElseStmtLoc
;
1577 StmtResult ElseStmt
;
1579 if (Tok
.is(tok::kw_else
)) {
1580 if (TrailingElseLoc
)
1581 *TrailingElseLoc
= Tok
.getLocation();
1583 ElseLoc
= ConsumeToken();
1584 ElseStmtLoc
= Tok
.getLocation();
1586 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1587 // there is no compound stmt. C90 does not have this clause. We only do
1588 // this if the body isn't a compound statement to avoid push/pop in common
1592 // The substatement in a selection-statement (each substatement, in the else
1593 // form of the if statement) implicitly defines a local scope.
1595 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
,
1596 Tok
.is(tok::l_brace
));
1598 MisleadingIndentationChecker
MIChecker(*this, MSK_else
, ElseLoc
);
1599 bool ShouldEnter
= ConstexprCondition
&& *ConstexprCondition
;
1600 Sema::ExpressionEvaluationContext Context
=
1601 Sema::ExpressionEvaluationContext::DiscardedStatement
;
1602 if (NotLocation
.isValid() && IsConsteval
) {
1603 Context
= Sema::ExpressionEvaluationContext::ImmediateFunctionContext
;
1607 EnterExpressionEvaluationContext
PotentiallyDiscarded(
1608 Actions
, Context
, nullptr,
1609 Sema::ExpressionEvaluationContextRecord::EK_Other
, ShouldEnter
);
1610 ElseStmt
= ParseStatement();
1612 if (ElseStmt
.isUsable())
1615 // Pop the 'else' scope if needed.
1617 } else if (Tok
.is(tok::code_completion
)) {
1619 Actions
.CodeCompleteAfterIf(getCurScope(), IsBracedThen
);
1621 } else if (InnerStatementTrailingElseLoc
.isValid()) {
1622 Diag(InnerStatementTrailingElseLoc
, diag::warn_dangling_else
);
1627 // If the then or else stmt is invalid and the other is valid (and present),
1628 // turn the invalid one into a null stmt to avoid dropping the other
1629 // part. If both are invalid, return error.
1630 if ((ThenStmt
.isInvalid() && ElseStmt
.isInvalid()) ||
1631 (ThenStmt
.isInvalid() && ElseStmt
.get() == nullptr) ||
1632 (ThenStmt
.get() == nullptr && ElseStmt
.isInvalid())) {
1633 // Both invalid, or one is invalid and other is non-present: return error.
1638 auto IsCompoundStatement
= [](const Stmt
*S
) {
1639 if (const auto *Outer
= dyn_cast_if_present
<AttributedStmt
>(S
))
1640 S
= Outer
->getSubStmt();
1641 return isa_and_nonnull
<clang::CompoundStmt
>(S
);
1644 if (!IsCompoundStatement(ThenStmt
.get())) {
1645 Diag(ConstevalLoc
, diag::err_expected_after
) << "consteval"
1649 if (!ElseStmt
.isUnset() && !IsCompoundStatement(ElseStmt
.get())) {
1650 Diag(ElseLoc
, diag::err_expected_after
) << "else"
1656 // Now if either are invalid, replace with a ';'.
1657 if (ThenStmt
.isInvalid())
1658 ThenStmt
= Actions
.ActOnNullStmt(ThenStmtLoc
);
1659 if (ElseStmt
.isInvalid())
1660 ElseStmt
= Actions
.ActOnNullStmt(ElseStmtLoc
);
1662 IfStatementKind Kind
= IfStatementKind::Ordinary
;
1664 Kind
= IfStatementKind::Constexpr
;
1665 else if (IsConsteval
)
1666 Kind
= NotLocation
.isValid() ? IfStatementKind::ConstevalNegated
1667 : IfStatementKind::ConstevalNonNegated
;
1669 return Actions
.ActOnIfStmt(IfLoc
, Kind
, LParen
, InitStmt
.get(), Cond
, RParen
,
1670 ThenStmt
.get(), ElseLoc
, ElseStmt
.get());
1673 /// ParseSwitchStatement
1674 /// switch-statement:
1675 /// 'switch' '(' expression ')' statement
1676 /// [C++] 'switch' '(' condition ')' statement
1677 StmtResult
Parser::ParseSwitchStatement(SourceLocation
*TrailingElseLoc
) {
1678 assert(Tok
.is(tok::kw_switch
) && "Not a switch stmt!");
1679 SourceLocation SwitchLoc
= ConsumeToken(); // eat the 'switch'.
1681 if (Tok
.isNot(tok::l_paren
)) {
1682 Diag(Tok
, diag::err_expected_lparen_after
) << "switch";
1683 SkipUntil(tok::semi
);
1687 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1689 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1690 // not the case for C90. Start the switch scope.
1693 // A name introduced by a declaration in a condition is in scope from its
1694 // point of declaration until the end of the substatements controlled by the
1697 // Names declared in the for-init-statement, and in the condition of if,
1698 // while, for, and switch statements are local to the if, while, for, or
1699 // switch statement (including the controlled statement).
1701 unsigned ScopeFlags
= Scope::SwitchScope
;
1703 ScopeFlags
|= Scope::DeclScope
| Scope::ControlScope
;
1704 ParseScope
SwitchScope(this, ScopeFlags
);
1706 // Parse the condition.
1707 StmtResult InitStmt
;
1708 Sema::ConditionResult Cond
;
1709 SourceLocation LParen
;
1710 SourceLocation RParen
;
1711 if (ParseParenExprOrCondition(&InitStmt
, Cond
, SwitchLoc
,
1712 Sema::ConditionKind::Switch
, LParen
, RParen
))
1715 StmtResult Switch
= Actions
.ActOnStartOfSwitchStmt(
1716 SwitchLoc
, LParen
, InitStmt
.get(), Cond
, RParen
);
1718 if (Switch
.isInvalid()) {
1719 // Skip the switch body.
1720 // FIXME: This is not optimal recovery, but parsing the body is more
1721 // dangerous due to the presence of case and default statements, which
1722 // will have no place to connect back with the switch.
1723 if (Tok
.is(tok::l_brace
)) {
1725 SkipUntil(tok::r_brace
);
1727 SkipUntil(tok::semi
);
1731 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1732 // there is no compound stmt. C90 does not have this clause. We only do this
1733 // if the body isn't a compound statement to avoid push/pop in common cases.
1736 // The substatement in a selection-statement (each substatement, in the else
1737 // form of the if statement) implicitly defines a local scope.
1739 // See comments in ParseIfStatement for why we create a scope for the
1740 // condition and a new scope for substatement in C++.
1742 getCurScope()->AddFlags(Scope::BreakScope
);
1743 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1745 // We have incremented the mangling number for the SwitchScope and the
1746 // InnerScope, which is one too many.
1748 getCurScope()->decrementMSManglingNumber();
1750 // Read the body statement.
1751 StmtResult
Body(ParseStatement(TrailingElseLoc
));
1757 return Actions
.ActOnFinishSwitchStmt(SwitchLoc
, Switch
.get(), Body
.get());
1760 /// ParseWhileStatement
1761 /// while-statement: [C99 6.8.5.1]
1762 /// 'while' '(' expression ')' statement
1763 /// [C++] 'while' '(' condition ')' statement
1764 StmtResult
Parser::ParseWhileStatement(SourceLocation
*TrailingElseLoc
) {
1765 assert(Tok
.is(tok::kw_while
) && "Not a while stmt!");
1766 SourceLocation WhileLoc
= Tok
.getLocation();
1767 ConsumeToken(); // eat the 'while'.
1769 if (Tok
.isNot(tok::l_paren
)) {
1770 Diag(Tok
, diag::err_expected_lparen_after
) << "while";
1771 SkipUntil(tok::semi
);
1775 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1777 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1778 // the case for C90. Start the loop scope.
1781 // A name introduced by a declaration in a condition is in scope from its
1782 // point of declaration until the end of the substatements controlled by the
1785 // Names declared in the for-init-statement, and in the condition of if,
1786 // while, for, and switch statements are local to the if, while, for, or
1787 // switch statement (including the controlled statement).
1789 unsigned ScopeFlags
;
1791 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
|
1792 Scope::DeclScope
| Scope::ControlScope
;
1794 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
1795 ParseScope
WhileScope(this, ScopeFlags
);
1797 // Parse the condition.
1798 Sema::ConditionResult Cond
;
1799 SourceLocation LParen
;
1800 SourceLocation RParen
;
1801 if (ParseParenExprOrCondition(nullptr, Cond
, WhileLoc
,
1802 Sema::ConditionKind::Boolean
, LParen
, RParen
))
1805 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1806 // there is no compound stmt. C90 does not have this clause. We only do this
1807 // if the body isn't a compound statement to avoid push/pop in common cases.
1810 // The substatement in an iteration-statement implicitly defines a local scope
1811 // which is entered and exited each time through the loop.
1813 // See comments in ParseIfStatement for why we create a scope for the
1814 // condition and a new scope for substatement in C++.
1816 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1818 MisleadingIndentationChecker
MIChecker(*this, MSK_while
, WhileLoc
);
1820 // Read the body statement.
1821 StmtResult
Body(ParseStatement(TrailingElseLoc
));
1823 if (Body
.isUsable())
1825 // Pop the body scope if needed.
1829 if (Cond
.isInvalid() || Body
.isInvalid())
1832 return Actions
.ActOnWhileStmt(WhileLoc
, LParen
, Cond
, RParen
, Body
.get());
1835 /// ParseDoStatement
1836 /// do-statement: [C99 6.8.5.2]
1837 /// 'do' statement 'while' '(' expression ')' ';'
1838 /// Note: this lets the caller parse the end ';'.
1839 StmtResult
Parser::ParseDoStatement() {
1840 assert(Tok
.is(tok::kw_do
) && "Not a do stmt!");
1841 SourceLocation DoLoc
= ConsumeToken(); // eat the 'do'.
1843 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1844 // the case for C90. Start the loop scope.
1845 unsigned ScopeFlags
;
1846 if (getLangOpts().C99
)
1847 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
| Scope::DeclScope
;
1849 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
1851 ParseScope
DoScope(this, ScopeFlags
);
1853 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1854 // there is no compound stmt. C90 does not have this clause. We only do this
1855 // if the body isn't a compound statement to avoid push/pop in common cases.
1858 // The substatement in an iteration-statement implicitly defines a local scope
1859 // which is entered and exited each time through the loop.
1861 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1862 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1864 // Read the body statement.
1865 StmtResult
Body(ParseStatement());
1867 // Pop the body scope if needed.
1870 if (Tok
.isNot(tok::kw_while
)) {
1871 if (!Body
.isInvalid()) {
1872 Diag(Tok
, diag::err_expected_while
);
1873 Diag(DoLoc
, diag::note_matching
) << "'do'";
1874 SkipUntil(tok::semi
, StopBeforeMatch
);
1878 SourceLocation WhileLoc
= ConsumeToken();
1880 if (Tok
.isNot(tok::l_paren
)) {
1881 Diag(Tok
, diag::err_expected_lparen_after
) << "do/while";
1882 SkipUntil(tok::semi
, StopBeforeMatch
);
1886 // Parse the parenthesized expression.
1887 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1890 // A do-while expression is not a condition, so can't have attributes.
1891 DiagnoseAndSkipCXX11Attributes();
1893 SourceLocation Start
= Tok
.getLocation();
1894 ExprResult Cond
= ParseExpression();
1895 // Correct the typos in condition before closing the scope.
1896 if (Cond
.isUsable())
1897 Cond
= Actions
.CorrectDelayedTyposInExpr(Cond
, /*InitDecl=*/nullptr,
1898 /*RecoverUncorrectedTypos=*/true);
1900 if (!Tok
.isOneOf(tok::r_paren
, tok::r_square
, tok::r_brace
))
1901 SkipUntil(tok::semi
);
1902 Cond
= Actions
.CreateRecoveryExpr(
1903 Start
, Start
== Tok
.getLocation() ? Start
: PrevTokLocation
, {},
1904 Actions
.getASTContext().BoolTy
);
1909 if (Cond
.isInvalid() || Body
.isInvalid())
1912 return Actions
.ActOnDoStmt(DoLoc
, Body
.get(), WhileLoc
, T
.getOpenLocation(),
1913 Cond
.get(), T
.getCloseLocation());
1916 bool Parser::isForRangeIdentifier() {
1917 assert(Tok
.is(tok::identifier
));
1919 const Token
&Next
= NextToken();
1920 if (Next
.is(tok::colon
))
1923 if (Next
.isOneOf(tok::l_square
, tok::kw_alignas
)) {
1924 TentativeParsingAction
PA(*this);
1926 SkipCXX11Attributes();
1927 bool Result
= Tok
.is(tok::colon
);
1935 /// ParseForStatement
1936 /// for-statement: [C99 6.8.5.3]
1937 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1938 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1939 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1942 /// 'co_await'[opt] [Coroutines]
1943 /// '(' for-range-declaration ':' for-range-initializer ')'
1945 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1946 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1948 /// [C++] for-init-statement:
1949 /// [C++] expression-statement
1950 /// [C++] simple-declaration
1951 /// [C++23] alias-declaration
1953 /// [C++0x] for-range-declaration:
1954 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1955 /// [C++0x] for-range-initializer:
1956 /// [C++0x] expression
1957 /// [C++0x] braced-init-list [TODO]
1958 StmtResult
Parser::ParseForStatement(SourceLocation
*TrailingElseLoc
) {
1959 assert(Tok
.is(tok::kw_for
) && "Not a for stmt!");
1960 SourceLocation ForLoc
= ConsumeToken(); // eat the 'for'.
1962 SourceLocation CoawaitLoc
;
1963 if (Tok
.is(tok::kw_co_await
))
1964 CoawaitLoc
= ConsumeToken();
1966 if (Tok
.isNot(tok::l_paren
)) {
1967 Diag(Tok
, diag::err_expected_lparen_after
) << "for";
1968 SkipUntil(tok::semi
);
1972 bool C99orCXXorObjC
= getLangOpts().C99
|| getLangOpts().CPlusPlus
||
1975 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1976 // the case for C90. Start the loop scope.
1979 // A name introduced by a declaration in a condition is in scope from its
1980 // point of declaration until the end of the substatements controlled by the
1983 // Names declared in the for-init-statement, and in the condition of if,
1984 // while, for, and switch statements are local to the if, while, for, or
1985 // switch statement (including the controlled statement).
1987 // Names declared in the for-init-statement are in the same declarative-region
1988 // as those declared in the condition.
1990 unsigned ScopeFlags
= 0;
1992 ScopeFlags
= Scope::DeclScope
| Scope::ControlScope
;
1994 ParseScope
ForScope(this, ScopeFlags
);
1996 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2001 bool ForEach
= false;
2002 StmtResult FirstPart
;
2003 Sema::ConditionResult SecondPart
;
2004 ExprResult Collection
;
2005 ForRangeInfo ForRangeInfo
;
2006 FullExprArg
ThirdPart(Actions
);
2008 if (Tok
.is(tok::code_completion
)) {
2010 Actions
.CodeCompleteOrdinaryName(getCurScope(),
2011 C99orCXXorObjC
? Sema::PCC_ForInit
2012 : Sema::PCC_Expression
);
2016 ParsedAttributes
attrs(AttrFactory
);
2017 MaybeParseCXX11Attributes(attrs
);
2019 SourceLocation EmptyInitStmtSemiLoc
;
2021 // Parse the first part of the for specifier.
2022 if (Tok
.is(tok::semi
)) { // for (;
2023 ProhibitAttributes(attrs
);
2024 // no first part, eat the ';'.
2025 SourceLocation SemiLoc
= Tok
.getLocation();
2026 if (!Tok
.hasLeadingEmptyMacro() && !SemiLoc
.isMacroID())
2027 EmptyInitStmtSemiLoc
= SemiLoc
;
2029 } else if (getLangOpts().CPlusPlus
&& Tok
.is(tok::identifier
) &&
2030 isForRangeIdentifier()) {
2031 ProhibitAttributes(attrs
);
2032 IdentifierInfo
*Name
= Tok
.getIdentifierInfo();
2033 SourceLocation Loc
= ConsumeToken();
2034 MaybeParseCXX11Attributes(attrs
);
2036 ForRangeInfo
.ColonLoc
= ConsumeToken();
2037 if (Tok
.is(tok::l_brace
))
2038 ForRangeInfo
.RangeExpr
= ParseBraceInitializer();
2040 ForRangeInfo
.RangeExpr
= ParseExpression();
2042 Diag(Loc
, diag::err_for_range_identifier
)
2043 << ((getLangOpts().CPlusPlus11
&& !getLangOpts().CPlusPlus17
)
2044 ? FixItHint::CreateInsertion(Loc
, "auto &&")
2047 ForRangeInfo
.LoopVar
=
2048 Actions
.ActOnCXXForRangeIdentifier(getCurScope(), Loc
, Name
, attrs
);
2049 } else if (isForInitDeclaration()) { // for (int X = 4;
2050 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
2052 // Parse declaration, which eats the ';'.
2053 if (!C99orCXXorObjC
) { // Use of C99-style for loops in C90 mode?
2054 Diag(Tok
, diag::ext_c99_variable_decl_in_for_loop
);
2055 Diag(Tok
, diag::warn_gcc_variable_decl_in_for_loop
);
2058 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
2059 if (Tok
.is(tok::kw_using
)) {
2060 DG
= ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit
,
2062 FirstPart
= Actions
.ActOnDeclStmt(DG
, DeclStart
, Tok
.getLocation());
2064 // In C++0x, "for (T NS:a" might not be a typo for ::
2065 bool MightBeForRangeStmt
= getLangOpts().CPlusPlus
;
2066 ColonProtectionRAIIObject
ColonProtection(*this, MightBeForRangeStmt
);
2067 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
2068 DG
= ParseSimpleDeclaration(
2069 DeclaratorContext::ForInit
, DeclEnd
, attrs
, DeclSpecAttrs
, false,
2070 MightBeForRangeStmt
? &ForRangeInfo
: nullptr);
2071 FirstPart
= Actions
.ActOnDeclStmt(DG
, DeclStart
, Tok
.getLocation());
2072 if (ForRangeInfo
.ParsedForRangeDecl()) {
2073 Diag(ForRangeInfo
.ColonLoc
, getLangOpts().CPlusPlus11
2074 ? diag::warn_cxx98_compat_for_range
2075 : diag::ext_for_range
);
2076 ForRangeInfo
.LoopVar
= FirstPart
;
2077 FirstPart
= StmtResult();
2078 } else if (Tok
.is(tok::semi
)) { // for (int x = 4;
2080 } else if ((ForEach
= isTokIdentifier_in())) {
2081 Actions
.ActOnForEachDeclStmt(DG
);
2082 // ObjC: for (id x in expr)
2083 ConsumeToken(); // consume 'in'
2085 if (Tok
.is(tok::code_completion
)) {
2087 Actions
.CodeCompleteObjCForCollection(getCurScope(), DG
);
2090 Collection
= ParseExpression();
2092 Diag(Tok
, diag::err_expected_semi_for
);
2096 ProhibitAttributes(attrs
);
2097 Value
= Actions
.CorrectDelayedTyposInExpr(ParseExpression());
2099 ForEach
= isTokIdentifier_in();
2101 // Turn the expression into a stmt.
2102 if (!Value
.isInvalid()) {
2104 FirstPart
= Actions
.ActOnForEachLValueExpr(Value
.get());
2106 // We already know this is not an init-statement within a for loop, so
2107 // if we are parsing a C++11 range-based for loop, we should treat this
2108 // expression statement as being a discarded value expression because
2109 // we will err below. This way we do not warn on an unused expression
2110 // that was an error in the first place, like with: for (expr : expr);
2111 bool IsRangeBasedFor
=
2112 getLangOpts().CPlusPlus11
&& !ForEach
&& Tok
.is(tok::colon
);
2113 FirstPart
= Actions
.ActOnExprStmt(Value
, !IsRangeBasedFor
);
2117 if (Tok
.is(tok::semi
)) {
2119 } else if (ForEach
) {
2120 ConsumeToken(); // consume 'in'
2122 if (Tok
.is(tok::code_completion
)) {
2124 Actions
.CodeCompleteObjCForCollection(getCurScope(), nullptr);
2127 Collection
= ParseExpression();
2128 } else if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::colon
) && FirstPart
.get()) {
2129 // User tried to write the reasonable, but ill-formed, for-range-statement
2130 // for (expr : expr) { ... }
2131 Diag(Tok
, diag::err_for_range_expected_decl
)
2132 << FirstPart
.get()->getSourceRange();
2133 SkipUntil(tok::r_paren
, StopBeforeMatch
);
2134 SecondPart
= Sema::ConditionError();
2136 if (!Value
.isInvalid()) {
2137 Diag(Tok
, diag::err_expected_semi_for
);
2139 // Skip until semicolon or rparen, don't consume it.
2140 SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
);
2141 if (Tok
.is(tok::semi
))
2147 // Parse the second part of the for specifier.
2148 if (!ForEach
&& !ForRangeInfo
.ParsedForRangeDecl() &&
2149 !SecondPart
.isInvalid()) {
2150 // Parse the second part of the for specifier.
2151 if (Tok
.is(tok::semi
)) { // for (...;;
2153 } else if (Tok
.is(tok::r_paren
)) {
2154 // missing both semicolons.
2156 if (getLangOpts().CPlusPlus
) {
2157 // C++2a: We've parsed an init-statement; we might have a
2158 // for-range-declaration next.
2159 bool MightBeForRangeStmt
= !ForRangeInfo
.ParsedForRangeDecl();
2160 ColonProtectionRAIIObject
ColonProtection(*this, MightBeForRangeStmt
);
2161 SourceLocation SecondPartStart
= Tok
.getLocation();
2162 Sema::ConditionKind CK
= Sema::ConditionKind::Boolean
;
2163 SecondPart
= ParseCXXCondition(
2164 /*InitStmt=*/nullptr, ForLoc
, CK
,
2165 // FIXME: recovery if we don't see another semi!
2166 /*MissingOK=*/true, MightBeForRangeStmt
? &ForRangeInfo
: nullptr,
2167 /*EnterForConditionScope=*/true);
2169 if (ForRangeInfo
.ParsedForRangeDecl()) {
2170 Diag(FirstPart
.get() ? FirstPart
.get()->getBeginLoc()
2171 : ForRangeInfo
.ColonLoc
,
2172 getLangOpts().CPlusPlus20
2173 ? diag::warn_cxx17_compat_for_range_init_stmt
2174 : diag::ext_for_range_init_stmt
)
2175 << (FirstPart
.get() ? FirstPart
.get()->getSourceRange()
2177 if (EmptyInitStmtSemiLoc
.isValid()) {
2178 Diag(EmptyInitStmtSemiLoc
, diag::warn_empty_init_statement
)
2180 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc
);
2184 if (SecondPart
.isInvalid()) {
2185 ExprResult CondExpr
= Actions
.CreateRecoveryExpr(
2187 Tok
.getLocation() == SecondPartStart
? SecondPartStart
2189 {}, Actions
.PreferredConditionType(CK
));
2190 if (!CondExpr
.isInvalid())
2191 SecondPart
= Actions
.ActOnCondition(getCurScope(), ForLoc
,
2193 /*MissingOK=*/false);
2197 // We permit 'continue' and 'break' in the condition of a for loop.
2198 getCurScope()->AddFlags(Scope::BreakScope
| Scope::ContinueScope
);
2200 ExprResult SecondExpr
= ParseExpression();
2201 if (SecondExpr
.isInvalid())
2202 SecondPart
= Sema::ConditionError();
2204 SecondPart
= Actions
.ActOnCondition(
2205 getCurScope(), ForLoc
, SecondExpr
.get(),
2206 Sema::ConditionKind::Boolean
, /*MissingOK=*/true);
2211 // Enter a break / continue scope, if we didn't already enter one while
2212 // parsing the second part.
2213 if (!getCurScope()->isContinueScope())
2214 getCurScope()->AddFlags(Scope::BreakScope
| Scope::ContinueScope
);
2216 // Parse the third part of the for statement.
2217 if (!ForEach
&& !ForRangeInfo
.ParsedForRangeDecl()) {
2218 if (Tok
.isNot(tok::semi
)) {
2219 if (!SecondPart
.isInvalid())
2220 Diag(Tok
, diag::err_expected_semi_for
);
2221 SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
);
2224 if (Tok
.is(tok::semi
)) {
2228 if (Tok
.isNot(tok::r_paren
)) { // for (...;...;)
2229 ExprResult Third
= ParseExpression();
2230 // FIXME: The C++11 standard doesn't actually say that this is a
2231 // discarded-value expression, but it clearly should be.
2232 ThirdPart
= Actions
.MakeFullDiscardedValueExpr(Third
.get());
2238 // C++ Coroutines [stmt.iter]:
2239 // 'co_await' can only be used for a range-based for statement.
2240 if (CoawaitLoc
.isValid() && !ForRangeInfo
.ParsedForRangeDecl()) {
2241 Diag(CoawaitLoc
, diag::err_for_co_await_not_range_for
);
2242 CoawaitLoc
= SourceLocation();
2245 if (CoawaitLoc
.isValid() && getLangOpts().CPlusPlus20
)
2246 Diag(CoawaitLoc
, diag::warn_deprecated_for_co_await
);
2248 // We need to perform most of the semantic analysis for a C++0x for-range
2249 // statememt before parsing the body, in order to be able to deduce the type
2250 // of an auto-typed loop variable.
2251 StmtResult ForRangeStmt
;
2252 StmtResult ForEachStmt
;
2254 if (ForRangeInfo
.ParsedForRangeDecl()) {
2255 ExprResult CorrectedRange
=
2256 Actions
.CorrectDelayedTyposInExpr(ForRangeInfo
.RangeExpr
.get());
2257 ForRangeStmt
= Actions
.ActOnCXXForRangeStmt(
2258 getCurScope(), ForLoc
, CoawaitLoc
, FirstPart
.get(),
2259 ForRangeInfo
.LoopVar
.get(), ForRangeInfo
.ColonLoc
, CorrectedRange
.get(),
2260 T
.getCloseLocation(), Sema::BFRK_Build
);
2262 // Similarly, we need to do the semantic analysis for a for-range
2263 // statement immediately in order to close over temporaries correctly.
2264 } else if (ForEach
) {
2265 ForEachStmt
= Actions
.ActOnObjCForCollectionStmt(ForLoc
,
2268 T
.getCloseLocation());
2270 // In OpenMP loop region loop control variable must be captured and be
2271 // private. Perform analysis of first part (if any).
2272 if (getLangOpts().OpenMP
&& FirstPart
.isUsable()) {
2273 Actions
.ActOnOpenMPLoopInitialization(ForLoc
, FirstPart
.get());
2277 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2278 // there is no compound stmt. C90 does not have this clause. We only do this
2279 // if the body isn't a compound statement to avoid push/pop in common cases.
2282 // The substatement in an iteration-statement implicitly defines a local scope
2283 // which is entered and exited each time through the loop.
2285 // See comments in ParseIfStatement for why we create a scope for
2286 // for-init-statement/condition and a new scope for substatement in C++.
2288 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXXorObjC
,
2289 Tok
.is(tok::l_brace
));
2291 // The body of the for loop has the same local mangling number as the
2292 // for-init-statement.
2293 // It will only be incremented if the body contains other things that would
2294 // normally increment the mangling number (like a compound statement).
2296 getCurScope()->decrementMSManglingNumber();
2298 MisleadingIndentationChecker
MIChecker(*this, MSK_for
, ForLoc
);
2300 // Read the body statement.
2301 StmtResult
Body(ParseStatement(TrailingElseLoc
));
2303 if (Body
.isUsable())
2306 // Pop the body scope if needed.
2309 // Leave the for-scope.
2312 if (Body
.isInvalid())
2316 return Actions
.FinishObjCForCollectionStmt(ForEachStmt
.get(),
2319 if (ForRangeInfo
.ParsedForRangeDecl())
2320 return Actions
.FinishCXXForRangeStmt(ForRangeStmt
.get(), Body
.get());
2322 return Actions
.ActOnForStmt(ForLoc
, T
.getOpenLocation(), FirstPart
.get(),
2323 SecondPart
, ThirdPart
, T
.getCloseLocation(),
2327 /// ParseGotoStatement
2329 /// 'goto' identifier ';'
2330 /// [GNU] 'goto' '*' expression ';'
2332 /// Note: this lets the caller parse the end ';'.
2334 StmtResult
Parser::ParseGotoStatement() {
2335 assert(Tok
.is(tok::kw_goto
) && "Not a goto stmt!");
2336 SourceLocation GotoLoc
= ConsumeToken(); // eat the 'goto'.
2339 if (Tok
.is(tok::identifier
)) {
2340 LabelDecl
*LD
= Actions
.LookupOrCreateLabel(Tok
.getIdentifierInfo(),
2342 Res
= Actions
.ActOnGotoStmt(GotoLoc
, Tok
.getLocation(), LD
);
2344 } else if (Tok
.is(tok::star
)) {
2345 // GNU indirect goto extension.
2346 Diag(Tok
, diag::ext_gnu_indirect_goto
);
2347 SourceLocation StarLoc
= ConsumeToken();
2348 ExprResult
R(ParseExpression());
2349 if (R
.isInvalid()) { // Skip to the semicolon, but don't consume it.
2350 SkipUntil(tok::semi
, StopBeforeMatch
);
2353 Res
= Actions
.ActOnIndirectGotoStmt(GotoLoc
, StarLoc
, R
.get());
2355 Diag(Tok
, diag::err_expected
) << tok::identifier
;
2362 /// ParseContinueStatement
2366 /// Note: this lets the caller parse the end ';'.
2368 StmtResult
Parser::ParseContinueStatement() {
2369 SourceLocation ContinueLoc
= ConsumeToken(); // eat the 'continue'.
2370 return Actions
.ActOnContinueStmt(ContinueLoc
, getCurScope());
2373 /// ParseBreakStatement
2377 /// Note: this lets the caller parse the end ';'.
2379 StmtResult
Parser::ParseBreakStatement() {
2380 SourceLocation BreakLoc
= ConsumeToken(); // eat the 'break'.
2381 return Actions
.ActOnBreakStmt(BreakLoc
, getCurScope());
2384 /// ParseReturnStatement
2386 /// 'return' expression[opt] ';'
2387 /// 'return' braced-init-list ';'
2388 /// 'co_return' expression[opt] ';'
2389 /// 'co_return' braced-init-list ';'
2390 StmtResult
Parser::ParseReturnStatement() {
2391 assert((Tok
.is(tok::kw_return
) || Tok
.is(tok::kw_co_return
)) &&
2392 "Not a return stmt!");
2393 bool IsCoreturn
= Tok
.is(tok::kw_co_return
);
2394 SourceLocation ReturnLoc
= ConsumeToken(); // eat the 'return'.
2397 if (Tok
.isNot(tok::semi
)) {
2399 PreferredType
.enterReturn(Actions
, Tok
.getLocation());
2400 // FIXME: Code completion for co_return.
2401 if (Tok
.is(tok::code_completion
) && !IsCoreturn
) {
2403 Actions
.CodeCompleteExpression(getCurScope(),
2404 PreferredType
.get(Tok
.getLocation()));
2408 if (Tok
.is(tok::l_brace
) && getLangOpts().CPlusPlus
) {
2409 R
= ParseInitializer();
2411 Diag(R
.get()->getBeginLoc(),
2412 getLangOpts().CPlusPlus11
2413 ? diag::warn_cxx98_compat_generalized_initializer_lists
2414 : diag::ext_generalized_initializer_lists
)
2415 << R
.get()->getSourceRange();
2417 R
= ParseExpression();
2418 if (R
.isInvalid()) {
2419 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
2424 return Actions
.ActOnCoreturnStmt(getCurScope(), ReturnLoc
, R
.get());
2425 return Actions
.ActOnReturnStmt(ReturnLoc
, R
.get(), getCurScope());
2428 StmtResult
Parser::ParsePragmaLoopHint(StmtVector
&Stmts
,
2429 ParsedStmtContext StmtCtx
,
2430 SourceLocation
*TrailingElseLoc
,
2431 ParsedAttributes
&Attrs
) {
2432 // Create temporary attribute list.
2433 ParsedAttributes
TempAttrs(AttrFactory
);
2435 SourceLocation StartLoc
= Tok
.getLocation();
2437 // Get loop hints and consume annotated token.
2438 while (Tok
.is(tok::annot_pragma_loop_hint
)) {
2440 if (!HandlePragmaLoopHint(Hint
))
2443 ArgsUnion ArgHints
[] = {Hint
.PragmaNameLoc
, Hint
.OptionLoc
, Hint
.StateLoc
,
2444 ArgsUnion(Hint
.ValueExpr
)};
2445 TempAttrs
.addNew(Hint
.PragmaNameLoc
->Ident
, Hint
.Range
, nullptr,
2446 Hint
.PragmaNameLoc
->Loc
, ArgHints
, 4,
2447 ParsedAttr::Form::Pragma());
2450 // Get the next statement.
2451 MaybeParseCXX11Attributes(Attrs
);
2453 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
2454 StmtResult S
= ParseStatementOrDeclarationAfterAttributes(
2455 Stmts
, StmtCtx
, TrailingElseLoc
, Attrs
, EmptyDeclSpecAttrs
);
2457 Attrs
.takeAllFrom(TempAttrs
);
2459 // Start of attribute range may already be set for some invalid input.
2461 if (Attrs
.Range
.getBegin().isInvalid())
2462 Attrs
.Range
.setBegin(StartLoc
);
2467 Decl
*Parser::ParseFunctionStatementBody(Decl
*Decl
, ParseScope
&BodyScope
) {
2468 assert(Tok
.is(tok::l_brace
));
2469 SourceLocation LBraceLoc
= Tok
.getLocation();
2471 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, Decl
, LBraceLoc
,
2472 "parsing function body");
2474 // Save and reset current vtordisp stack if we have entered a C++ method body.
2476 getLangOpts().CPlusPlus
&& Decl
&& isa
<CXXMethodDecl
>(Decl
);
2477 Sema::PragmaStackSentinelRAII
2478 PragmaStackSentinel(Actions
, "InternalPragmaState", IsCXXMethod
);
2480 // Do not enter a scope for the brace, as the arguments are in the same scope
2481 // (the function body) as the body itself. Instead, just read the statement
2482 // list and put it into a CompoundStmt for safe keeping.
2483 StmtResult
FnBody(ParseCompoundStatementBody());
2485 // If the function body could not be parsed, make a bogus compoundstmt.
2486 if (FnBody
.isInvalid()) {
2487 Sema::CompoundScopeRAII
CompoundScope(Actions
);
2489 Actions
.ActOnCompoundStmt(LBraceLoc
, LBraceLoc
, std::nullopt
, false);
2493 return Actions
.ActOnFinishFunctionBody(Decl
, FnBody
.get());
2496 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
2498 /// function-try-block:
2499 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2501 Decl
*Parser::ParseFunctionTryBlock(Decl
*Decl
, ParseScope
&BodyScope
) {
2502 assert(Tok
.is(tok::kw_try
) && "Expected 'try'");
2503 SourceLocation TryLoc
= ConsumeToken();
2505 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, Decl
, TryLoc
,
2506 "parsing function try block");
2508 // Constructor initializer list?
2509 if (Tok
.is(tok::colon
))
2510 ParseConstructorInitializer(Decl
);
2512 Actions
.ActOnDefaultCtorInitializers(Decl
);
2514 // Save and reset current vtordisp stack if we have entered a C++ method body.
2516 getLangOpts().CPlusPlus
&& Decl
&& isa
<CXXMethodDecl
>(Decl
);
2517 Sema::PragmaStackSentinelRAII
2518 PragmaStackSentinel(Actions
, "InternalPragmaState", IsCXXMethod
);
2520 SourceLocation LBraceLoc
= Tok
.getLocation();
2521 StmtResult
FnBody(ParseCXXTryBlockCommon(TryLoc
, /*FnTry*/true));
2522 // If we failed to parse the try-catch, we just give the function an empty
2523 // compound statement as the body.
2524 if (FnBody
.isInvalid()) {
2525 Sema::CompoundScopeRAII
CompoundScope(Actions
);
2527 Actions
.ActOnCompoundStmt(LBraceLoc
, LBraceLoc
, std::nullopt
, false);
2531 return Actions
.ActOnFinishFunctionBody(Decl
, FnBody
.get());
2534 bool Parser::trySkippingFunctionBody() {
2535 assert(SkipFunctionBodies
&&
2536 "Should only be called when SkipFunctionBodies is enabled");
2537 if (!PP
.isCodeCompletionEnabled()) {
2542 // We're in code-completion mode. Skip parsing for all function bodies unless
2543 // the body contains the code-completion point.
2544 TentativeParsingAction
PA(*this);
2545 bool IsTryCatch
= Tok
.is(tok::kw_try
);
2547 bool ErrorInPrologue
= ConsumeAndStoreFunctionPrologue(Toks
);
2548 if (llvm::any_of(Toks
, [](const Token
&Tok
) {
2549 return Tok
.is(tok::code_completion
);
2554 if (ErrorInPrologue
) {
2556 SkipMalformedDecl();
2559 if (!SkipUntil(tok::r_brace
, StopAtCodeCompletion
)) {
2563 while (IsTryCatch
&& Tok
.is(tok::kw_catch
)) {
2564 if (!SkipUntil(tok::l_brace
, StopAtCodeCompletion
) ||
2565 !SkipUntil(tok::r_brace
, StopAtCodeCompletion
)) {
2574 /// ParseCXXTryBlock - Parse a C++ try-block.
2577 /// 'try' compound-statement handler-seq
2579 StmtResult
Parser::ParseCXXTryBlock() {
2580 assert(Tok
.is(tok::kw_try
) && "Expected 'try'");
2582 SourceLocation TryLoc
= ConsumeToken();
2583 return ParseCXXTryBlockCommon(TryLoc
);
2586 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2587 /// function-try-block.
2590 /// 'try' compound-statement handler-seq
2592 /// function-try-block:
2593 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2596 /// handler handler-seq[opt]
2598 /// [Borland] try-block:
2599 /// 'try' compound-statement seh-except-block
2600 /// 'try' compound-statement seh-finally-block
2602 StmtResult
Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc
, bool FnTry
) {
2603 if (Tok
.isNot(tok::l_brace
))
2604 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
2606 StmtResult
TryBlock(ParseCompoundStatement(
2607 /*isStmtExpr=*/false, Scope::DeclScope
| Scope::TryScope
|
2608 Scope::CompoundStmtScope
|
2609 (FnTry
? Scope::FnTryCatchScope
: 0)));
2610 if (TryBlock
.isInvalid())
2613 // Borland allows SEH-handlers with 'try'
2615 if ((Tok
.is(tok::identifier
) &&
2616 Tok
.getIdentifierInfo() == getSEHExceptKeyword()) ||
2617 Tok
.is(tok::kw___finally
)) {
2618 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2620 if(Tok
.getIdentifierInfo() == getSEHExceptKeyword()) {
2621 SourceLocation Loc
= ConsumeToken();
2622 Handler
= ParseSEHExceptBlock(Loc
);
2625 SourceLocation Loc
= ConsumeToken();
2626 Handler
= ParseSEHFinallyBlock(Loc
);
2628 if(Handler
.isInvalid())
2631 return Actions
.ActOnSEHTryBlock(true /* IsCXXTry */,
2637 StmtVector Handlers
;
2639 // C++11 attributes can't appear here, despite this context seeming
2641 DiagnoseAndSkipCXX11Attributes();
2643 if (Tok
.isNot(tok::kw_catch
))
2644 return StmtError(Diag(Tok
, diag::err_expected_catch
));
2645 while (Tok
.is(tok::kw_catch
)) {
2646 StmtResult
Handler(ParseCXXCatchBlock(FnTry
));
2647 if (!Handler
.isInvalid())
2648 Handlers
.push_back(Handler
.get());
2650 // Don't bother creating the full statement if we don't have any usable
2652 if (Handlers
.empty())
2655 return Actions
.ActOnCXXTryBlock(TryLoc
, TryBlock
.get(), Handlers
);
2659 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2662 /// 'catch' '(' exception-declaration ')' compound-statement
2664 /// exception-declaration:
2665 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2666 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2669 StmtResult
Parser::ParseCXXCatchBlock(bool FnCatch
) {
2670 assert(Tok
.is(tok::kw_catch
) && "Expected 'catch'");
2672 SourceLocation CatchLoc
= ConsumeToken();
2674 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2675 if (T
.expectAndConsume())
2679 // The name in a catch exception-declaration is local to the handler and
2680 // shall not be redeclared in the outermost block of the handler.
2681 ParseScope
CatchScope(this, Scope::DeclScope
| Scope::ControlScope
|
2683 (FnCatch
? Scope::FnTryCatchScope
: 0));
2685 // exception-declaration is equivalent to '...' or a parameter-declaration
2686 // without default arguments.
2687 Decl
*ExceptionDecl
= nullptr;
2688 if (Tok
.isNot(tok::ellipsis
)) {
2689 ParsedAttributes
Attributes(AttrFactory
);
2690 MaybeParseCXX11Attributes(Attributes
);
2692 DeclSpec
DS(AttrFactory
);
2694 if (ParseCXXTypeSpecifierSeq(DS
))
2697 Declarator
ExDecl(DS
, Attributes
, DeclaratorContext::CXXCatch
);
2698 ParseDeclarator(ExDecl
);
2699 ExceptionDecl
= Actions
.ActOnExceptionDeclarator(getCurScope(), ExDecl
);
2704 if (T
.getCloseLocation().isInvalid())
2707 if (Tok
.isNot(tok::l_brace
))
2708 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
2710 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2711 StmtResult
Block(ParseCompoundStatement());
2712 if (Block
.isInvalid())
2715 return Actions
.ActOnCXXCatchBlock(CatchLoc
, ExceptionDecl
, Block
.get());
2718 void Parser::ParseMicrosoftIfExistsStatement(StmtVector
&Stmts
) {
2719 IfExistsCondition Result
;
2720 if (ParseMicrosoftIfExistsCondition(Result
))
2723 // Handle dependent statements by parsing the braces as a compound statement.
2724 // This is not the same behavior as Visual C++, which don't treat this as a
2725 // compound statement, but for Clang's type checking we can't have anything
2726 // inside these braces escaping to the surrounding code.
2727 if (Result
.Behavior
== IEB_Dependent
) {
2728 if (!Tok
.is(tok::l_brace
)) {
2729 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
2733 StmtResult Compound
= ParseCompoundStatement();
2734 if (Compound
.isInvalid())
2737 StmtResult DepResult
= Actions
.ActOnMSDependentExistsStmt(Result
.KeywordLoc
,
2742 if (DepResult
.isUsable())
2743 Stmts
.push_back(DepResult
.get());
2747 BalancedDelimiterTracker
Braces(*this, tok::l_brace
);
2748 if (Braces
.consumeOpen()) {
2749 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
2753 switch (Result
.Behavior
) {
2755 // Parse the statements below.
2759 llvm_unreachable("Dependent case handled above");
2766 // Condition is true, parse the statements.
2767 while (Tok
.isNot(tok::r_brace
)) {
2769 ParseStatementOrDeclaration(Stmts
, ParsedStmtContext::Compound
);
2771 Stmts
.push_back(R
.get());
2773 Braces
.consumeClose();