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/SemaCodeCompletion.h"
26 #include "clang/Sema/SemaObjC.h"
27 #include "clang/Sema/SemaOpenACC.h"
28 #include "clang/Sema/SemaOpenMP.h"
29 #include "clang/Sema/TypoCorrection.h"
30 #include "llvm/ADT/STLExtras.h"
33 using namespace clang
;
35 //===----------------------------------------------------------------------===//
36 // C99 6.8: Statements and Blocks.
37 //===----------------------------------------------------------------------===//
39 /// Parse a standalone statement (for instance, as the body of an 'if',
40 /// 'while', or 'for').
41 StmtResult
Parser::ParseStatement(SourceLocation
*TrailingElseLoc
,
42 ParsedStmtContext StmtCtx
) {
45 // We may get back a null statement if we found a #pragma. Keep going until
46 // we get an actual statement.
49 Res
= ParseStatementOrDeclaration(Stmts
, StmtCtx
, TrailingElseLoc
);
50 } while (!Res
.isInvalid() && !Res
.get());
55 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
56 /// StatementOrDeclaration:
62 /// compound-statement
63 /// expression-statement
64 /// selection-statement
65 /// iteration-statement
67 /// [C++] declaration-statement
69 /// [MS] seh-try-block
70 /// [OBC] objc-throw-statement
71 /// [OBC] objc-try-catch-statement
72 /// [OBC] objc-synchronized-statement
73 /// [GNU] asm-statement
74 /// [OMP] openmp-construct [TODO]
76 /// labeled-statement:
77 /// identifier ':' statement
78 /// 'case' constant-expression ':' statement
79 /// 'default' ':' statement
81 /// selection-statement:
85 /// iteration-statement:
90 /// expression-statement:
91 /// expression[opt] ';'
94 /// 'goto' identifier ';'
97 /// 'return' expression[opt] ';'
98 /// [GNU] 'goto' '*' expression ';'
100 /// [OBC] objc-throw-statement:
101 /// [OBC] '@' 'throw' expression ';'
102 /// [OBC] '@' 'throw' ';'
105 Parser::ParseStatementOrDeclaration(StmtVector
&Stmts
,
106 ParsedStmtContext StmtCtx
,
107 SourceLocation
*TrailingElseLoc
) {
109 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
111 // Because we're parsing either a statement or a declaration, the order of
112 // attribute parsing is important. [[]] attributes at the start of a
113 // statement are different from [[]] attributes that follow an __attribute__
114 // at the start of the statement. Thus, we're not using MaybeParseAttributes
115 // here because we don't want to allow arbitrary orderings.
116 ParsedAttributes
CXX11Attrs(AttrFactory
);
117 MaybeParseCXX11Attributes(CXX11Attrs
, /*MightBeObjCMessageSend*/ true);
118 ParsedAttributes
GNUOrMSAttrs(AttrFactory
);
119 if (getLangOpts().OpenCL
)
120 MaybeParseGNUAttributes(GNUOrMSAttrs
);
122 if (getLangOpts().HLSL
)
123 MaybeParseMicrosoftAttributes(GNUOrMSAttrs
);
125 StmtResult Res
= ParseStatementOrDeclarationAfterAttributes(
126 Stmts
, StmtCtx
, TrailingElseLoc
, CXX11Attrs
, GNUOrMSAttrs
);
127 MaybeDestroyTemplateIds();
129 // Attributes that are left should all go on the statement, so concatenate the
131 ParsedAttributes
Attrs(AttrFactory
);
132 takeAndConcatenateAttrs(CXX11Attrs
, GNUOrMSAttrs
, Attrs
);
134 assert((Attrs
.empty() || Res
.isInvalid() || Res
.isUsable()) &&
135 "attributes on empty statement");
137 if (Attrs
.empty() || Res
.isInvalid())
140 return Actions
.ActOnAttributedStmt(Attrs
, Res
.get());
144 class StatementFilterCCC final
: public CorrectionCandidateCallback
{
146 StatementFilterCCC(Token nextTok
) : NextToken(nextTok
) {
147 WantTypeSpecifiers
= nextTok
.isOneOf(tok::l_paren
, tok::less
, tok::l_square
,
148 tok::identifier
, tok::star
, tok::amp
);
149 WantExpressionKeywords
=
150 nextTok
.isOneOf(tok::l_paren
, tok::identifier
, tok::arrow
, tok::period
);
151 WantRemainingKeywords
=
152 nextTok
.isOneOf(tok::l_paren
, tok::semi
, tok::identifier
, tok::l_brace
);
153 WantCXXNamedCasts
= false;
156 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
157 if (FieldDecl
*FD
= candidate
.getCorrectionDeclAs
<FieldDecl
>())
158 return !candidate
.getCorrectionSpecifier() || isa
<ObjCIvarDecl
>(FD
);
159 if (NextToken
.is(tok::equal
))
160 return candidate
.getCorrectionDeclAs
<VarDecl
>();
161 if (NextToken
.is(tok::period
) &&
162 candidate
.getCorrectionDeclAs
<NamespaceDecl
>())
164 return CorrectionCandidateCallback::ValidateCandidate(candidate
);
167 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
168 return std::make_unique
<StatementFilterCCC
>(*this);
176 StmtResult
Parser::ParseStatementOrDeclarationAfterAttributes(
177 StmtVector
&Stmts
, ParsedStmtContext StmtCtx
,
178 SourceLocation
*TrailingElseLoc
, ParsedAttributes
&CXX11Attrs
,
179 ParsedAttributes
&GNUAttrs
) {
180 const char *SemiError
= nullptr;
182 SourceLocation GNUAttributeLoc
;
184 // Cases in this switch statement should fall through if the parser expects
185 // the token to end in a semicolon (in which case SemiError should be set),
186 // or they directly 'return;' if not.
188 tok::TokenKind Kind
= Tok
.getKind();
189 SourceLocation AtLoc
;
191 case tok::at
: // May be a @try or @throw statement
193 AtLoc
= ConsumeToken(); // consume @
194 return ParseObjCAtStatement(AtLoc
, StmtCtx
);
197 case tok::code_completion
:
199 Actions
.CodeCompletion().CodeCompleteOrdinaryName(
200 getCurScope(), SemaCodeCompletion::PCC_Statement
);
203 case tok::identifier
:
205 Token Next
= NextToken();
206 if (Next
.is(tok::colon
)) { // C99 6.8.1: labeled-statement
207 // Both C++11 and GNU attributes preceding the label appertain to the
208 // label, so put them in a single list to pass on to
209 // ParseLabeledStatement().
210 ParsedAttributes
Attrs(AttrFactory
);
211 takeAndConcatenateAttrs(CXX11Attrs
, GNUAttrs
, Attrs
);
213 // identifier ':' statement
214 return ParseLabeledStatement(Attrs
, StmtCtx
);
217 // Look up the identifier, and typo-correct it to a keyword if it's not
219 if (Next
.isNot(tok::coloncolon
)) {
220 // Try to limit which sets of keywords should be included in typo
221 // correction based on what the next token is.
222 StatementFilterCCC
CCC(Next
);
223 if (TryAnnotateName(&CCC
) == ANK_Error
) {
224 // Handle errors here by skipping up to the next semicolon or '}', and
225 // eat the semicolon if that's what stopped us.
226 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
227 if (Tok
.is(tok::semi
))
232 // If the identifier was annotated, try again.
233 if (Tok
.isNot(tok::identifier
))
242 bool HaveAttrs
= !CXX11Attrs
.empty() || !GNUAttrs
.empty();
243 auto IsStmtAttr
= [](ParsedAttr
&Attr
) { return Attr
.isStmtAttr(); };
244 bool AllAttrsAreStmtAttrs
= llvm::all_of(CXX11Attrs
, IsStmtAttr
) &&
245 llvm::all_of(GNUAttrs
, IsStmtAttr
);
246 // In C, the grammar production for statement (C23 6.8.1p1) does not allow
247 // for declarations, which is different from C++ (C++23 [stmt.pre]p1). So
248 // in C++, we always allow a declaration, but in C we need to check whether
249 // we're in a statement context that allows declarations. e.g., in C, the
250 // following is invalid: if (1) int x;
251 if ((getLangOpts().CPlusPlus
|| getLangOpts().MicrosoftExt
||
252 (StmtCtx
& ParsedStmtContext::AllowDeclarationsInC
) !=
253 ParsedStmtContext()) &&
254 ((GNUAttributeLoc
.isValid() && !(HaveAttrs
&& AllAttrsAreStmtAttrs
)) ||
255 isDeclarationStatement())) {
256 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
258 if (GNUAttributeLoc
.isValid()) {
259 DeclStart
= GNUAttributeLoc
;
260 Decl
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
, CXX11Attrs
,
261 GNUAttrs
, &GNUAttributeLoc
);
263 Decl
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
, CXX11Attrs
,
266 if (CXX11Attrs
.Range
.getBegin().isValid()) {
267 // The caller must guarantee that the CXX11Attrs appear before the
268 // GNUAttrs, and we rely on that here.
269 assert(GNUAttrs
.Range
.getBegin().isInvalid() ||
270 GNUAttrs
.Range
.getBegin() > CXX11Attrs
.Range
.getBegin());
271 DeclStart
= CXX11Attrs
.Range
.getBegin();
272 } else if (GNUAttrs
.Range
.getBegin().isValid())
273 DeclStart
= GNUAttrs
.Range
.getBegin();
274 return Actions
.ActOnDeclStmt(Decl
, DeclStart
, DeclEnd
);
277 if (Tok
.is(tok::r_brace
)) {
278 Diag(Tok
, diag::err_expected_statement
);
282 switch (Tok
.getKind()) {
283 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
284 #include "clang/Basic/TransformTypeTraits.def"
285 if (NextToken().is(tok::less
)) {
286 Tok
.setKind(tok::identifier
);
287 Diag(Tok
, diag::ext_keyword_as_ident
)
288 << Tok
.getIdentifierInfo()->getName() << 0;
289 goto ParseIdentifier
;
293 return ParseExprStatement(StmtCtx
);
297 case tok::kw___attribute
: {
298 GNUAttributeLoc
= Tok
.getLocation();
299 ParseGNUAttributes(GNUAttrs
);
303 case tok::kw_template
: {
304 SourceLocation DeclEnd
;
305 ParsedAttributes
Attrs(AttrFactory
);
306 ParseTemplateDeclarationOrSpecialization(DeclaratorContext::Block
, DeclEnd
,
308 getAccessSpecifierIfPresent());
312 case tok::kw_case
: // C99 6.8.1: labeled-statement
313 return ParseCaseStatement(StmtCtx
);
314 case tok::kw_default
: // C99 6.8.1: labeled-statement
315 return ParseDefaultStatement(StmtCtx
);
317 case tok::l_brace
: // C99 6.8.2: compound-statement
318 return ParseCompoundStatement();
319 case tok::semi
: { // C99 6.8.3p3: expression[opt] ';'
320 bool HasLeadingEmptyMacro
= Tok
.hasLeadingEmptyMacro();
321 return Actions
.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro
);
324 case tok::kw_if
: // C99 6.8.4.1: if-statement
325 return ParseIfStatement(TrailingElseLoc
);
326 case tok::kw_switch
: // C99 6.8.4.2: switch-statement
327 return ParseSwitchStatement(TrailingElseLoc
);
329 case tok::kw_while
: // C99 6.8.5.1: while-statement
330 return ParseWhileStatement(TrailingElseLoc
);
331 case tok::kw_do
: // C99 6.8.5.2: do-statement
332 Res
= ParseDoStatement();
333 SemiError
= "do/while";
335 case tok::kw_for
: // C99 6.8.5.3: for-statement
336 return ParseForStatement(TrailingElseLoc
);
338 case tok::kw_goto
: // C99 6.8.6.1: goto-statement
339 Res
= ParseGotoStatement();
342 case tok::kw_continue
: // C99 6.8.6.2: continue-statement
343 Res
= ParseContinueStatement();
344 SemiError
= "continue";
346 case tok::kw_break
: // C99 6.8.6.3: break-statement
347 Res
= ParseBreakStatement();
350 case tok::kw_return
: // C99 6.8.6.4: return-statement
351 Res
= ParseReturnStatement();
352 SemiError
= "return";
354 case tok::kw_co_return
: // C++ Coroutines: co_return statement
355 Res
= ParseReturnStatement();
356 SemiError
= "co_return";
360 for (const ParsedAttr
&AL
: CXX11Attrs
)
361 // Could be relaxed if asm-related regular keyword attributes are
363 (AL
.isRegularKeywordAttribute()
364 ? Diag(AL
.getRange().getBegin(), diag::err_keyword_not_allowed
)
365 : Diag(AL
.getRange().getBegin(), diag::warn_attribute_ignored
))
367 // Prevent these from being interpreted as statement attributes later on.
369 ProhibitAttributes(GNUAttrs
);
371 Res
= ParseAsmStatement(msAsm
);
372 if (msAsm
) return Res
;
377 case tok::kw___if_exists
:
378 case tok::kw___if_not_exists
:
379 ProhibitAttributes(CXX11Attrs
);
380 ProhibitAttributes(GNUAttrs
);
381 ParseMicrosoftIfExistsStatement(Stmts
);
382 // An __if_exists block is like a compound statement, but it doesn't create
386 case tok::kw_try
: // C++ 15: try-block
387 return ParseCXXTryBlock();
390 ProhibitAttributes(CXX11Attrs
);
391 ProhibitAttributes(GNUAttrs
);
392 return ParseSEHTryBlock();
394 case tok::kw___leave
:
395 Res
= ParseSEHLeaveStatement();
396 SemiError
= "__leave";
399 case tok::annot_pragma_vis
:
400 ProhibitAttributes(CXX11Attrs
);
401 ProhibitAttributes(GNUAttrs
);
402 HandlePragmaVisibility();
405 case tok::annot_pragma_pack
:
406 ProhibitAttributes(CXX11Attrs
);
407 ProhibitAttributes(GNUAttrs
);
411 case tok::annot_pragma_msstruct
:
412 ProhibitAttributes(CXX11Attrs
);
413 ProhibitAttributes(GNUAttrs
);
414 HandlePragmaMSStruct();
417 case tok::annot_pragma_align
:
418 ProhibitAttributes(CXX11Attrs
);
419 ProhibitAttributes(GNUAttrs
);
423 case tok::annot_pragma_weak
:
424 ProhibitAttributes(CXX11Attrs
);
425 ProhibitAttributes(GNUAttrs
);
429 case tok::annot_pragma_weakalias
:
430 ProhibitAttributes(CXX11Attrs
);
431 ProhibitAttributes(GNUAttrs
);
432 HandlePragmaWeakAlias();
435 case tok::annot_pragma_redefine_extname
:
436 ProhibitAttributes(CXX11Attrs
);
437 ProhibitAttributes(GNUAttrs
);
438 HandlePragmaRedefineExtname();
441 case tok::annot_pragma_fp_contract
:
442 ProhibitAttributes(CXX11Attrs
);
443 ProhibitAttributes(GNUAttrs
);
444 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "fp_contract";
445 ConsumeAnnotationToken();
448 case tok::annot_pragma_fp
:
449 ProhibitAttributes(CXX11Attrs
);
450 ProhibitAttributes(GNUAttrs
);
451 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "clang fp";
452 ConsumeAnnotationToken();
455 case tok::annot_pragma_fenv_access
:
456 case tok::annot_pragma_fenv_access_ms
:
457 ProhibitAttributes(CXX11Attrs
);
458 ProhibitAttributes(GNUAttrs
);
459 Diag(Tok
, diag::err_pragma_file_or_compound_scope
)
460 << (Kind
== tok::annot_pragma_fenv_access
? "STDC FENV_ACCESS"
462 ConsumeAnnotationToken();
465 case tok::annot_pragma_fenv_round
:
466 ProhibitAttributes(CXX11Attrs
);
467 ProhibitAttributes(GNUAttrs
);
468 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "STDC FENV_ROUND";
469 ConsumeAnnotationToken();
472 case tok::annot_pragma_cx_limited_range
:
473 ProhibitAttributes(CXX11Attrs
);
474 ProhibitAttributes(GNUAttrs
);
475 Diag(Tok
, diag::err_pragma_file_or_compound_scope
)
476 << "STDC CX_LIMITED_RANGE";
477 ConsumeAnnotationToken();
480 case tok::annot_pragma_float_control
:
481 ProhibitAttributes(CXX11Attrs
);
482 ProhibitAttributes(GNUAttrs
);
483 Diag(Tok
, diag::err_pragma_file_or_compound_scope
) << "float_control";
484 ConsumeAnnotationToken();
487 case tok::annot_pragma_opencl_extension
:
488 ProhibitAttributes(CXX11Attrs
);
489 ProhibitAttributes(GNUAttrs
);
490 HandlePragmaOpenCLExtension();
493 case tok::annot_pragma_captured
:
494 ProhibitAttributes(CXX11Attrs
);
495 ProhibitAttributes(GNUAttrs
);
496 return HandlePragmaCaptured();
498 case tok::annot_pragma_openmp
:
499 // Prohibit attributes that are not OpenMP attributes, but only before
500 // processing a #pragma omp clause.
501 ProhibitAttributes(CXX11Attrs
);
502 ProhibitAttributes(GNUAttrs
);
504 case tok::annot_attr_openmp
:
505 // Do not prohibit attributes if they were OpenMP attributes.
506 return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx
);
508 case tok::annot_pragma_openacc
:
509 return ParseOpenACCDirectiveStmt();
511 case tok::annot_pragma_ms_pointers_to_members
:
512 ProhibitAttributes(CXX11Attrs
);
513 ProhibitAttributes(GNUAttrs
);
514 HandlePragmaMSPointersToMembers();
517 case tok::annot_pragma_ms_pragma
:
518 ProhibitAttributes(CXX11Attrs
);
519 ProhibitAttributes(GNUAttrs
);
520 HandlePragmaMSPragma();
523 case tok::annot_pragma_ms_vtordisp
:
524 ProhibitAttributes(CXX11Attrs
);
525 ProhibitAttributes(GNUAttrs
);
526 HandlePragmaMSVtorDisp();
529 case tok::annot_pragma_loop_hint
:
530 ProhibitAttributes(CXX11Attrs
);
531 ProhibitAttributes(GNUAttrs
);
532 return ParsePragmaLoopHint(Stmts
, StmtCtx
, TrailingElseLoc
, CXX11Attrs
);
534 case tok::annot_pragma_dump
:
538 case tok::annot_pragma_attribute
:
539 HandlePragmaAttribute();
543 // If we reached this code, the statement must end in a semicolon.
544 if (!TryConsumeToken(tok::semi
) && !Res
.isInvalid()) {
545 // If the result was valid, then we do want to diagnose this. Use
546 // ExpectAndConsume to emit the diagnostic, even though we know it won't
548 ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_stmt
, SemiError
);
549 // Skip until we see a } or ;, but don't eat it.
550 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
556 /// Parse an expression statement.
557 StmtResult
Parser::ParseExprStatement(ParsedStmtContext StmtCtx
) {
558 // If a case keyword is missing, this is where it should be inserted.
559 Token OldToken
= Tok
;
561 ExprStatementTokLoc
= Tok
.getLocation();
563 // expression[opt] ';'
564 ExprResult
Expr(ParseExpression());
565 if (Expr
.isInvalid()) {
566 // If the expression is invalid, skip ahead to the next semicolon or '}'.
567 // Not doing this opens us up to the possibility of infinite loops if
568 // ParseExpression does not consume any tokens.
569 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
570 if (Tok
.is(tok::semi
))
572 return Actions
.ActOnExprStmtError();
575 if (Tok
.is(tok::colon
) && getCurScope()->isSwitchScope() &&
576 Actions
.CheckCaseExpression(Expr
.get())) {
577 // If a constant expression is followed by a colon inside a switch block,
578 // suggest a missing case keyword.
579 Diag(OldToken
, diag::err_expected_case_before_expression
)
580 << FixItHint::CreateInsertion(OldToken
.getLocation(), "case ");
582 // Recover parsing as a case statement.
583 return ParseCaseStatement(StmtCtx
, /*MissingCase=*/true, Expr
);
586 Token
*CurTok
= nullptr;
587 // Note we shouldn't eat the token since the callback needs it.
588 if (Tok
.is(tok::annot_repl_input_end
))
591 // Otherwise, eat the semicolon.
592 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr
);
594 StmtResult R
= handleExprStmt(Expr
, StmtCtx
);
595 if (CurTok
&& !R
.isInvalid())
596 CurTok
->setAnnotationValue(R
.get());
601 /// ParseSEHTryBlockCommon
604 /// '__try' compound-statement seh-handler
608 /// seh-finally-block
610 StmtResult
Parser::ParseSEHTryBlock() {
611 assert(Tok
.is(tok::kw___try
) && "Expected '__try'");
612 SourceLocation TryLoc
= ConsumeToken();
614 if (Tok
.isNot(tok::l_brace
))
615 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
617 StmtResult
TryBlock(ParseCompoundStatement(
618 /*isStmtExpr=*/false,
619 Scope::DeclScope
| Scope::CompoundStmtScope
| Scope::SEHTryScope
));
620 if (TryBlock
.isInvalid())
624 if (Tok
.is(tok::identifier
) &&
625 Tok
.getIdentifierInfo() == getSEHExceptKeyword()) {
626 SourceLocation Loc
= ConsumeToken();
627 Handler
= ParseSEHExceptBlock(Loc
);
628 } else if (Tok
.is(tok::kw___finally
)) {
629 SourceLocation Loc
= ConsumeToken();
630 Handler
= ParseSEHFinallyBlock(Loc
);
632 return StmtError(Diag(Tok
, diag::err_seh_expected_handler
));
635 if(Handler
.isInvalid())
638 return Actions
.ActOnSEHTryBlock(false /* IsCXXTry */,
644 /// ParseSEHExceptBlock - Handle __except
646 /// seh-except-block:
647 /// '__except' '(' seh-filter-expression ')' compound-statement
649 StmtResult
Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc
) {
650 PoisonIdentifierRAIIObject
raii(Ident__exception_code
, false),
651 raii2(Ident___exception_code
, false),
652 raii3(Ident_GetExceptionCode
, false);
654 if (ExpectAndConsume(tok::l_paren
))
657 ParseScope
ExpectScope(this, Scope::DeclScope
| Scope::ControlScope
|
658 Scope::SEHExceptScope
);
660 if (getLangOpts().Borland
) {
661 Ident__exception_info
->setIsPoisoned(false);
662 Ident___exception_info
->setIsPoisoned(false);
663 Ident_GetExceptionInfo
->setIsPoisoned(false);
666 ExprResult FilterExpr
;
668 ParseScopeFlags
FilterScope(this, getCurScope()->getFlags() |
669 Scope::SEHFilterScope
);
670 FilterExpr
= Actions
.CorrectDelayedTyposInExpr(ParseExpression());
673 if (getLangOpts().Borland
) {
674 Ident__exception_info
->setIsPoisoned(true);
675 Ident___exception_info
->setIsPoisoned(true);
676 Ident_GetExceptionInfo
->setIsPoisoned(true);
679 if(FilterExpr
.isInvalid())
682 if (ExpectAndConsume(tok::r_paren
))
685 if (Tok
.isNot(tok::l_brace
))
686 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
688 StmtResult
Block(ParseCompoundStatement());
690 if(Block
.isInvalid())
693 return Actions
.ActOnSEHExceptBlock(ExceptLoc
, FilterExpr
.get(), Block
.get());
696 /// ParseSEHFinallyBlock - Handle __finally
698 /// seh-finally-block:
699 /// '__finally' compound-statement
701 StmtResult
Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc
) {
702 PoisonIdentifierRAIIObject
raii(Ident__abnormal_termination
, false),
703 raii2(Ident___abnormal_termination
, false),
704 raii3(Ident_AbnormalTermination
, false);
706 if (Tok
.isNot(tok::l_brace
))
707 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
709 ParseScope
FinallyScope(this, 0);
710 Actions
.ActOnStartSEHFinallyBlock();
712 StmtResult
Block(ParseCompoundStatement());
713 if(Block
.isInvalid()) {
714 Actions
.ActOnAbortSEHFinallyBlock();
718 return Actions
.ActOnFinishSEHFinallyBlock(FinallyLoc
, Block
.get());
723 /// seh-leave-statement:
726 StmtResult
Parser::ParseSEHLeaveStatement() {
727 SourceLocation LeaveLoc
= ConsumeToken(); // eat the '__leave'.
728 return Actions
.ActOnSEHLeaveStmt(LeaveLoc
, getCurScope());
731 static void DiagnoseLabelFollowedByDecl(Parser
&P
, const Stmt
*SubStmt
) {
732 // When in C mode (but not Microsoft extensions mode), diagnose use of a
733 // label that is followed by a declaration rather than a statement.
734 if (!P
.getLangOpts().CPlusPlus
&& !P
.getLangOpts().MicrosoftExt
&&
735 isa
<DeclStmt
>(SubStmt
)) {
736 P
.Diag(SubStmt
->getBeginLoc(),
738 ? diag::warn_c23_compat_label_followed_by_declaration
739 : diag::ext_c_label_followed_by_declaration
);
743 /// ParseLabeledStatement - We have an identifier and a ':' after it.
747 /// [GNU] identifier ':' attributes[opt]
749 /// labeled-statement:
752 StmtResult
Parser::ParseLabeledStatement(ParsedAttributes
&Attrs
,
753 ParsedStmtContext StmtCtx
) {
754 assert(Tok
.is(tok::identifier
) && Tok
.getIdentifierInfo() &&
755 "Not an identifier!");
757 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
758 // substatement in a selection statement, in place of the loop body in an
759 // iteration statement, or in place of the statement that follows a label.
760 StmtCtx
&= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives
;
762 Token IdentTok
= Tok
; // Save the whole token.
763 ConsumeToken(); // eat the identifier.
765 assert(Tok
.is(tok::colon
) && "Not a label!");
767 // identifier ':' statement
768 SourceLocation ColonLoc
= ConsumeToken();
770 // Read label attributes, if present.
772 if (Tok
.is(tok::kw___attribute
)) {
773 ParsedAttributes
TempAttrs(AttrFactory
);
774 ParseGNUAttributes(TempAttrs
);
776 // In C++, GNU attributes only apply to the label if they are followed by a
777 // semicolon, to disambiguate label attributes from attributes on a labeled
780 // This doesn't quite match what GCC does; if the attribute list is empty
781 // and followed by a semicolon, GCC will reject (it appears to parse the
782 // attributes as part of a statement in that case). That looks like a bug.
783 if (!getLangOpts().CPlusPlus
|| Tok
.is(tok::semi
))
784 Attrs
.takeAllFrom(TempAttrs
);
787 ParsedAttributes
EmptyCXX11Attrs(AttrFactory
);
788 SubStmt
= ParseStatementOrDeclarationAfterAttributes(
789 Stmts
, StmtCtx
, nullptr, EmptyCXX11Attrs
, TempAttrs
);
790 if (!TempAttrs
.empty() && !SubStmt
.isInvalid())
791 SubStmt
= Actions
.ActOnAttributedStmt(TempAttrs
, SubStmt
.get());
795 // The label may have no statement following it
796 if (SubStmt
.isUnset() && Tok
.is(tok::r_brace
)) {
797 DiagnoseLabelAtEndOfCompoundStatement();
798 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
801 // If we've not parsed a statement yet, parse one now.
802 if (SubStmt
.isUnset())
803 SubStmt
= ParseStatement(nullptr, StmtCtx
);
805 // Broken substmt shouldn't prevent the label from being added to the AST.
806 if (SubStmt
.isInvalid())
807 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
809 DiagnoseLabelFollowedByDecl(*this, SubStmt
.get());
811 LabelDecl
*LD
= Actions
.LookupOrCreateLabel(IdentTok
.getIdentifierInfo(),
812 IdentTok
.getLocation());
813 Actions
.ProcessDeclAttributeList(Actions
.CurScope
, LD
, Attrs
);
816 return Actions
.ActOnLabelStmt(IdentTok
.getLocation(), LD
, ColonLoc
,
820 /// ParseCaseStatement
821 /// labeled-statement:
822 /// 'case' constant-expression ':' statement
823 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
825 StmtResult
Parser::ParseCaseStatement(ParsedStmtContext StmtCtx
,
826 bool MissingCase
, ExprResult Expr
) {
827 assert((MissingCase
|| Tok
.is(tok::kw_case
)) && "Not a case stmt!");
829 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
830 // substatement in a selection statement, in place of the loop body in an
831 // iteration statement, or in place of the statement that follows a label.
832 StmtCtx
&= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives
;
834 // It is very common for code to contain many case statements recursively
835 // nested, as in (but usually without indentation):
842 // Parsing this naively works, but is both inefficient and can cause us to run
843 // out of stack space in our recursive descent parser. As a special case,
844 // flatten this recursion into an iterative loop. This is complex and gross,
845 // but all the grossness is constrained to ParseCaseStatement (and some
846 // weirdness in the actions), so this is just local grossness :).
848 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
850 StmtResult
TopLevelCase(true);
852 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
853 // gets updated each time a new case is parsed, and whose body is unset so
854 // far. When parsing 'case 4', this is the 'case 3' node.
855 Stmt
*DeepestParsedCaseStmt
= nullptr;
857 // While we have case statements, eat and stack them.
858 SourceLocation ColonLoc
;
860 SourceLocation CaseLoc
= MissingCase
? Expr
.get()->getExprLoc() :
861 ConsumeToken(); // eat the 'case'.
862 ColonLoc
= SourceLocation();
864 if (Tok
.is(tok::code_completion
)) {
866 Actions
.CodeCompletion().CodeCompleteCase(getCurScope());
870 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
871 /// Disable this form of error recovery while we're parsing the case
873 ColonProtectionRAIIObject
ColonProtection(*this);
877 LHS
= ParseCaseExpression(CaseLoc
);
878 if (LHS
.isInvalid()) {
879 // If constant-expression is parsed unsuccessfully, recover by skipping
880 // current case statement (moving to the colon that ends it).
881 if (!SkipUntil(tok::colon
, tok::r_brace
, StopAtSemi
| StopBeforeMatch
))
889 // GNU case range extension.
890 SourceLocation DotDotDotLoc
;
892 if (TryConsumeToken(tok::ellipsis
, DotDotDotLoc
)) {
893 // In C++, this is a GNU extension. In C, it's a C2y extension.
895 if (getLangOpts().CPlusPlus
)
896 DiagId
= diag::ext_gnu_case_range
;
897 else if (getLangOpts().C2y
)
898 DiagId
= diag::warn_c23_compat_case_range
;
900 DiagId
= diag::ext_c2y_case_range
;
901 Diag(DotDotDotLoc
, DiagId
);
902 RHS
= ParseCaseExpression(CaseLoc
);
903 if (RHS
.isInvalid()) {
904 if (!SkipUntil(tok::colon
, tok::r_brace
, StopAtSemi
| StopBeforeMatch
))
909 ColonProtection
.restore();
911 if (TryConsumeToken(tok::colon
, ColonLoc
)) {
912 } else if (TryConsumeToken(tok::semi
, ColonLoc
) ||
913 TryConsumeToken(tok::coloncolon
, ColonLoc
)) {
914 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
915 Diag(ColonLoc
, diag::err_expected_after
)
916 << "'case'" << tok::colon
917 << FixItHint::CreateReplacement(ColonLoc
, ":");
919 SourceLocation ExpectedLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
920 Diag(ExpectedLoc
, diag::err_expected_after
)
921 << "'case'" << tok::colon
922 << FixItHint::CreateInsertion(ExpectedLoc
, ":");
923 ColonLoc
= ExpectedLoc
;
927 Actions
.ActOnCaseStmt(CaseLoc
, LHS
, DotDotDotLoc
, RHS
, ColonLoc
);
929 // If we had a sema error parsing this case, then just ignore it and
930 // continue parsing the sub-stmt.
931 if (Case
.isInvalid()) {
932 if (TopLevelCase
.isInvalid()) // No parsed case stmts.
933 return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
934 // Otherwise, just don't add it as a nested case.
936 // If this is the first case statement we parsed, it becomes TopLevelCase.
937 // Otherwise we link it into the current chain.
938 Stmt
*NextDeepest
= Case
.get();
939 if (TopLevelCase
.isInvalid())
942 Actions
.ActOnCaseStmtBody(DeepestParsedCaseStmt
, Case
.get());
943 DeepestParsedCaseStmt
= NextDeepest
;
946 // Handle all case statements.
947 } while (Tok
.is(tok::kw_case
));
949 // If we found a non-case statement, start by parsing it.
952 if (Tok
.is(tok::r_brace
)) {
953 // "switch (X) { case 4: }", is valid and is treated as if label was
954 // followed by a null statement.
955 DiagnoseLabelAtEndOfCompoundStatement();
956 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
958 SubStmt
= ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
961 // Install the body into the most deeply-nested case.
962 if (DeepestParsedCaseStmt
) {
963 // Broken sub-stmt shouldn't prevent forming the case statement properly.
964 if (SubStmt
.isInvalid())
965 SubStmt
= Actions
.ActOnNullStmt(SourceLocation());
966 DiagnoseLabelFollowedByDecl(*this, SubStmt
.get());
967 Actions
.ActOnCaseStmtBody(DeepestParsedCaseStmt
, SubStmt
.get());
970 // Return the top level parsed statement tree.
974 /// ParseDefaultStatement
975 /// labeled-statement:
976 /// 'default' ':' statement
977 /// Note that this does not parse the 'statement' at the end.
979 StmtResult
Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx
) {
980 assert(Tok
.is(tok::kw_default
) && "Not a default stmt!");
982 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
983 // substatement in a selection statement, in place of the loop body in an
984 // iteration statement, or in place of the statement that follows a label.
985 StmtCtx
&= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives
;
987 SourceLocation DefaultLoc
= ConsumeToken(); // eat the 'default'.
989 SourceLocation ColonLoc
;
990 if (TryConsumeToken(tok::colon
, ColonLoc
)) {
991 } else if (TryConsumeToken(tok::semi
, ColonLoc
)) {
992 // Treat "default;" as a typo for "default:".
993 Diag(ColonLoc
, diag::err_expected_after
)
994 << "'default'" << tok::colon
995 << FixItHint::CreateReplacement(ColonLoc
, ":");
997 SourceLocation ExpectedLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
998 Diag(ExpectedLoc
, diag::err_expected_after
)
999 << "'default'" << tok::colon
1000 << FixItHint::CreateInsertion(ExpectedLoc
, ":");
1001 ColonLoc
= ExpectedLoc
;
1006 if (Tok
.is(tok::r_brace
)) {
1007 // "switch (X) {... default: }", is valid and is treated as if label was
1008 // followed by a null statement.
1009 DiagnoseLabelAtEndOfCompoundStatement();
1010 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
1012 SubStmt
= ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx
);
1015 // Broken sub-stmt shouldn't prevent forming the case statement properly.
1016 if (SubStmt
.isInvalid())
1017 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
1019 DiagnoseLabelFollowedByDecl(*this, SubStmt
.get());
1020 return Actions
.ActOnDefaultStmt(DefaultLoc
, ColonLoc
,
1021 SubStmt
.get(), getCurScope());
1024 StmtResult
Parser::ParseCompoundStatement(bool isStmtExpr
) {
1025 return ParseCompoundStatement(isStmtExpr
,
1026 Scope::DeclScope
| Scope::CompoundStmtScope
);
1029 /// ParseCompoundStatement - Parse a "{}" block.
1031 /// compound-statement: [C99 6.8.2]
1032 /// { block-item-list[opt] }
1033 /// [GNU] { label-declarations block-item-list } [TODO]
1035 /// block-item-list:
1037 /// block-item-list block-item
1041 /// [GNU] '__extension__' declaration
1044 /// [GNU] label-declarations:
1045 /// [GNU] label-declaration
1046 /// [GNU] label-declarations label-declaration
1048 /// [GNU] label-declaration:
1049 /// [GNU] '__label__' identifier-list ';'
1051 StmtResult
Parser::ParseCompoundStatement(bool isStmtExpr
,
1052 unsigned ScopeFlags
) {
1053 assert(Tok
.is(tok::l_brace
) && "Not a compound stmt!");
1055 // Enter a scope to hold everything within the compound stmt. Compound
1056 // statements can always hold declarations.
1057 ParseScope
CompoundScope(this, ScopeFlags
);
1059 // Parse the statements in the body.
1060 return ParseCompoundStatementBody(isStmtExpr
);
1063 /// Parse any pragmas at the start of the compound expression. We handle these
1064 /// separately since some pragmas (FP_CONTRACT) must appear before any C
1065 /// statement in the compound, but may be intermingled with other pragmas.
1066 void Parser::ParseCompoundStatementLeadingPragmas() {
1067 bool checkForPragmas
= true;
1068 while (checkForPragmas
) {
1069 switch (Tok
.getKind()) {
1070 case tok::annot_pragma_vis
:
1071 HandlePragmaVisibility();
1073 case tok::annot_pragma_pack
:
1076 case tok::annot_pragma_msstruct
:
1077 HandlePragmaMSStruct();
1079 case tok::annot_pragma_align
:
1080 HandlePragmaAlign();
1082 case tok::annot_pragma_weak
:
1085 case tok::annot_pragma_weakalias
:
1086 HandlePragmaWeakAlias();
1088 case tok::annot_pragma_redefine_extname
:
1089 HandlePragmaRedefineExtname();
1091 case tok::annot_pragma_opencl_extension
:
1092 HandlePragmaOpenCLExtension();
1094 case tok::annot_pragma_fp_contract
:
1095 HandlePragmaFPContract();
1097 case tok::annot_pragma_fp
:
1100 case tok::annot_pragma_fenv_access
:
1101 case tok::annot_pragma_fenv_access_ms
:
1102 HandlePragmaFEnvAccess();
1104 case tok::annot_pragma_fenv_round
:
1105 HandlePragmaFEnvRound();
1107 case tok::annot_pragma_cx_limited_range
:
1108 HandlePragmaCXLimitedRange();
1110 case tok::annot_pragma_float_control
:
1111 HandlePragmaFloatControl();
1113 case tok::annot_pragma_ms_pointers_to_members
:
1114 HandlePragmaMSPointersToMembers();
1116 case tok::annot_pragma_ms_pragma
:
1117 HandlePragmaMSPragma();
1119 case tok::annot_pragma_ms_vtordisp
:
1120 HandlePragmaMSVtorDisp();
1122 case tok::annot_pragma_dump
:
1126 checkForPragmas
= false;
1133 void Parser::DiagnoseLabelAtEndOfCompoundStatement() {
1134 if (getLangOpts().CPlusPlus
) {
1135 Diag(Tok
, getLangOpts().CPlusPlus23
1136 ? diag::warn_cxx20_compat_label_end_of_compound_statement
1137 : diag::ext_cxx_label_end_of_compound_statement
);
1139 Diag(Tok
, getLangOpts().C23
1140 ? diag::warn_c23_compat_label_end_of_compound_statement
1141 : diag::ext_c_label_end_of_compound_statement
);
1145 /// Consume any extra semi-colons resulting in null statements,
1146 /// returning true if any tok::semi were consumed.
1147 bool Parser::ConsumeNullStmt(StmtVector
&Stmts
) {
1148 if (!Tok
.is(tok::semi
))
1151 SourceLocation StartLoc
= Tok
.getLocation();
1152 SourceLocation EndLoc
;
1154 while (Tok
.is(tok::semi
) && !Tok
.hasLeadingEmptyMacro() &&
1155 Tok
.getLocation().isValid() && !Tok
.getLocation().isMacroID()) {
1156 EndLoc
= Tok
.getLocation();
1158 // Don't just ConsumeToken() this tok::semi, do store it in AST.
1160 ParseStatementOrDeclaration(Stmts
, ParsedStmtContext::SubStmt
);
1162 Stmts
.push_back(R
.get());
1165 // Did not consume any extra semi.
1166 if (EndLoc
.isInvalid())
1169 Diag(StartLoc
, diag::warn_null_statement
)
1170 << FixItHint::CreateRemoval(SourceRange(StartLoc
, EndLoc
));
1174 StmtResult
Parser::handleExprStmt(ExprResult E
, ParsedStmtContext StmtCtx
) {
1175 bool IsStmtExprResult
= false;
1176 if ((StmtCtx
& ParsedStmtContext::InStmtExpr
) != ParsedStmtContext()) {
1177 // For GCC compatibility we skip past NullStmts.
1178 unsigned LookAhead
= 0;
1179 while (GetLookAheadToken(LookAhead
).is(tok::semi
)) {
1182 // Then look to see if the next two tokens close the statement expression;
1183 // if so, this expression statement is the last statement in a statement
1185 IsStmtExprResult
= GetLookAheadToken(LookAhead
).is(tok::r_brace
) &&
1186 GetLookAheadToken(LookAhead
+ 1).is(tok::r_paren
);
1189 if (IsStmtExprResult
)
1190 E
= Actions
.ActOnStmtExprResult(E
);
1191 return Actions
.ActOnExprStmt(E
, /*DiscardedValue=*/!IsStmtExprResult
);
1194 /// ParseCompoundStatementBody - Parse a sequence of statements optionally
1195 /// followed by a label and invoke the ActOnCompoundStmt action. This expects
1196 /// the '{' to be the current token, and consume the '}' at the end of the
1197 /// block. It does not manipulate the scope stack.
1198 StmtResult
Parser::ParseCompoundStatementBody(bool isStmtExpr
) {
1199 PrettyStackTraceLoc
CrashInfo(PP
.getSourceManager(),
1201 "in compound statement ('{}')");
1203 // Record the current FPFeatures, restore on leaving the
1204 // compound statement.
1205 Sema::FPFeaturesStateRAII
SaveFPFeatures(Actions
);
1207 InMessageExpressionRAIIObject
InMessage(*this, false);
1208 BalancedDelimiterTracker
T(*this, tok::l_brace
);
1209 if (T
.consumeOpen())
1212 Sema::CompoundScopeRAII
CompoundScope(Actions
, isStmtExpr
);
1214 // Parse any pragmas at the beginning of the compound statement.
1215 ParseCompoundStatementLeadingPragmas();
1216 Actions
.ActOnAfterCompoundStatementLeadingPragmas();
1220 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1221 // only allowed at the start of a compound stmt regardless of the language.
1222 while (Tok
.is(tok::kw___label__
)) {
1223 SourceLocation LabelLoc
= ConsumeToken();
1225 SmallVector
<Decl
*, 8> DeclsInGroup
;
1227 if (Tok
.isNot(tok::identifier
)) {
1228 Diag(Tok
, diag::err_expected
) << tok::identifier
;
1232 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1233 SourceLocation IdLoc
= ConsumeToken();
1234 DeclsInGroup
.push_back(Actions
.LookupOrCreateLabel(II
, IdLoc
, LabelLoc
));
1236 if (!TryConsumeToken(tok::comma
))
1240 DeclSpec
DS(AttrFactory
);
1241 DeclGroupPtrTy Res
=
1242 Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
, DeclsInGroup
);
1243 StmtResult R
= Actions
.ActOnDeclStmt(Res
, LabelLoc
, Tok
.getLocation());
1245 ExpectAndConsumeSemi(diag::err_expected_semi_declaration
);
1247 Stmts
.push_back(R
.get());
1250 ParsedStmtContext SubStmtCtx
=
1251 ParsedStmtContext::Compound
|
1252 (isStmtExpr
? ParsedStmtContext::InStmtExpr
: ParsedStmtContext());
1254 bool LastIsError
= false;
1255 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
1256 Tok
.isNot(tok::eof
)) {
1257 if (Tok
.is(tok::annot_pragma_unused
)) {
1258 HandlePragmaUnused();
1262 if (ConsumeNullStmt(Stmts
))
1266 if (Tok
.isNot(tok::kw___extension__
)) {
1267 R
= ParseStatementOrDeclaration(Stmts
, SubStmtCtx
);
1269 // __extension__ can start declarations and it can also be a unary
1270 // operator for expressions. Consume multiple __extension__ markers here
1271 // until we can determine which is which.
1272 // FIXME: This loses extension expressions in the AST!
1273 SourceLocation ExtLoc
= ConsumeToken();
1274 while (Tok
.is(tok::kw___extension__
))
1277 ParsedAttributes
attrs(AttrFactory
);
1278 MaybeParseCXX11Attributes(attrs
, /*MightBeObjCMessageSend*/ true);
1280 // If this is the start of a declaration, parse it as such.
1281 if (isDeclarationStatement()) {
1282 // __extension__ silences extension warnings in the subdeclaration.
1283 // FIXME: Save the __extension__ on the decl as a node somehow?
1284 ExtensionRAIIObject
O(Diags
);
1286 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
1287 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
1288 DeclGroupPtrTy Res
= ParseDeclaration(DeclaratorContext::Block
, DeclEnd
,
1289 attrs
, DeclSpecAttrs
);
1290 R
= Actions
.ActOnDeclStmt(Res
, DeclStart
, DeclEnd
);
1292 // Otherwise this was a unary __extension__ marker.
1293 ExprResult
Res(ParseExpressionWithLeadingExtension(ExtLoc
));
1295 if (Res
.isInvalid()) {
1296 SkipUntil(tok::semi
);
1300 // Eat the semicolon at the end of stmt and convert the expr into a
1302 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr
);
1303 R
= handleExprStmt(Res
, SubStmtCtx
);
1305 R
= Actions
.ActOnAttributedStmt(attrs
, R
.get());
1310 Stmts
.push_back(R
.get());
1311 LastIsError
= R
.isInvalid();
1313 // StmtExpr needs to do copy initialization for last statement.
1314 // If last statement is invalid, the last statement in `Stmts` will be
1315 // incorrect. Then the whole compound statement should also be marked as
1316 // invalid to prevent subsequent errors.
1317 if (isStmtExpr
&& LastIsError
&& !Stmts
.empty())
1320 // Warn the user that using option `-ffp-eval-method=source` on a
1321 // 32-bit target and feature `sse` disabled, or using
1322 // `pragma clang fp eval_method=source` and feature `sse` disabled, is not
1324 if (!PP
.getTargetInfo().supportSourceEvalMethod() &&
1325 (PP
.getLastFPEvalPragmaLocation().isValid() ||
1326 PP
.getCurrentFPEvalMethod() ==
1327 LangOptions::FPEvalMethodKind::FEM_Source
))
1328 Diag(Tok
.getLocation(),
1329 diag::warn_no_support_for_eval_method_source_on_m32
);
1331 SourceLocation CloseLoc
= Tok
.getLocation();
1333 // We broke out of the while loop because we found a '}' or EOF.
1334 if (!T
.consumeClose()) {
1335 // If this is the '})' of a statement expression, check that it's written
1336 // in a sensible way.
1337 if (isStmtExpr
&& Tok
.is(tok::r_paren
))
1338 checkCompoundToken(CloseLoc
, tok::r_brace
, CompoundToken::StmtExprEnd
);
1340 // Recover by creating a compound statement with what we parsed so far,
1341 // instead of dropping everything and returning StmtError().
1344 if (T
.getCloseLocation().isValid())
1345 CloseLoc
= T
.getCloseLocation();
1347 return Actions
.ActOnCompoundStmt(T
.getOpenLocation(), CloseLoc
,
1351 /// ParseParenExprOrCondition:
1352 /// [C ] '(' expression ')'
1353 /// [C++] '(' condition ')'
1354 /// [C++1z] '(' init-statement[opt] condition ')'
1356 /// This function parses and performs error recovery on the specified condition
1357 /// or expression (depending on whether we're in C++ or C mode). This function
1358 /// goes out of its way to recover well. It returns true if there was a parser
1359 /// error (the right paren couldn't be found), which indicates that the caller
1360 /// should try to recover harder. It returns false if the condition is
1361 /// successfully parsed. Note that a successful parse can still have semantic
1362 /// errors in the condition.
1363 /// Additionally, it will assign the location of the outer-most '(' and ')',
1364 /// to LParenLoc and RParenLoc, respectively.
1365 bool Parser::ParseParenExprOrCondition(StmtResult
*InitStmt
,
1366 Sema::ConditionResult
&Cond
,
1368 Sema::ConditionKind CK
,
1369 SourceLocation
&LParenLoc
,
1370 SourceLocation
&RParenLoc
) {
1371 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1373 SourceLocation Start
= Tok
.getLocation();
1375 if (getLangOpts().CPlusPlus
) {
1376 Cond
= ParseCXXCondition(InitStmt
, Loc
, CK
, false);
1378 ExprResult CondExpr
= ParseExpression();
1380 // If required, convert to a boolean value.
1381 if (CondExpr
.isInvalid())
1382 Cond
= Sema::ConditionError();
1384 Cond
= Actions
.ActOnCondition(getCurScope(), Loc
, CondExpr
.get(), CK
,
1385 /*MissingOK=*/false);
1388 // If the parser was confused by the condition and we don't have a ')', try to
1389 // recover by skipping ahead to a semi and bailing out. If condexp is
1390 // semantically invalid but we have well formed code, keep going.
1391 if (Cond
.isInvalid() && Tok
.isNot(tok::r_paren
)) {
1392 SkipUntil(tok::semi
);
1393 // Skipping may have stopped if it found the containing ')'. If so, we can
1394 // continue parsing the if statement.
1395 if (Tok
.isNot(tok::r_paren
))
1399 if (Cond
.isInvalid()) {
1400 ExprResult CondExpr
= Actions
.CreateRecoveryExpr(
1401 Start
, Tok
.getLocation() == Start
? Start
: PrevTokLocation
, {},
1402 Actions
.PreferredConditionType(CK
));
1403 if (!CondExpr
.isInvalid())
1404 Cond
= Actions
.ActOnCondition(getCurScope(), Loc
, CondExpr
.get(), CK
,
1405 /*MissingOK=*/false);
1408 // Either the condition is valid or the rparen is present.
1410 LParenLoc
= T
.getOpenLocation();
1411 RParenLoc
= T
.getCloseLocation();
1413 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1414 // that all callers are looking for a statement after the condition, so ")"
1416 while (Tok
.is(tok::r_paren
)) {
1417 Diag(Tok
, diag::err_extraneous_rparen_in_condition
)
1418 << FixItHint::CreateRemoval(Tok
.getLocation());
1427 enum MisleadingStatementKind
{ MSK_if
, MSK_else
, MSK_for
, MSK_while
};
1429 struct MisleadingIndentationChecker
{
1431 SourceLocation StmtLoc
;
1432 SourceLocation PrevLoc
;
1433 unsigned NumDirectives
;
1434 MisleadingStatementKind Kind
;
1436 MisleadingIndentationChecker(Parser
&P
, MisleadingStatementKind K
,
1438 : P(P
), StmtLoc(SL
), PrevLoc(P
.getCurToken().getLocation()),
1439 NumDirectives(P
.getPreprocessor().getNumDirectives()), Kind(K
),
1440 ShouldSkip(P
.getCurToken().is(tok::l_brace
)) {
1441 if (!P
.MisleadingIndentationElseLoc
.isInvalid()) {
1442 StmtLoc
= P
.MisleadingIndentationElseLoc
;
1443 P
.MisleadingIndentationElseLoc
= SourceLocation();
1445 if (Kind
== MSK_else
&& !ShouldSkip
)
1446 P
.MisleadingIndentationElseLoc
= SL
;
1449 /// Compute the column number will aligning tabs on TabStop (-ftabstop), this
1450 /// gives the visual indentation of the SourceLocation.
1451 static unsigned getVisualIndentation(SourceManager
&SM
, SourceLocation Loc
) {
1452 unsigned TabStop
= SM
.getDiagnostics().getDiagnosticOptions().TabStop
;
1454 unsigned ColNo
= SM
.getSpellingColumnNumber(Loc
);
1455 if (ColNo
== 0 || TabStop
== 1)
1458 std::pair
<FileID
, unsigned> FIDAndOffset
= SM
.getDecomposedLoc(Loc
);
1461 StringRef BufData
= SM
.getBufferData(FIDAndOffset
.first
, &Invalid
);
1465 const char *EndPos
= BufData
.data() + FIDAndOffset
.second
;
1466 // FileOffset are 0-based and Column numbers are 1-based
1467 assert(FIDAndOffset
.second
+ 1 >= ColNo
&&
1468 "Column number smaller than file offset?");
1470 unsigned VisualColumn
= 0; // Stored as 0-based column, here.
1471 // Loop from beginning of line up to Loc's file position, counting columns,
1473 for (const char *CurPos
= EndPos
- (ColNo
- 1); CurPos
!= EndPos
;
1475 if (*CurPos
== '\t')
1476 // Advance visual column to next tabstop.
1477 VisualColumn
+= (TabStop
- VisualColumn
% TabStop
);
1481 return VisualColumn
+ 1;
1485 Token Tok
= P
.getCurToken();
1486 if (P
.getActions().getDiagnostics().isIgnored(
1487 diag::warn_misleading_indentation
, Tok
.getLocation()) ||
1488 ShouldSkip
|| NumDirectives
!= P
.getPreprocessor().getNumDirectives() ||
1489 Tok
.isOneOf(tok::semi
, tok::r_brace
) || Tok
.isAnnotation() ||
1490 Tok
.getLocation().isMacroID() || PrevLoc
.isMacroID() ||
1491 StmtLoc
.isMacroID() ||
1492 (Kind
== MSK_else
&& P
.MisleadingIndentationElseLoc
.isInvalid())) {
1493 P
.MisleadingIndentationElseLoc
= SourceLocation();
1496 if (Kind
== MSK_else
)
1497 P
.MisleadingIndentationElseLoc
= SourceLocation();
1499 SourceManager
&SM
= P
.getPreprocessor().getSourceManager();
1500 unsigned PrevColNum
= getVisualIndentation(SM
, PrevLoc
);
1501 unsigned CurColNum
= getVisualIndentation(SM
, Tok
.getLocation());
1502 unsigned StmtColNum
= getVisualIndentation(SM
, StmtLoc
);
1504 if (PrevColNum
!= 0 && CurColNum
!= 0 && StmtColNum
!= 0 &&
1505 ((PrevColNum
> StmtColNum
&& PrevColNum
== CurColNum
) ||
1506 !Tok
.isAtStartOfLine()) &&
1507 SM
.getPresumedLineNumber(StmtLoc
) !=
1508 SM
.getPresumedLineNumber(Tok
.getLocation()) &&
1509 (Tok
.isNot(tok::identifier
) ||
1510 P
.getPreprocessor().LookAhead(0).isNot(tok::colon
))) {
1511 P
.Diag(Tok
.getLocation(), diag::warn_misleading_indentation
) << Kind
;
1512 P
.Diag(StmtLoc
, diag::note_previous_statement
);
1519 /// ParseIfStatement
1520 /// if-statement: [C99 6.8.4.1]
1521 /// 'if' '(' expression ')' statement
1522 /// 'if' '(' expression ')' statement 'else' statement
1523 /// [C++] 'if' '(' condition ')' statement
1524 /// [C++] 'if' '(' condition ')' statement 'else' statement
1525 /// [C++23] 'if' '!' [opt] consteval compound-statement
1526 /// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement
1528 StmtResult
Parser::ParseIfStatement(SourceLocation
*TrailingElseLoc
) {
1529 assert(Tok
.is(tok::kw_if
) && "Not an if stmt!");
1530 SourceLocation IfLoc
= ConsumeToken(); // eat the 'if'.
1532 bool IsConstexpr
= false;
1533 bool IsConsteval
= false;
1534 SourceLocation NotLocation
;
1535 SourceLocation ConstevalLoc
;
1537 if (Tok
.is(tok::kw_constexpr
)) {
1538 // C23 supports constexpr keyword, but only for object definitions.
1539 if (getLangOpts().CPlusPlus
) {
1540 Diag(Tok
, getLangOpts().CPlusPlus17
? diag::warn_cxx14_compat_constexpr_if
1541 : diag::ext_constexpr_if
);
1546 if (Tok
.is(tok::exclaim
)) {
1547 NotLocation
= ConsumeToken();
1550 if (Tok
.is(tok::kw_consteval
)) {
1551 Diag(Tok
, getLangOpts().CPlusPlus23
? diag::warn_cxx20_compat_consteval_if
1552 : diag::ext_consteval_if
);
1554 ConstevalLoc
= ConsumeToken();
1557 if (!IsConsteval
&& (NotLocation
.isValid() || Tok
.isNot(tok::l_paren
))) {
1558 Diag(Tok
, diag::err_expected_lparen_after
) << "if";
1559 SkipUntil(tok::semi
);
1563 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1565 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1566 // the case for C90.
1569 // A name introduced by a declaration in a condition is in scope from its
1570 // point of declaration until the end of the substatements controlled by the
1573 // Names declared in the for-init-statement, and in the condition of if,
1574 // while, for, and switch statements are local to the if, while, for, or
1575 // switch statement (including the controlled statement).
1577 ParseScope
IfScope(this, Scope::DeclScope
| Scope::ControlScope
, C99orCXX
);
1579 // Parse the condition.
1580 StmtResult InitStmt
;
1581 Sema::ConditionResult Cond
;
1582 SourceLocation LParen
;
1583 SourceLocation RParen
;
1584 std::optional
<bool> ConstexprCondition
;
1587 if (ParseParenExprOrCondition(&InitStmt
, Cond
, IfLoc
,
1588 IsConstexpr
? Sema::ConditionKind::ConstexprIf
1589 : Sema::ConditionKind::Boolean
,
1594 ConstexprCondition
= Cond
.getKnownValue();
1597 bool IsBracedThen
= Tok
.is(tok::l_brace
);
1599 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1600 // there is no compound stmt. C90 does not have this clause. We only do this
1601 // if the body isn't a compound statement to avoid push/pop in common cases.
1604 // The substatement in a selection-statement (each substatement, in the else
1605 // form of the if statement) implicitly defines a local scope.
1607 // For C++ we create a scope for the condition and a new scope for
1608 // substatements because:
1609 // -When the 'then' scope exits, we want the condition declaration to still be
1610 // active for the 'else' scope too.
1611 // -Sema will detect name clashes by considering declarations of a
1612 // 'ControlScope' as part of its direct subscope.
1613 // -If we wanted the condition and substatement to be in the same scope, we
1614 // would have to notify ParseStatement not to create a new scope. It's
1615 // simpler to let it create a new scope.
1617 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, IsBracedThen
);
1619 MisleadingIndentationChecker
MIChecker(*this, MSK_if
, IfLoc
);
1621 // Read the 'then' stmt.
1622 SourceLocation ThenStmtLoc
= Tok
.getLocation();
1624 SourceLocation InnerStatementTrailingElseLoc
;
1625 StmtResult ThenStmt
;
1627 bool ShouldEnter
= ConstexprCondition
&& !*ConstexprCondition
;
1628 Sema::ExpressionEvaluationContext Context
=
1629 Sema::ExpressionEvaluationContext::DiscardedStatement
;
1630 if (NotLocation
.isInvalid() && IsConsteval
) {
1631 Context
= Sema::ExpressionEvaluationContext::ImmediateFunctionContext
;
1635 EnterExpressionEvaluationContext
PotentiallyDiscarded(
1636 Actions
, Context
, nullptr,
1637 Sema::ExpressionEvaluationContextRecord::EK_Other
, ShouldEnter
);
1638 ThenStmt
= ParseStatement(&InnerStatementTrailingElseLoc
);
1641 if (Tok
.isNot(tok::kw_else
))
1644 // Pop the 'if' scope if needed.
1647 // If it has an else, parse it.
1648 SourceLocation ElseLoc
;
1649 SourceLocation ElseStmtLoc
;
1650 StmtResult ElseStmt
;
1652 if (Tok
.is(tok::kw_else
)) {
1653 if (TrailingElseLoc
)
1654 *TrailingElseLoc
= Tok
.getLocation();
1656 ElseLoc
= ConsumeToken();
1657 ElseStmtLoc
= Tok
.getLocation();
1659 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1660 // there is no compound stmt. C90 does not have this clause. We only do
1661 // this if the body isn't a compound statement to avoid push/pop in common
1665 // The substatement in a selection-statement (each substatement, in the else
1666 // form of the if statement) implicitly defines a local scope.
1668 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
,
1669 Tok
.is(tok::l_brace
));
1671 MisleadingIndentationChecker
MIChecker(*this, MSK_else
, ElseLoc
);
1672 bool ShouldEnter
= ConstexprCondition
&& *ConstexprCondition
;
1673 Sema::ExpressionEvaluationContext Context
=
1674 Sema::ExpressionEvaluationContext::DiscardedStatement
;
1675 if (NotLocation
.isValid() && IsConsteval
) {
1676 Context
= Sema::ExpressionEvaluationContext::ImmediateFunctionContext
;
1680 EnterExpressionEvaluationContext
PotentiallyDiscarded(
1681 Actions
, Context
, nullptr,
1682 Sema::ExpressionEvaluationContextRecord::EK_Other
, ShouldEnter
);
1683 ElseStmt
= ParseStatement();
1685 if (ElseStmt
.isUsable())
1688 // Pop the 'else' scope if needed.
1690 } else if (Tok
.is(tok::code_completion
)) {
1692 Actions
.CodeCompletion().CodeCompleteAfterIf(getCurScope(), IsBracedThen
);
1694 } else if (InnerStatementTrailingElseLoc
.isValid()) {
1695 Diag(InnerStatementTrailingElseLoc
, diag::warn_dangling_else
);
1700 // If the then or else stmt is invalid and the other is valid (and present),
1701 // turn the invalid one into a null stmt to avoid dropping the other
1702 // part. If both are invalid, return error.
1703 if ((ThenStmt
.isInvalid() && ElseStmt
.isInvalid()) ||
1704 (ThenStmt
.isInvalid() && ElseStmt
.get() == nullptr) ||
1705 (ThenStmt
.get() == nullptr && ElseStmt
.isInvalid())) {
1706 // Both invalid, or one is invalid and other is non-present: return error.
1711 auto IsCompoundStatement
= [](const Stmt
*S
) {
1712 if (const auto *Outer
= dyn_cast_if_present
<AttributedStmt
>(S
))
1713 S
= Outer
->getSubStmt();
1714 return isa_and_nonnull
<clang::CompoundStmt
>(S
);
1717 if (!IsCompoundStatement(ThenStmt
.get())) {
1718 Diag(ConstevalLoc
, diag::err_expected_after
) << "consteval"
1722 if (!ElseStmt
.isUnset() && !IsCompoundStatement(ElseStmt
.get())) {
1723 Diag(ElseLoc
, diag::err_expected_after
) << "else"
1729 // Now if either are invalid, replace with a ';'.
1730 if (ThenStmt
.isInvalid())
1731 ThenStmt
= Actions
.ActOnNullStmt(ThenStmtLoc
);
1732 if (ElseStmt
.isInvalid())
1733 ElseStmt
= Actions
.ActOnNullStmt(ElseStmtLoc
);
1735 IfStatementKind Kind
= IfStatementKind::Ordinary
;
1737 Kind
= IfStatementKind::Constexpr
;
1738 else if (IsConsteval
)
1739 Kind
= NotLocation
.isValid() ? IfStatementKind::ConstevalNegated
1740 : IfStatementKind::ConstevalNonNegated
;
1742 return Actions
.ActOnIfStmt(IfLoc
, Kind
, LParen
, InitStmt
.get(), Cond
, RParen
,
1743 ThenStmt
.get(), ElseLoc
, ElseStmt
.get());
1746 /// ParseSwitchStatement
1747 /// switch-statement:
1748 /// 'switch' '(' expression ')' statement
1749 /// [C++] 'switch' '(' condition ')' statement
1750 StmtResult
Parser::ParseSwitchStatement(SourceLocation
*TrailingElseLoc
) {
1751 assert(Tok
.is(tok::kw_switch
) && "Not a switch stmt!");
1752 SourceLocation SwitchLoc
= ConsumeToken(); // eat the 'switch'.
1754 if (Tok
.isNot(tok::l_paren
)) {
1755 Diag(Tok
, diag::err_expected_lparen_after
) << "switch";
1756 SkipUntil(tok::semi
);
1760 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1762 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1763 // not the case for C90. Start the switch scope.
1766 // A name introduced by a declaration in a condition is in scope from its
1767 // point of declaration until the end of the substatements controlled by the
1770 // Names declared in the for-init-statement, and in the condition of if,
1771 // while, for, and switch statements are local to the if, while, for, or
1772 // switch statement (including the controlled statement).
1774 unsigned ScopeFlags
= Scope::SwitchScope
;
1776 ScopeFlags
|= Scope::DeclScope
| Scope::ControlScope
;
1777 ParseScope
SwitchScope(this, ScopeFlags
);
1779 // Parse the condition.
1780 StmtResult InitStmt
;
1781 Sema::ConditionResult Cond
;
1782 SourceLocation LParen
;
1783 SourceLocation RParen
;
1784 if (ParseParenExprOrCondition(&InitStmt
, Cond
, SwitchLoc
,
1785 Sema::ConditionKind::Switch
, LParen
, RParen
))
1788 StmtResult Switch
= Actions
.ActOnStartOfSwitchStmt(
1789 SwitchLoc
, LParen
, InitStmt
.get(), Cond
, RParen
);
1791 if (Switch
.isInvalid()) {
1792 // Skip the switch body.
1793 // FIXME: This is not optimal recovery, but parsing the body is more
1794 // dangerous due to the presence of case and default statements, which
1795 // will have no place to connect back with the switch.
1796 if (Tok
.is(tok::l_brace
)) {
1798 SkipUntil(tok::r_brace
);
1800 SkipUntil(tok::semi
);
1804 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1805 // there is no compound stmt. C90 does not have this clause. We only do this
1806 // if the body isn't a compound statement to avoid push/pop in common cases.
1809 // The substatement in a selection-statement (each substatement, in the else
1810 // form of the if statement) implicitly defines a local scope.
1812 // See comments in ParseIfStatement for why we create a scope for the
1813 // condition and a new scope for substatement in C++.
1815 getCurScope()->AddFlags(Scope::BreakScope
);
1816 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1818 // We have incremented the mangling number for the SwitchScope and the
1819 // InnerScope, which is one too many.
1821 getCurScope()->decrementMSManglingNumber();
1823 // Read the body statement.
1824 StmtResult
Body(ParseStatement(TrailingElseLoc
));
1830 return Actions
.ActOnFinishSwitchStmt(SwitchLoc
, Switch
.get(), Body
.get());
1833 /// ParseWhileStatement
1834 /// while-statement: [C99 6.8.5.1]
1835 /// 'while' '(' expression ')' statement
1836 /// [C++] 'while' '(' condition ')' statement
1837 StmtResult
Parser::ParseWhileStatement(SourceLocation
*TrailingElseLoc
) {
1838 assert(Tok
.is(tok::kw_while
) && "Not a while stmt!");
1839 SourceLocation WhileLoc
= Tok
.getLocation();
1840 ConsumeToken(); // eat the 'while'.
1842 if (Tok
.isNot(tok::l_paren
)) {
1843 Diag(Tok
, diag::err_expected_lparen_after
) << "while";
1844 SkipUntil(tok::semi
);
1848 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1850 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1851 // the case for C90. Start the loop scope.
1854 // A name introduced by a declaration in a condition is in scope from its
1855 // point of declaration until the end of the substatements controlled by the
1858 // Names declared in the for-init-statement, and in the condition of if,
1859 // while, for, and switch statements are local to the if, while, for, or
1860 // switch statement (including the controlled statement).
1862 unsigned ScopeFlags
;
1864 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
|
1865 Scope::DeclScope
| Scope::ControlScope
;
1867 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
1868 ParseScope
WhileScope(this, ScopeFlags
);
1870 // Parse the condition.
1871 Sema::ConditionResult Cond
;
1872 SourceLocation LParen
;
1873 SourceLocation RParen
;
1874 if (ParseParenExprOrCondition(nullptr, Cond
, WhileLoc
,
1875 Sema::ConditionKind::Boolean
, LParen
, RParen
))
1878 // OpenACC Restricts a while-loop inside of certain construct/clause
1879 // combinations, so diagnose that here in OpenACC mode.
1880 SemaOpenACC::LoopInConstructRAII LCR
{getActions().OpenACC()};
1881 getActions().OpenACC().ActOnWhileStmt(WhileLoc
);
1883 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1884 // there is no compound stmt. C90 does not have this clause. We only do this
1885 // if the body isn't a compound statement to avoid push/pop in common cases.
1888 // The substatement in an iteration-statement implicitly defines a local scope
1889 // which is entered and exited each time through the loop.
1891 // See comments in ParseIfStatement for why we create a scope for the
1892 // condition and a new scope for substatement in C++.
1894 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1896 MisleadingIndentationChecker
MIChecker(*this, MSK_while
, WhileLoc
);
1898 // Read the body statement.
1899 StmtResult
Body(ParseStatement(TrailingElseLoc
));
1901 if (Body
.isUsable())
1903 // Pop the body scope if needed.
1907 if (Cond
.isInvalid() || Body
.isInvalid())
1910 return Actions
.ActOnWhileStmt(WhileLoc
, LParen
, Cond
, RParen
, Body
.get());
1913 /// ParseDoStatement
1914 /// do-statement: [C99 6.8.5.2]
1915 /// 'do' statement 'while' '(' expression ')' ';'
1916 /// Note: this lets the caller parse the end ';'.
1917 StmtResult
Parser::ParseDoStatement() {
1918 assert(Tok
.is(tok::kw_do
) && "Not a do stmt!");
1919 SourceLocation DoLoc
= ConsumeToken(); // eat the 'do'.
1921 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1922 // the case for C90. Start the loop scope.
1923 unsigned ScopeFlags
;
1924 if (getLangOpts().C99
)
1925 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
| Scope::DeclScope
;
1927 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
1929 ParseScope
DoScope(this, ScopeFlags
);
1931 // OpenACC Restricts a do-while-loop inside of certain construct/clause
1932 // combinations, so diagnose that here in OpenACC mode.
1933 SemaOpenACC::LoopInConstructRAII LCR
{getActions().OpenACC()};
1934 getActions().OpenACC().ActOnDoStmt(DoLoc
);
1936 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1937 // there is no compound stmt. C90 does not have this clause. We only do this
1938 // if the body isn't a compound statement to avoid push/pop in common cases.
1941 // The substatement in an iteration-statement implicitly defines a local scope
1942 // which is entered and exited each time through the loop.
1944 bool C99orCXX
= getLangOpts().C99
|| getLangOpts().CPlusPlus
;
1945 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXX
, Tok
.is(tok::l_brace
));
1947 // Read the body statement.
1948 StmtResult
Body(ParseStatement());
1950 // Pop the body scope if needed.
1953 if (Tok
.isNot(tok::kw_while
)) {
1954 if (!Body
.isInvalid()) {
1955 Diag(Tok
, diag::err_expected_while
);
1956 Diag(DoLoc
, diag::note_matching
) << "'do'";
1957 SkipUntil(tok::semi
, StopBeforeMatch
);
1961 SourceLocation WhileLoc
= ConsumeToken();
1963 if (Tok
.isNot(tok::l_paren
)) {
1964 Diag(Tok
, diag::err_expected_lparen_after
) << "do/while";
1965 SkipUntil(tok::semi
, StopBeforeMatch
);
1969 // Parse the parenthesized expression.
1970 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1973 // A do-while expression is not a condition, so can't have attributes.
1974 DiagnoseAndSkipCXX11Attributes();
1976 SourceLocation Start
= Tok
.getLocation();
1977 ExprResult Cond
= ParseExpression();
1978 // Correct the typos in condition before closing the scope.
1979 if (Cond
.isUsable())
1980 Cond
= Actions
.CorrectDelayedTyposInExpr(Cond
, /*InitDecl=*/nullptr,
1981 /*RecoverUncorrectedTypos=*/true);
1983 if (!Tok
.isOneOf(tok::r_paren
, tok::r_square
, tok::r_brace
))
1984 SkipUntil(tok::semi
);
1985 Cond
= Actions
.CreateRecoveryExpr(
1986 Start
, Start
== Tok
.getLocation() ? Start
: PrevTokLocation
, {},
1987 Actions
.getASTContext().BoolTy
);
1992 if (Cond
.isInvalid() || Body
.isInvalid())
1995 return Actions
.ActOnDoStmt(DoLoc
, Body
.get(), WhileLoc
, T
.getOpenLocation(),
1996 Cond
.get(), T
.getCloseLocation());
1999 bool Parser::isForRangeIdentifier() {
2000 assert(Tok
.is(tok::identifier
));
2002 const Token
&Next
= NextToken();
2003 if (Next
.is(tok::colon
))
2006 if (Next
.isOneOf(tok::l_square
, tok::kw_alignas
)) {
2007 TentativeParsingAction
PA(*this);
2009 SkipCXX11Attributes();
2010 bool Result
= Tok
.is(tok::colon
);
2018 /// ParseForStatement
2019 /// for-statement: [C99 6.8.5.3]
2020 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
2021 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
2022 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
2025 /// 'co_await'[opt] [Coroutines]
2026 /// '(' for-range-declaration ':' for-range-initializer ')'
2028 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
2029 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
2031 /// [C++] for-init-statement:
2032 /// [C++] expression-statement
2033 /// [C++] simple-declaration
2034 /// [C++23] alias-declaration
2036 /// [C++0x] for-range-declaration:
2037 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
2038 /// [C++0x] for-range-initializer:
2039 /// [C++0x] expression
2040 /// [C++0x] braced-init-list [TODO]
2041 StmtResult
Parser::ParseForStatement(SourceLocation
*TrailingElseLoc
) {
2042 assert(Tok
.is(tok::kw_for
) && "Not a for stmt!");
2043 SourceLocation ForLoc
= ConsumeToken(); // eat the 'for'.
2045 SourceLocation CoawaitLoc
;
2046 if (Tok
.is(tok::kw_co_await
))
2047 CoawaitLoc
= ConsumeToken();
2049 if (Tok
.isNot(tok::l_paren
)) {
2050 Diag(Tok
, diag::err_expected_lparen_after
) << "for";
2051 SkipUntil(tok::semi
);
2055 bool C99orCXXorObjC
= getLangOpts().C99
|| getLangOpts().CPlusPlus
||
2058 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
2059 // the case for C90. Start the loop scope.
2062 // A name introduced by a declaration in a condition is in scope from its
2063 // point of declaration until the end of the substatements controlled by the
2066 // Names declared in the for-init-statement, and in the condition of if,
2067 // while, for, and switch statements are local to the if, while, for, or
2068 // switch statement (including the controlled statement).
2070 // Names declared in the for-init-statement are in the same declarative-region
2071 // as those declared in the condition.
2073 unsigned ScopeFlags
= 0;
2075 ScopeFlags
= Scope::DeclScope
| Scope::ControlScope
;
2077 ParseScope
ForScope(this, ScopeFlags
);
2079 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2084 bool ForEach
= false;
2085 StmtResult FirstPart
;
2086 Sema::ConditionResult SecondPart
;
2087 ExprResult Collection
;
2088 ForRangeInfo ForRangeInfo
;
2089 FullExprArg
ThirdPart(Actions
);
2091 if (Tok
.is(tok::code_completion
)) {
2093 Actions
.CodeCompletion().CodeCompleteOrdinaryName(
2094 getCurScope(), C99orCXXorObjC
? SemaCodeCompletion::PCC_ForInit
2095 : SemaCodeCompletion::PCC_Expression
);
2099 ParsedAttributes
attrs(AttrFactory
);
2100 MaybeParseCXX11Attributes(attrs
);
2102 SourceLocation EmptyInitStmtSemiLoc
;
2104 // Parse the first part of the for specifier.
2105 if (Tok
.is(tok::semi
)) { // for (;
2106 ProhibitAttributes(attrs
);
2107 // no first part, eat the ';'.
2108 SourceLocation SemiLoc
= Tok
.getLocation();
2109 if (!Tok
.hasLeadingEmptyMacro() && !SemiLoc
.isMacroID())
2110 EmptyInitStmtSemiLoc
= SemiLoc
;
2112 } else if (getLangOpts().CPlusPlus
&& Tok
.is(tok::identifier
) &&
2113 isForRangeIdentifier()) {
2114 ProhibitAttributes(attrs
);
2115 IdentifierInfo
*Name
= Tok
.getIdentifierInfo();
2116 SourceLocation Loc
= ConsumeToken();
2117 MaybeParseCXX11Attributes(attrs
);
2119 ForRangeInfo
.ColonLoc
= ConsumeToken();
2120 if (Tok
.is(tok::l_brace
))
2121 ForRangeInfo
.RangeExpr
= ParseBraceInitializer();
2123 ForRangeInfo
.RangeExpr
= ParseExpression();
2125 Diag(Loc
, diag::err_for_range_identifier
)
2126 << ((getLangOpts().CPlusPlus11
&& !getLangOpts().CPlusPlus17
)
2127 ? FixItHint::CreateInsertion(Loc
, "auto &&")
2130 ForRangeInfo
.LoopVar
=
2131 Actions
.ActOnCXXForRangeIdentifier(getCurScope(), Loc
, Name
, attrs
);
2132 } else if (isForInitDeclaration()) { // for (int X = 4;
2133 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
2135 // Parse declaration, which eats the ';'.
2136 if (!C99orCXXorObjC
) { // Use of C99-style for loops in C90 mode?
2137 Diag(Tok
, diag::ext_c99_variable_decl_in_for_loop
);
2138 Diag(Tok
, diag::warn_gcc_variable_decl_in_for_loop
);
2141 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
2142 if (Tok
.is(tok::kw_using
)) {
2143 DG
= ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit
,
2145 FirstPart
= Actions
.ActOnDeclStmt(DG
, DeclStart
, Tok
.getLocation());
2147 // In C++0x, "for (T NS:a" might not be a typo for ::
2148 bool MightBeForRangeStmt
= getLangOpts().CPlusPlus
;
2149 ColonProtectionRAIIObject
ColonProtection(*this, MightBeForRangeStmt
);
2150 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
2151 DG
= ParseSimpleDeclaration(
2152 DeclaratorContext::ForInit
, DeclEnd
, attrs
, DeclSpecAttrs
, false,
2153 MightBeForRangeStmt
? &ForRangeInfo
: nullptr);
2154 FirstPart
= Actions
.ActOnDeclStmt(DG
, DeclStart
, Tok
.getLocation());
2155 if (ForRangeInfo
.ParsedForRangeDecl()) {
2156 Diag(ForRangeInfo
.ColonLoc
, getLangOpts().CPlusPlus11
2157 ? diag::warn_cxx98_compat_for_range
2158 : diag::ext_for_range
);
2159 ForRangeInfo
.LoopVar
= FirstPart
;
2160 FirstPart
= StmtResult();
2161 } else if (Tok
.is(tok::semi
)) { // for (int x = 4;
2163 } else if ((ForEach
= isTokIdentifier_in())) {
2164 Actions
.ActOnForEachDeclStmt(DG
);
2165 // ObjC: for (id x in expr)
2166 ConsumeToken(); // consume 'in'
2168 if (Tok
.is(tok::code_completion
)) {
2170 Actions
.CodeCompletion().CodeCompleteObjCForCollection(getCurScope(),
2174 Collection
= ParseExpression();
2176 Diag(Tok
, diag::err_expected_semi_for
);
2180 ProhibitAttributes(attrs
);
2181 Value
= Actions
.CorrectDelayedTyposInExpr(ParseExpression());
2183 ForEach
= isTokIdentifier_in();
2185 // Turn the expression into a stmt.
2186 if (!Value
.isInvalid()) {
2188 FirstPart
= Actions
.ActOnForEachLValueExpr(Value
.get());
2190 // We already know this is not an init-statement within a for loop, so
2191 // if we are parsing a C++11 range-based for loop, we should treat this
2192 // expression statement as being a discarded value expression because
2193 // we will err below. This way we do not warn on an unused expression
2194 // that was an error in the first place, like with: for (expr : expr);
2195 bool IsRangeBasedFor
=
2196 getLangOpts().CPlusPlus11
&& !ForEach
&& Tok
.is(tok::colon
);
2197 FirstPart
= Actions
.ActOnExprStmt(Value
, !IsRangeBasedFor
);
2201 if (Tok
.is(tok::semi
)) {
2203 } else if (ForEach
) {
2204 ConsumeToken(); // consume 'in'
2206 if (Tok
.is(tok::code_completion
)) {
2208 Actions
.CodeCompletion().CodeCompleteObjCForCollection(getCurScope(),
2212 Collection
= ParseExpression();
2213 } else if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::colon
) && FirstPart
.get()) {
2214 // User tried to write the reasonable, but ill-formed, for-range-statement
2215 // for (expr : expr) { ... }
2216 Diag(Tok
, diag::err_for_range_expected_decl
)
2217 << FirstPart
.get()->getSourceRange();
2218 SkipUntil(tok::r_paren
, StopBeforeMatch
);
2219 SecondPart
= Sema::ConditionError();
2221 if (!Value
.isInvalid()) {
2222 Diag(Tok
, diag::err_expected_semi_for
);
2224 // Skip until semicolon or rparen, don't consume it.
2225 SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
);
2226 if (Tok
.is(tok::semi
))
2232 // Parse the second part of the for specifier.
2233 if (!ForEach
&& !ForRangeInfo
.ParsedForRangeDecl() &&
2234 !SecondPart
.isInvalid()) {
2235 // Parse the second part of the for specifier.
2236 if (Tok
.is(tok::semi
)) { // for (...;;
2238 } else if (Tok
.is(tok::r_paren
)) {
2239 // missing both semicolons.
2241 if (getLangOpts().CPlusPlus
) {
2242 // C++2a: We've parsed an init-statement; we might have a
2243 // for-range-declaration next.
2244 bool MightBeForRangeStmt
= !ForRangeInfo
.ParsedForRangeDecl();
2245 ColonProtectionRAIIObject
ColonProtection(*this, MightBeForRangeStmt
);
2246 SourceLocation SecondPartStart
= Tok
.getLocation();
2247 Sema::ConditionKind CK
= Sema::ConditionKind::Boolean
;
2248 SecondPart
= ParseCXXCondition(
2249 /*InitStmt=*/nullptr, ForLoc
, CK
,
2250 // FIXME: recovery if we don't see another semi!
2251 /*MissingOK=*/true, MightBeForRangeStmt
? &ForRangeInfo
: nullptr,
2252 /*EnterForConditionScope=*/true);
2254 if (ForRangeInfo
.ParsedForRangeDecl()) {
2255 Diag(FirstPart
.get() ? FirstPart
.get()->getBeginLoc()
2256 : ForRangeInfo
.ColonLoc
,
2257 getLangOpts().CPlusPlus20
2258 ? diag::warn_cxx17_compat_for_range_init_stmt
2259 : diag::ext_for_range_init_stmt
)
2260 << (FirstPart
.get() ? FirstPart
.get()->getSourceRange()
2262 if (EmptyInitStmtSemiLoc
.isValid()) {
2263 Diag(EmptyInitStmtSemiLoc
, diag::warn_empty_init_statement
)
2265 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc
);
2269 if (SecondPart
.isInvalid()) {
2270 ExprResult CondExpr
= Actions
.CreateRecoveryExpr(
2272 Tok
.getLocation() == SecondPartStart
? SecondPartStart
2274 {}, Actions
.PreferredConditionType(CK
));
2275 if (!CondExpr
.isInvalid())
2276 SecondPart
= Actions
.ActOnCondition(getCurScope(), ForLoc
,
2278 /*MissingOK=*/false);
2282 // We permit 'continue' and 'break' in the condition of a for loop.
2283 getCurScope()->AddFlags(Scope::BreakScope
| Scope::ContinueScope
);
2285 ExprResult SecondExpr
= ParseExpression();
2286 if (SecondExpr
.isInvalid())
2287 SecondPart
= Sema::ConditionError();
2289 SecondPart
= Actions
.ActOnCondition(
2290 getCurScope(), ForLoc
, SecondExpr
.get(),
2291 Sema::ConditionKind::Boolean
, /*MissingOK=*/true);
2296 // Enter a break / continue scope, if we didn't already enter one while
2297 // parsing the second part.
2298 if (!getCurScope()->isContinueScope())
2299 getCurScope()->AddFlags(Scope::BreakScope
| Scope::ContinueScope
);
2301 // Parse the third part of the for statement.
2302 if (!ForEach
&& !ForRangeInfo
.ParsedForRangeDecl()) {
2303 if (Tok
.isNot(tok::semi
)) {
2304 if (!SecondPart
.isInvalid())
2305 Diag(Tok
, diag::err_expected_semi_for
);
2306 SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
);
2309 if (Tok
.is(tok::semi
)) {
2313 if (Tok
.isNot(tok::r_paren
)) { // for (...;...;)
2314 ExprResult Third
= ParseExpression();
2315 // FIXME: The C++11 standard doesn't actually say that this is a
2316 // discarded-value expression, but it clearly should be.
2317 ThirdPart
= Actions
.MakeFullDiscardedValueExpr(Third
.get());
2323 // C++ Coroutines [stmt.iter]:
2324 // 'co_await' can only be used for a range-based for statement.
2325 if (CoawaitLoc
.isValid() && !ForRangeInfo
.ParsedForRangeDecl()) {
2326 Diag(CoawaitLoc
, diag::err_for_co_await_not_range_for
);
2327 CoawaitLoc
= SourceLocation();
2330 if (CoawaitLoc
.isValid() && getLangOpts().CPlusPlus20
)
2331 Diag(CoawaitLoc
, diag::warn_deprecated_for_co_await
);
2333 // We need to perform most of the semantic analysis for a C++0x for-range
2334 // statememt before parsing the body, in order to be able to deduce the type
2335 // of an auto-typed loop variable.
2336 StmtResult ForRangeStmt
;
2337 StmtResult ForEachStmt
;
2339 if (ForRangeInfo
.ParsedForRangeDecl()) {
2340 ExprResult CorrectedRange
=
2341 Actions
.CorrectDelayedTyposInExpr(ForRangeInfo
.RangeExpr
.get());
2342 ForRangeStmt
= Actions
.ActOnCXXForRangeStmt(
2343 getCurScope(), ForLoc
, CoawaitLoc
, FirstPart
.get(),
2344 ForRangeInfo
.LoopVar
.get(), ForRangeInfo
.ColonLoc
, CorrectedRange
.get(),
2345 T
.getCloseLocation(), Sema::BFRK_Build
,
2346 ForRangeInfo
.LifetimeExtendTemps
);
2347 } else if (ForEach
) {
2348 // Similarly, we need to do the semantic analysis for a for-range
2349 // statement immediately in order to close over temporaries correctly.
2350 ForEachStmt
= Actions
.ObjC().ActOnObjCForCollectionStmt(
2351 ForLoc
, FirstPart
.get(), Collection
.get(), T
.getCloseLocation());
2353 // In OpenMP loop region loop control variable must be captured and be
2354 // private. Perform analysis of first part (if any).
2355 if (getLangOpts().OpenMP
&& FirstPart
.isUsable()) {
2356 Actions
.OpenMP().ActOnOpenMPLoopInitialization(ForLoc
, FirstPart
.get());
2360 // OpenACC Restricts a for-loop inside of certain construct/clause
2361 // combinations, so diagnose that here in OpenACC mode.
2362 SemaOpenACC::LoopInConstructRAII LCR
{getActions().OpenACC()};
2363 if (ForRangeInfo
.ParsedForRangeDecl())
2364 getActions().OpenACC().ActOnRangeForStmtBegin(ForLoc
, ForRangeStmt
.get());
2366 getActions().OpenACC().ActOnForStmtBegin(
2367 ForLoc
, FirstPart
.get(), SecondPart
.get().second
, ThirdPart
.get());
2369 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2370 // there is no compound stmt. C90 does not have this clause. We only do this
2371 // if the body isn't a compound statement to avoid push/pop in common cases.
2374 // The substatement in an iteration-statement implicitly defines a local scope
2375 // which is entered and exited each time through the loop.
2377 // See comments in ParseIfStatement for why we create a scope for
2378 // for-init-statement/condition and a new scope for substatement in C++.
2380 ParseScope
InnerScope(this, Scope::DeclScope
, C99orCXXorObjC
,
2381 Tok
.is(tok::l_brace
));
2383 // The body of the for loop has the same local mangling number as the
2384 // for-init-statement.
2385 // It will only be incremented if the body contains other things that would
2386 // normally increment the mangling number (like a compound statement).
2388 getCurScope()->decrementMSManglingNumber();
2390 MisleadingIndentationChecker
MIChecker(*this, MSK_for
, ForLoc
);
2392 // Read the body statement.
2393 StmtResult
Body(ParseStatement(TrailingElseLoc
));
2395 if (Body
.isUsable())
2398 // Pop the body scope if needed.
2401 getActions().OpenACC().ActOnForStmtEnd(ForLoc
, Body
);
2403 // Leave the for-scope.
2406 if (Body
.isInvalid())
2410 return Actions
.ObjC().FinishObjCForCollectionStmt(ForEachStmt
.get(),
2413 if (ForRangeInfo
.ParsedForRangeDecl())
2414 return Actions
.FinishCXXForRangeStmt(ForRangeStmt
.get(), Body
.get());
2416 return Actions
.ActOnForStmt(ForLoc
, T
.getOpenLocation(), FirstPart
.get(),
2417 SecondPart
, ThirdPart
, T
.getCloseLocation(),
2421 /// ParseGotoStatement
2423 /// 'goto' identifier ';'
2424 /// [GNU] 'goto' '*' expression ';'
2426 /// Note: this lets the caller parse the end ';'.
2428 StmtResult
Parser::ParseGotoStatement() {
2429 assert(Tok
.is(tok::kw_goto
) && "Not a goto stmt!");
2430 SourceLocation GotoLoc
= ConsumeToken(); // eat the 'goto'.
2433 if (Tok
.is(tok::identifier
)) {
2434 LabelDecl
*LD
= Actions
.LookupOrCreateLabel(Tok
.getIdentifierInfo(),
2436 Res
= Actions
.ActOnGotoStmt(GotoLoc
, Tok
.getLocation(), LD
);
2438 } else if (Tok
.is(tok::star
)) {
2439 // GNU indirect goto extension.
2440 Diag(Tok
, diag::ext_gnu_indirect_goto
);
2441 SourceLocation StarLoc
= ConsumeToken();
2442 ExprResult
R(ParseExpression());
2443 if (R
.isInvalid()) { // Skip to the semicolon, but don't consume it.
2444 SkipUntil(tok::semi
, StopBeforeMatch
);
2447 Res
= Actions
.ActOnIndirectGotoStmt(GotoLoc
, StarLoc
, R
.get());
2449 Diag(Tok
, diag::err_expected
) << tok::identifier
;
2456 /// ParseContinueStatement
2460 /// Note: this lets the caller parse the end ';'.
2462 StmtResult
Parser::ParseContinueStatement() {
2463 SourceLocation ContinueLoc
= ConsumeToken(); // eat the 'continue'.
2464 return Actions
.ActOnContinueStmt(ContinueLoc
, getCurScope());
2467 /// ParseBreakStatement
2471 /// Note: this lets the caller parse the end ';'.
2473 StmtResult
Parser::ParseBreakStatement() {
2474 SourceLocation BreakLoc
= ConsumeToken(); // eat the 'break'.
2475 return Actions
.ActOnBreakStmt(BreakLoc
, getCurScope());
2478 /// ParseReturnStatement
2480 /// 'return' expression[opt] ';'
2481 /// 'return' braced-init-list ';'
2482 /// 'co_return' expression[opt] ';'
2483 /// 'co_return' braced-init-list ';'
2484 StmtResult
Parser::ParseReturnStatement() {
2485 assert((Tok
.is(tok::kw_return
) || Tok
.is(tok::kw_co_return
)) &&
2486 "Not a return stmt!");
2487 bool IsCoreturn
= Tok
.is(tok::kw_co_return
);
2488 SourceLocation ReturnLoc
= ConsumeToken(); // eat the 'return'.
2491 if (Tok
.isNot(tok::semi
)) {
2493 PreferredType
.enterReturn(Actions
, Tok
.getLocation());
2494 // FIXME: Code completion for co_return.
2495 if (Tok
.is(tok::code_completion
) && !IsCoreturn
) {
2497 Actions
.CodeCompletion().CodeCompleteExpression(
2498 getCurScope(), PreferredType
.get(Tok
.getLocation()));
2502 if (Tok
.is(tok::l_brace
) && getLangOpts().CPlusPlus
) {
2503 R
= ParseInitializer();
2505 Diag(R
.get()->getBeginLoc(),
2506 getLangOpts().CPlusPlus11
2507 ? diag::warn_cxx98_compat_generalized_initializer_lists
2508 : diag::ext_generalized_initializer_lists
)
2509 << R
.get()->getSourceRange();
2511 R
= ParseExpression();
2512 if (R
.isInvalid()) {
2513 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
2518 return Actions
.ActOnCoreturnStmt(getCurScope(), ReturnLoc
, R
.get());
2519 return Actions
.ActOnReturnStmt(ReturnLoc
, R
.get(), getCurScope());
2522 StmtResult
Parser::ParsePragmaLoopHint(StmtVector
&Stmts
,
2523 ParsedStmtContext StmtCtx
,
2524 SourceLocation
*TrailingElseLoc
,
2525 ParsedAttributes
&Attrs
) {
2526 // Create temporary attribute list.
2527 ParsedAttributes
TempAttrs(AttrFactory
);
2529 SourceLocation StartLoc
= Tok
.getLocation();
2531 // Get loop hints and consume annotated token.
2532 while (Tok
.is(tok::annot_pragma_loop_hint
)) {
2534 if (!HandlePragmaLoopHint(Hint
))
2537 ArgsUnion ArgHints
[] = {Hint
.PragmaNameLoc
, Hint
.OptionLoc
, Hint
.StateLoc
,
2538 ArgsUnion(Hint
.ValueExpr
)};
2539 TempAttrs
.addNew(Hint
.PragmaNameLoc
->Ident
, Hint
.Range
, nullptr,
2540 Hint
.PragmaNameLoc
->Loc
, ArgHints
, 4,
2541 ParsedAttr::Form::Pragma());
2544 // Get the next statement.
2545 MaybeParseCXX11Attributes(Attrs
);
2547 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
2548 StmtResult S
= ParseStatementOrDeclarationAfterAttributes(
2549 Stmts
, StmtCtx
, TrailingElseLoc
, Attrs
, EmptyDeclSpecAttrs
);
2551 Attrs
.takeAllFrom(TempAttrs
);
2553 // Start of attribute range may already be set for some invalid input.
2555 if (Attrs
.Range
.getBegin().isInvalid())
2556 Attrs
.Range
.setBegin(StartLoc
);
2561 Decl
*Parser::ParseFunctionStatementBody(Decl
*Decl
, ParseScope
&BodyScope
) {
2562 assert(Tok
.is(tok::l_brace
));
2563 SourceLocation LBraceLoc
= Tok
.getLocation();
2565 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, Decl
, LBraceLoc
,
2566 "parsing function body");
2568 // Save and reset current vtordisp stack if we have entered a C++ method body.
2570 getLangOpts().CPlusPlus
&& Decl
&& isa
<CXXMethodDecl
>(Decl
);
2571 Sema::PragmaStackSentinelRAII
2572 PragmaStackSentinel(Actions
, "InternalPragmaState", IsCXXMethod
);
2574 // Do not enter a scope for the brace, as the arguments are in the same scope
2575 // (the function body) as the body itself. Instead, just read the statement
2576 // list and put it into a CompoundStmt for safe keeping.
2577 StmtResult
FnBody(ParseCompoundStatementBody());
2579 // If the function body could not be parsed, make a bogus compoundstmt.
2580 if (FnBody
.isInvalid()) {
2581 Sema::CompoundScopeRAII
CompoundScope(Actions
);
2582 FnBody
= Actions
.ActOnCompoundStmt(LBraceLoc
, LBraceLoc
, {}, false);
2586 return Actions
.ActOnFinishFunctionBody(Decl
, FnBody
.get());
2589 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
2591 /// function-try-block:
2592 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2594 Decl
*Parser::ParseFunctionTryBlock(Decl
*Decl
, ParseScope
&BodyScope
) {
2595 assert(Tok
.is(tok::kw_try
) && "Expected 'try'");
2596 SourceLocation TryLoc
= ConsumeToken();
2598 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, Decl
, TryLoc
,
2599 "parsing function try block");
2601 // Constructor initializer list?
2602 if (Tok
.is(tok::colon
))
2603 ParseConstructorInitializer(Decl
);
2605 Actions
.ActOnDefaultCtorInitializers(Decl
);
2607 // Save and reset current vtordisp stack if we have entered a C++ method body.
2609 getLangOpts().CPlusPlus
&& Decl
&& isa
<CXXMethodDecl
>(Decl
);
2610 Sema::PragmaStackSentinelRAII
2611 PragmaStackSentinel(Actions
, "InternalPragmaState", IsCXXMethod
);
2613 SourceLocation LBraceLoc
= Tok
.getLocation();
2614 StmtResult
FnBody(ParseCXXTryBlockCommon(TryLoc
, /*FnTry*/true));
2615 // If we failed to parse the try-catch, we just give the function an empty
2616 // compound statement as the body.
2617 if (FnBody
.isInvalid()) {
2618 Sema::CompoundScopeRAII
CompoundScope(Actions
);
2619 FnBody
= Actions
.ActOnCompoundStmt(LBraceLoc
, LBraceLoc
, {}, false);
2623 return Actions
.ActOnFinishFunctionBody(Decl
, FnBody
.get());
2626 bool Parser::trySkippingFunctionBody() {
2627 assert(SkipFunctionBodies
&&
2628 "Should only be called when SkipFunctionBodies is enabled");
2629 if (!PP
.isCodeCompletionEnabled()) {
2634 // We're in code-completion mode. Skip parsing for all function bodies unless
2635 // the body contains the code-completion point.
2636 TentativeParsingAction
PA(*this);
2637 bool IsTryCatch
= Tok
.is(tok::kw_try
);
2639 bool ErrorInPrologue
= ConsumeAndStoreFunctionPrologue(Toks
);
2640 if (llvm::any_of(Toks
, [](const Token
&Tok
) {
2641 return Tok
.is(tok::code_completion
);
2646 if (ErrorInPrologue
) {
2648 SkipMalformedDecl();
2651 if (!SkipUntil(tok::r_brace
, StopAtCodeCompletion
)) {
2655 while (IsTryCatch
&& Tok
.is(tok::kw_catch
)) {
2656 if (!SkipUntil(tok::l_brace
, StopAtCodeCompletion
) ||
2657 !SkipUntil(tok::r_brace
, StopAtCodeCompletion
)) {
2666 /// ParseCXXTryBlock - Parse a C++ try-block.
2669 /// 'try' compound-statement handler-seq
2671 StmtResult
Parser::ParseCXXTryBlock() {
2672 assert(Tok
.is(tok::kw_try
) && "Expected 'try'");
2674 SourceLocation TryLoc
= ConsumeToken();
2675 return ParseCXXTryBlockCommon(TryLoc
);
2678 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2679 /// function-try-block.
2682 /// 'try' compound-statement handler-seq
2684 /// function-try-block:
2685 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2688 /// handler handler-seq[opt]
2690 /// [Borland] try-block:
2691 /// 'try' compound-statement seh-except-block
2692 /// 'try' compound-statement seh-finally-block
2694 StmtResult
Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc
, bool FnTry
) {
2695 if (Tok
.isNot(tok::l_brace
))
2696 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
2698 StmtResult
TryBlock(ParseCompoundStatement(
2699 /*isStmtExpr=*/false, Scope::DeclScope
| Scope::TryScope
|
2700 Scope::CompoundStmtScope
|
2701 (FnTry
? Scope::FnTryCatchScope
: 0)));
2702 if (TryBlock
.isInvalid())
2705 // Borland allows SEH-handlers with 'try'
2707 if ((Tok
.is(tok::identifier
) &&
2708 Tok
.getIdentifierInfo() == getSEHExceptKeyword()) ||
2709 Tok
.is(tok::kw___finally
)) {
2710 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2712 if(Tok
.getIdentifierInfo() == getSEHExceptKeyword()) {
2713 SourceLocation Loc
= ConsumeToken();
2714 Handler
= ParseSEHExceptBlock(Loc
);
2717 SourceLocation Loc
= ConsumeToken();
2718 Handler
= ParseSEHFinallyBlock(Loc
);
2720 if(Handler
.isInvalid())
2723 return Actions
.ActOnSEHTryBlock(true /* IsCXXTry */,
2729 StmtVector Handlers
;
2731 // C++11 attributes can't appear here, despite this context seeming
2733 DiagnoseAndSkipCXX11Attributes();
2735 if (Tok
.isNot(tok::kw_catch
))
2736 return StmtError(Diag(Tok
, diag::err_expected_catch
));
2737 while (Tok
.is(tok::kw_catch
)) {
2738 StmtResult
Handler(ParseCXXCatchBlock(FnTry
));
2739 if (!Handler
.isInvalid())
2740 Handlers
.push_back(Handler
.get());
2742 // Don't bother creating the full statement if we don't have any usable
2744 if (Handlers
.empty())
2747 return Actions
.ActOnCXXTryBlock(TryLoc
, TryBlock
.get(), Handlers
);
2751 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2754 /// 'catch' '(' exception-declaration ')' compound-statement
2756 /// exception-declaration:
2757 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2758 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2761 StmtResult
Parser::ParseCXXCatchBlock(bool FnCatch
) {
2762 assert(Tok
.is(tok::kw_catch
) && "Expected 'catch'");
2764 SourceLocation CatchLoc
= ConsumeToken();
2766 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2767 if (T
.expectAndConsume())
2771 // The name in a catch exception-declaration is local to the handler and
2772 // shall not be redeclared in the outermost block of the handler.
2773 ParseScope
CatchScope(this, Scope::DeclScope
| Scope::ControlScope
|
2775 (FnCatch
? Scope::FnTryCatchScope
: 0));
2777 // exception-declaration is equivalent to '...' or a parameter-declaration
2778 // without default arguments.
2779 Decl
*ExceptionDecl
= nullptr;
2780 if (Tok
.isNot(tok::ellipsis
)) {
2781 ParsedAttributes
Attributes(AttrFactory
);
2782 MaybeParseCXX11Attributes(Attributes
);
2784 DeclSpec
DS(AttrFactory
);
2786 if (ParseCXXTypeSpecifierSeq(DS
))
2789 Declarator
ExDecl(DS
, Attributes
, DeclaratorContext::CXXCatch
);
2790 ParseDeclarator(ExDecl
);
2791 ExceptionDecl
= Actions
.ActOnExceptionDeclarator(getCurScope(), ExDecl
);
2796 if (T
.getCloseLocation().isInvalid())
2799 if (Tok
.isNot(tok::l_brace
))
2800 return StmtError(Diag(Tok
, diag::err_expected
) << tok::l_brace
);
2802 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2803 StmtResult
Block(ParseCompoundStatement());
2804 if (Block
.isInvalid())
2807 return Actions
.ActOnCXXCatchBlock(CatchLoc
, ExceptionDecl
, Block
.get());
2810 void Parser::ParseMicrosoftIfExistsStatement(StmtVector
&Stmts
) {
2811 IfExistsCondition Result
;
2812 if (ParseMicrosoftIfExistsCondition(Result
))
2815 // Handle dependent statements by parsing the braces as a compound statement.
2816 // This is not the same behavior as Visual C++, which don't treat this as a
2817 // compound statement, but for Clang's type checking we can't have anything
2818 // inside these braces escaping to the surrounding code.
2819 if (Result
.Behavior
== IEB_Dependent
) {
2820 if (!Tok
.is(tok::l_brace
)) {
2821 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
2825 StmtResult Compound
= ParseCompoundStatement();
2826 if (Compound
.isInvalid())
2829 StmtResult DepResult
= Actions
.ActOnMSDependentExistsStmt(Result
.KeywordLoc
,
2834 if (DepResult
.isUsable())
2835 Stmts
.push_back(DepResult
.get());
2839 BalancedDelimiterTracker
Braces(*this, tok::l_brace
);
2840 if (Braces
.consumeOpen()) {
2841 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
2845 switch (Result
.Behavior
) {
2847 // Parse the statements below.
2851 llvm_unreachable("Dependent case handled above");
2858 // Condition is true, parse the statements.
2859 while (Tok
.isNot(tok::r_brace
)) {
2861 ParseStatementOrDeclaration(Stmts
, ParsedStmtContext::Compound
);
2863 Stmts
.push_back(R
.get());
2865 Braces
.consumeClose();