[NFC][RemoveDIs] Prefer iterators over inst-pointers in InstCombine
[llvm-project.git] / clang / lib / Parse / ParseStmt.cpp
blobfb883c08a745cfaea00b4f44e40c467b437858b0
1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Statement and Block portions of the Parser
10 // interface.
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"
26 #include <optional>
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) {
38 StmtResult Res;
40 // We may get back a null statement if we found a #pragma. Keep going until
41 // we get an actual statement.
42 StmtVector Stmts;
43 do {
44 Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);
45 } while (!Res.isInvalid() && !Res.get());
47 return Res;
50 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
51 /// StatementOrDeclaration:
52 /// statement
53 /// declaration
54 ///
55 /// statement:
56 /// labeled-statement
57 /// compound-statement
58 /// expression-statement
59 /// selection-statement
60 /// iteration-statement
61 /// jump-statement
62 /// [C++] declaration-statement
63 /// [C++] try-block
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]
70 ///
71 /// labeled-statement:
72 /// identifier ':' statement
73 /// 'case' constant-expression ':' statement
74 /// 'default' ':' statement
75 ///
76 /// selection-statement:
77 /// if-statement
78 /// switch-statement
79 ///
80 /// iteration-statement:
81 /// while-statement
82 /// do-statement
83 /// for-statement
84 ///
85 /// expression-statement:
86 /// expression[opt] ';'
87 ///
88 /// jump-statement:
89 /// 'goto' identifier ';'
90 /// 'continue' ';'
91 /// 'break' ';'
92 /// 'return' expression[opt] ';'
93 /// [GNU] 'goto' '*' expression ';'
94 ///
95 /// [OBC] objc-throw-statement:
96 /// [OBC] '@' 'throw' expression ';'
97 /// [OBC] '@' 'throw' ';'
98 ///
99 StmtResult
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
122 // two lists.
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())
130 return Res;
132 return Actions.ActOnAttributedStmt(Attrs, Res.get());
135 namespace {
136 class StatementFilterCCC final : public CorrectionCandidateCallback {
137 public:
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>())
155 return false;
156 return CorrectionCandidateCallback::ValidateCandidate(candidate);
159 std::unique_ptr<CorrectionCandidateCallback> clone() override {
160 return std::make_unique<StatementFilterCCC>(*this);
163 private:
164 Token NextToken;
168 StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
169 StmtVector &Stmts, ParsedStmtContext StmtCtx,
170 SourceLocation *TrailingElseLoc, ParsedAttributes &CXX11Attrs,
171 ParsedAttributes &GNUAttrs) {
172 const char *SemiError = nullptr;
173 StmtResult Res;
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.
179 Retry:
180 tok::TokenKind Kind = Tok.getKind();
181 SourceLocation AtLoc;
182 switch (Kind) {
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:
190 cutOffParsing();
191 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
192 return StmtError();
194 case tok::identifier:
195 ParseIdentifier: {
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
209 // found.
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))
219 ConsumeToken();
220 return StmtError();
223 // If the identifier was typo-corrected, try again.
224 if (Tok.isNot(tok::identifier))
225 goto Retry;
228 // Fall through
229 [[fallthrough]];
232 default: {
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;
243 DeclGroupPtrTy Decl;
244 if (GNUAttributeLoc.isValid()) {
245 DeclStart = GNUAttributeLoc;
246 Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, CXX11Attrs,
247 GNUAttrs, &GNUAttributeLoc);
248 } else {
249 Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, CXX11Attrs,
250 GNUAttrs);
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);
265 return StmtError();
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;
277 [[fallthrough]];
278 default:
279 return ParseExprStatement(StmtCtx);
283 case tok::kw___attribute: {
284 GNUAttributeLoc = Tok.getLocation();
285 ParseGNUAttributes(GNUAttrs);
286 goto Retry;
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";
311 break;
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();
317 SemiError = "goto";
318 break;
319 case tok::kw_continue: // C99 6.8.6.2: continue-statement
320 Res = ParseContinueStatement();
321 SemiError = "continue";
322 break;
323 case tok::kw_break: // C99 6.8.6.3: break-statement
324 Res = ParseBreakStatement();
325 SemiError = "break";
326 break;
327 case tok::kw_return: // C99 6.8.6.4: return-statement
328 Res = ParseReturnStatement();
329 SemiError = "return";
330 break;
331 case tok::kw_co_return: // C++ Coroutines: co_return statement
332 Res = ParseReturnStatement();
333 SemiError = "co_return";
334 break;
336 case tok::kw_asm: {
337 for (const ParsedAttr &AL : CXX11Attrs)
338 // Could be relaxed if asm-related regular keyword attributes are
339 // added later.
340 (AL.isRegularKeywordAttribute()
341 ? Diag(AL.getRange().getBegin(), diag::err_keyword_not_allowed)
342 : Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored))
343 << AL;
344 // Prevent these from being interpreted as statement attributes later on.
345 CXX11Attrs.clear();
346 ProhibitAttributes(GNUAttrs);
347 bool msAsm = false;
348 Res = ParseAsmStatement(msAsm);
349 if (msAsm) return Res;
350 SemiError = "asm";
351 break;
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
360 // a new scope.
361 return StmtEmpty();
363 case tok::kw_try: // C++ 15: try-block
364 return ParseCXXTryBlock();
366 case tok::kw___try:
367 ProhibitAttributes(CXX11Attrs);
368 ProhibitAttributes(GNUAttrs);
369 return ParseSEHTryBlock();
371 case tok::kw___leave:
372 Res = ParseSEHLeaveStatement();
373 SemiError = "__leave";
374 break;
376 case tok::annot_pragma_vis:
377 ProhibitAttributes(CXX11Attrs);
378 ProhibitAttributes(GNUAttrs);
379 HandlePragmaVisibility();
380 return StmtEmpty();
382 case tok::annot_pragma_pack:
383 ProhibitAttributes(CXX11Attrs);
384 ProhibitAttributes(GNUAttrs);
385 HandlePragmaPack();
386 return StmtEmpty();
388 case tok::annot_pragma_msstruct:
389 ProhibitAttributes(CXX11Attrs);
390 ProhibitAttributes(GNUAttrs);
391 HandlePragmaMSStruct();
392 return StmtEmpty();
394 case tok::annot_pragma_align:
395 ProhibitAttributes(CXX11Attrs);
396 ProhibitAttributes(GNUAttrs);
397 HandlePragmaAlign();
398 return StmtEmpty();
400 case tok::annot_pragma_weak:
401 ProhibitAttributes(CXX11Attrs);
402 ProhibitAttributes(GNUAttrs);
403 HandlePragmaWeak();
404 return StmtEmpty();
406 case tok::annot_pragma_weakalias:
407 ProhibitAttributes(CXX11Attrs);
408 ProhibitAttributes(GNUAttrs);
409 HandlePragmaWeakAlias();
410 return StmtEmpty();
412 case tok::annot_pragma_redefine_extname:
413 ProhibitAttributes(CXX11Attrs);
414 ProhibitAttributes(GNUAttrs);
415 HandlePragmaRedefineExtname();
416 return StmtEmpty();
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();
423 return StmtError();
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();
430 return StmtError();
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"
438 : "fenv_access");
439 ConsumeAnnotationToken();
440 return StmtEmpty();
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();
447 return StmtError();
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();
454 return StmtError();
456 case tok::annot_pragma_opencl_extension:
457 ProhibitAttributes(CXX11Attrs);
458 ProhibitAttributes(GNUAttrs);
459 HandlePragmaOpenCLExtension();
460 return StmtEmpty();
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);
472 [[fallthrough]];
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();
481 return StmtEmpty();
483 case tok::annot_pragma_ms_pragma:
484 ProhibitAttributes(CXX11Attrs);
485 ProhibitAttributes(GNUAttrs);
486 HandlePragmaMSPragma();
487 return StmtEmpty();
489 case tok::annot_pragma_ms_vtordisp:
490 ProhibitAttributes(CXX11Attrs);
491 ProhibitAttributes(GNUAttrs);
492 HandlePragmaMSVtorDisp();
493 return StmtEmpty();
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:
501 HandlePragmaDump();
502 return StmtEmpty();
504 case tok::annot_pragma_attribute:
505 HandlePragmaAttribute();
506 return StmtEmpty();
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
513 // succeed.
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);
519 return Res;
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))
537 ConsumeToken();
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)
558 CurTok = &Tok;
559 else
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());
567 return R;
570 /// ParseSEHTryBlockCommon
572 /// seh-try-block:
573 /// '__try' compound-statement seh-handler
575 /// seh-handler:
576 /// seh-except-block
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())
590 return TryBlock;
592 StmtResult Handler;
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);
600 } else {
601 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
604 if(Handler.isInvalid())
605 return Handler;
607 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
608 TryLoc,
609 TryBlock.get(),
610 Handler.get());
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))
624 return StmtError();
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())
649 return StmtError();
651 if (ExpectAndConsume(tok::r_paren))
652 return StmtError();
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())
660 return Block;
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();
684 return Block;
687 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
690 /// Handle __leave
692 /// seh-leave-statement:
693 /// '__leave' ';'
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.
702 /// label:
703 /// identifier ':'
704 /// [GNU] identifier ':' attributes[opt]
706 /// labeled-statement:
707 /// label 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.
727 StmtResult SubStmt;
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
734 // declaration.
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);
741 else {
742 StmtVector Stmts;
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);
768 Attrs.clear();
770 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
771 SubStmt.get());
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):
789 // case 1:
790 // case 2:
791 // case 3:
792 // case 4:
793 // case 5: etc.
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
802 // example above.
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;
812 do {
813 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
814 ConsumeToken(); // eat the 'case'.
815 ColonLoc = SourceLocation();
817 if (Tok.is(tok::code_completion)) {
818 cutOffParsing();
819 Actions.CodeCompleteCase(getCurScope());
820 return StmtError();
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
825 /// expression.
826 ColonProtectionRAIIObject ColonProtection(*this);
828 ExprResult LHS;
829 if (!MissingCase) {
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))
835 return StmtError();
837 } else {
838 LHS = Expr;
839 MissingCase = false;
842 // GNU case range extension.
843 SourceLocation DotDotDotLoc;
844 ExprResult RHS;
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))
850 return StmtError();
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, ":");
863 } else {
864 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
865 Diag(ExpectedLoc, diag::err_expected_after)
866 << "'case'" << tok::colon
867 << FixItHint::CreateInsertion(ExpectedLoc, ":");
868 ColonLoc = ExpectedLoc;
871 StmtResult Case =
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.
880 } else {
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())
885 TopLevelCase = Case;
886 else
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.
895 StmtResult SubStmt;
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);
902 } else {
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.
915 return TopLevelCase;
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, ":");
939 } else {
940 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
941 Diag(ExpectedLoc, diag::err_expected_after)
942 << "'default'" << tok::colon
943 << FixItHint::CreateInsertion(ExpectedLoc, ":");
944 ColonLoc = ExpectedLoc;
947 StmtResult SubStmt;
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);
954 } else {
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]
977 /// block-item-list:
978 /// block-item
979 /// block-item-list block-item
981 /// block-item:
982 /// declaration
983 /// [GNU] '__extension__' declaration
984 /// statement
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();
1014 break;
1015 case tok::annot_pragma_pack:
1016 HandlePragmaPack();
1017 break;
1018 case tok::annot_pragma_msstruct:
1019 HandlePragmaMSStruct();
1020 break;
1021 case tok::annot_pragma_align:
1022 HandlePragmaAlign();
1023 break;
1024 case tok::annot_pragma_weak:
1025 HandlePragmaWeak();
1026 break;
1027 case tok::annot_pragma_weakalias:
1028 HandlePragmaWeakAlias();
1029 break;
1030 case tok::annot_pragma_redefine_extname:
1031 HandlePragmaRedefineExtname();
1032 break;
1033 case tok::annot_pragma_opencl_extension:
1034 HandlePragmaOpenCLExtension();
1035 break;
1036 case tok::annot_pragma_fp_contract:
1037 HandlePragmaFPContract();
1038 break;
1039 case tok::annot_pragma_fp:
1040 HandlePragmaFP();
1041 break;
1042 case tok::annot_pragma_fenv_access:
1043 case tok::annot_pragma_fenv_access_ms:
1044 HandlePragmaFEnvAccess();
1045 break;
1046 case tok::annot_pragma_fenv_round:
1047 HandlePragmaFEnvRound();
1048 break;
1049 case tok::annot_pragma_float_control:
1050 HandlePragmaFloatControl();
1051 break;
1052 case tok::annot_pragma_ms_pointers_to_members:
1053 HandlePragmaMSPointersToMembers();
1054 break;
1055 case tok::annot_pragma_ms_pragma:
1056 HandlePragmaMSPragma();
1057 break;
1058 case tok::annot_pragma_ms_vtordisp:
1059 HandlePragmaMSVtorDisp();
1060 break;
1061 case tok::annot_pragma_dump:
1062 HandlePragmaDump();
1063 break;
1064 default:
1065 checkForPragmas = false;
1066 break;
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);
1077 } else {
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))
1088 return false;
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.
1098 StmtResult R =
1099 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
1100 if (R.isUsable())
1101 Stmts.push_back(R.get());
1104 // Did not consume any extra semi.
1105 if (EndLoc.isInvalid())
1106 return false;
1108 Diag(StartLoc, diag::warn_null_statement)
1109 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
1110 return true;
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)) {
1119 ++LookAhead;
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
1123 // expression.
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(),
1139 Tok.getLocation(),
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())
1149 return StmtError();
1151 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
1153 // Parse any pragmas at the beginning of the compound statement.
1154 ParseCompoundStatementLeadingPragmas();
1155 Actions.ActOnAfterCompoundStatementLeadingPragmas();
1157 StmtVector Stmts;
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;
1165 while (true) {
1166 if (Tok.isNot(tok::identifier)) {
1167 Diag(Tok, diag::err_expected) << tok::identifier;
1168 break;
1171 IdentifierInfo *II = Tok.getIdentifierInfo();
1172 SourceLocation IdLoc = ConsumeToken();
1173 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
1175 if (!TryConsumeToken(tok::comma))
1176 break;
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);
1185 if (R.isUsable())
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();
1197 continue;
1200 if (ConsumeNullStmt(Stmts))
1201 continue;
1203 StmtResult R;
1204 if (Tok.isNot(tok::kw___extension__)) {
1205 R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
1206 } else {
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__))
1213 ConsumeToken();
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);
1229 } else {
1230 // Otherwise this was a unary __extension__ marker.
1231 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1233 if (Res.isInvalid()) {
1234 SkipUntil(tok::semi);
1235 continue;
1238 // Eat the semicolon at the end of stmt and convert the expr into a
1239 // statement.
1240 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1241 R = handleExprStmt(Res, SubStmtCtx);
1242 if (R.isUsable())
1243 R = Actions.ActOnAttributedStmt(attrs, R.get());
1247 if (R.isUsable())
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
1253 // supported.
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);
1269 } else {
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,
1278 Stmts, isStmtExpr);
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,
1297 SourceLocation Loc,
1298 Sema::ConditionKind CK,
1299 SourceLocation &LParenLoc,
1300 SourceLocation &RParenLoc) {
1301 BalancedDelimiterTracker T(*this, tok::l_paren);
1302 T.consumeOpen();
1303 SourceLocation Start = Tok.getLocation();
1305 if (getLangOpts().CPlusPlus) {
1306 Cond = ParseCXXCondition(InitStmt, Loc, CK, false);
1307 } else {
1308 ExprResult CondExpr = ParseExpression();
1310 // If required, convert to a boolean value.
1311 if (CondExpr.isInvalid())
1312 Cond = Sema::ConditionError();
1313 else
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))
1326 return true;
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.
1339 T.consumeClose();
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 ")"
1345 // isn't valid.
1346 while (Tok.is(tok::r_paren)) {
1347 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1348 << FixItHint::CreateRemoval(Tok.getLocation());
1349 ConsumeParen();
1352 return false;
1355 namespace {
1357 enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };
1359 struct MisleadingIndentationChecker {
1360 Parser &P;
1361 SourceLocation StmtLoc;
1362 SourceLocation PrevLoc;
1363 unsigned NumDirectives;
1364 MisleadingStatementKind Kind;
1365 bool ShouldSkip;
1366 MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,
1367 SourceLocation SL)
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)
1386 return ColNo;
1388 std::pair<FileID, unsigned> FIDAndOffset = SM.getDecomposedLoc(Loc);
1390 bool Invalid;
1391 StringRef BufData = SM.getBufferData(FIDAndOffset.first, &Invalid);
1392 if (Invalid)
1393 return 0;
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,
1402 // expanding tabs.
1403 for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;
1404 ++CurPos) {
1405 if (*CurPos == '\t')
1406 // Advance visual column to next tabstop.
1407 VisualColumn += (TabStop - VisualColumn % TabStop);
1408 else
1409 VisualColumn++;
1411 return VisualColumn + 1;
1414 void Check() {
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();
1424 return;
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);
1470 IsConstexpr = true;
1471 ConsumeToken();
1472 } else {
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);
1480 IsConsteval = true;
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);
1487 return StmtError();
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.
1495 // C++ 6.4p3:
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
1498 // condition.
1499 // C++ 3.3.2p4:
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;
1512 if (!IsConsteval) {
1514 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1515 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1516 : Sema::ConditionKind::Boolean,
1517 LParen, RParen))
1518 return StmtError();
1520 if (IsConstexpr)
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.
1530 // C++ 6.4p1:
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;
1559 ShouldEnter = true;
1562 EnterExpressionEvaluationContext PotentiallyDiscarded(
1563 Actions, Context, nullptr,
1564 Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
1565 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1568 if (Tok.isNot(tok::kw_else))
1569 MIChecker.Check();
1571 // Pop the 'if' scope if needed.
1572 InnerScope.Exit();
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
1589 // cases.
1591 // C++ 6.4p1:
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;
1604 ShouldEnter = true;
1607 EnterExpressionEvaluationContext PotentiallyDiscarded(
1608 Actions, Context, nullptr,
1609 Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
1610 ElseStmt = ParseStatement();
1612 if (ElseStmt.isUsable())
1613 MIChecker.Check();
1615 // Pop the 'else' scope if needed.
1616 InnerScope.Exit();
1617 } else if (Tok.is(tok::code_completion)) {
1618 cutOffParsing();
1619 Actions.CodeCompleteAfterIf(getCurScope(), IsBracedThen);
1620 return StmtError();
1621 } else if (InnerStatementTrailingElseLoc.isValid()) {
1622 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1625 IfScope.Exit();
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.
1634 return StmtError();
1637 if (IsConsteval) {
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"
1646 << "{";
1647 return StmtError();
1649 if (!ElseStmt.isUnset() && !IsCompoundStatement(ElseStmt.get())) {
1650 Diag(ElseLoc, diag::err_expected_after) << "else"
1651 << "{";
1652 return StmtError();
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;
1663 if (IsConstexpr)
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);
1684 return StmtError();
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.
1692 // C++ 6.4p3:
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
1695 // condition.
1696 // C++ 3.3.2p4:
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;
1702 if (C99orCXX)
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))
1713 return StmtError();
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)) {
1724 ConsumeBrace();
1725 SkipUntil(tok::r_brace);
1726 } else
1727 SkipUntil(tok::semi);
1728 return Switch;
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.
1735 // C++ 6.4p1:
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.
1747 if (C99orCXX)
1748 getCurScope()->decrementMSManglingNumber();
1750 // Read the body statement.
1751 StmtResult Body(ParseStatement(TrailingElseLoc));
1753 // Pop the scopes.
1754 InnerScope.Exit();
1755 SwitchScope.Exit();
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);
1772 return StmtError();
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.
1780 // C++ 6.4p3:
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
1783 // condition.
1784 // C++ 3.3.2p4:
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;
1790 if (C99orCXX)
1791 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1792 Scope::DeclScope | Scope::ControlScope;
1793 else
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))
1803 return StmtError();
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.
1809 // C++ 6.5p2:
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())
1824 MIChecker.Check();
1825 // Pop the body scope if needed.
1826 InnerScope.Exit();
1827 WhileScope.Exit();
1829 if (Cond.isInvalid() || Body.isInvalid())
1830 return StmtError();
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;
1848 else
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.
1857 // C++ 6.5p2:
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.
1868 InnerScope.Exit();
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);
1876 return StmtError();
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);
1883 return StmtError();
1886 // Parse the parenthesized expression.
1887 BalancedDelimiterTracker T(*this, tok::l_paren);
1888 T.consumeOpen();
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);
1899 else {
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);
1906 T.consumeClose();
1907 DoScope.Exit();
1909 if (Cond.isInvalid() || Body.isInvalid())
1910 return StmtError();
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))
1921 return true;
1923 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1924 TentativeParsingAction PA(*this);
1925 ConsumeToken();
1926 SkipCXX11Attributes();
1927 bool Result = Tok.is(tok::colon);
1928 PA.Revert();
1929 return Result;
1932 return false;
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] ')'
1940 /// [C++] statement
1941 /// [C++0x] 'for'
1942 /// 'co_await'[opt] [Coroutines]
1943 /// '(' for-range-declaration ':' for-range-initializer ')'
1944 /// statement
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);
1969 return StmtError();
1972 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1973 getLangOpts().ObjC;
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.
1978 // C++ 6.4p3:
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
1981 // condition.
1982 // C++ 3.3.2p4:
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).
1986 // C++ 6.5.3p1:
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;
1991 if (C99orCXXorObjC)
1992 ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1994 ParseScope ForScope(this, ScopeFlags);
1996 BalancedDelimiterTracker T(*this, tok::l_paren);
1997 T.consumeOpen();
1999 ExprResult Value;
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)) {
2009 cutOffParsing();
2010 Actions.CodeCompleteOrdinaryName(getCurScope(),
2011 C99orCXXorObjC? Sema::PCC_ForInit
2012 : Sema::PCC_Expression);
2013 return StmtError();
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;
2028 ConsumeToken();
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();
2039 else
2040 ForRangeInfo.RangeExpr = ParseExpression();
2042 Diag(Loc, diag::err_for_range_identifier)
2043 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
2044 ? FixItHint::CreateInsertion(Loc, "auto &&")
2045 : FixItHint());
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);
2057 DeclGroupPtrTy DG;
2058 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2059 if (Tok.is(tok::kw_using)) {
2060 DG = ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit,
2061 attrs);
2062 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2063 } else {
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;
2079 ConsumeToken();
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)) {
2086 cutOffParsing();
2087 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
2088 return StmtError();
2090 Collection = ParseExpression();
2091 } else {
2092 Diag(Tok, diag::err_expected_semi_for);
2095 } else {
2096 ProhibitAttributes(attrs);
2097 Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2099 ForEach = isTokIdentifier_in();
2101 // Turn the expression into a stmt.
2102 if (!Value.isInvalid()) {
2103 if (ForEach)
2104 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
2105 else {
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)) {
2118 ConsumeToken();
2119 } else if (ForEach) {
2120 ConsumeToken(); // consume 'in'
2122 if (Tok.is(tok::code_completion)) {
2123 cutOffParsing();
2124 Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
2125 return StmtError();
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();
2135 } else {
2136 if (!Value.isInvalid()) {
2137 Diag(Tok, diag::err_expected_semi_for);
2138 } else {
2139 // Skip until semicolon or rparen, don't consume it.
2140 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
2141 if (Tok.is(tok::semi))
2142 ConsumeToken();
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 (...;;
2152 // no second part.
2153 } else if (Tok.is(tok::r_paren)) {
2154 // missing both semicolons.
2155 } else {
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()
2176 : SourceRange());
2177 if (EmptyInitStmtSemiLoc.isValid()) {
2178 Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
2179 << /*for-loop*/ 2
2180 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
2184 if (SecondPart.isInvalid()) {
2185 ExprResult CondExpr = Actions.CreateRecoveryExpr(
2186 SecondPartStart,
2187 Tok.getLocation() == SecondPartStart ? SecondPartStart
2188 : PrevTokLocation,
2189 {}, Actions.PreferredConditionType(CK));
2190 if (!CondExpr.isInvalid())
2191 SecondPart = Actions.ActOnCondition(getCurScope(), ForLoc,
2192 CondExpr.get(), CK,
2193 /*MissingOK=*/false);
2196 } else {
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();
2203 else
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)) {
2225 ConsumeToken();
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());
2235 // Match the ')'.
2236 T.consumeClose();
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,
2266 FirstPart.get(),
2267 Collection.get(),
2268 T.getCloseLocation());
2269 } else {
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.
2281 // C++ 6.5p2:
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).
2295 if (C99orCXXorObjC)
2296 getCurScope()->decrementMSManglingNumber();
2298 MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
2300 // Read the body statement.
2301 StmtResult Body(ParseStatement(TrailingElseLoc));
2303 if (Body.isUsable())
2304 MIChecker.Check();
2306 // Pop the body scope if needed.
2307 InnerScope.Exit();
2309 // Leave the for-scope.
2310 ForScope.Exit();
2312 if (Body.isInvalid())
2313 return StmtError();
2315 if (ForEach)
2316 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
2317 Body.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(),
2324 Body.get());
2327 /// ParseGotoStatement
2328 /// jump-statement:
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'.
2338 StmtResult Res;
2339 if (Tok.is(tok::identifier)) {
2340 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
2341 Tok.getLocation());
2342 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
2343 ConsumeToken();
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);
2351 return StmtError();
2353 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
2354 } else {
2355 Diag(Tok, diag::err_expected) << tok::identifier;
2356 return StmtError();
2359 return Res;
2362 /// ParseContinueStatement
2363 /// jump-statement:
2364 /// 'continue' ';'
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
2374 /// jump-statement:
2375 /// 'break' ';'
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
2385 /// jump-statement:
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'.
2396 ExprResult R;
2397 if (Tok.isNot(tok::semi)) {
2398 if (!IsCoreturn)
2399 PreferredType.enterReturn(Actions, Tok.getLocation());
2400 // FIXME: Code completion for co_return.
2401 if (Tok.is(tok::code_completion) && !IsCoreturn) {
2402 cutOffParsing();
2403 Actions.CodeCompleteExpression(getCurScope(),
2404 PreferredType.get(Tok.getLocation()));
2405 return StmtError();
2408 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
2409 R = ParseInitializer();
2410 if (R.isUsable())
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();
2416 } else
2417 R = ParseExpression();
2418 if (R.isInvalid()) {
2419 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2420 return StmtError();
2423 if (IsCoreturn)
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)) {
2439 LoopHint Hint;
2440 if (!HandlePragmaLoopHint(Hint))
2441 continue;
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.
2460 // See PR46336.
2461 if (Attrs.Range.getBegin().isInvalid())
2462 Attrs.Range.setBegin(StartLoc);
2464 return S;
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.
2475 bool IsCXXMethod =
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);
2488 FnBody =
2489 Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, std::nullopt, false);
2492 BodyScope.Exit();
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);
2511 else
2512 Actions.ActOnDefaultCtorInitializers(Decl);
2514 // Save and reset current vtordisp stack if we have entered a C++ method body.
2515 bool IsCXXMethod =
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);
2526 FnBody =
2527 Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, std::nullopt, false);
2530 BodyScope.Exit();
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()) {
2538 SkipFunctionBody();
2539 return true;
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);
2546 CachedTokens Toks;
2547 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2548 if (llvm::any_of(Toks, [](const Token &Tok) {
2549 return Tok.is(tok::code_completion);
2550 })) {
2551 PA.Revert();
2552 return false;
2554 if (ErrorInPrologue) {
2555 PA.Commit();
2556 SkipMalformedDecl();
2557 return true;
2559 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2560 PA.Revert();
2561 return false;
2563 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2564 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2565 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2566 PA.Revert();
2567 return false;
2570 PA.Commit();
2571 return true;
2574 /// ParseCXXTryBlock - Parse a C++ try-block.
2576 /// 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.
2589 /// try-block:
2590 /// 'try' compound-statement handler-seq
2592 /// function-try-block:
2593 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2595 /// 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())
2611 return TryBlock;
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(...)
2619 StmtResult Handler;
2620 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2621 SourceLocation Loc = ConsumeToken();
2622 Handler = ParseSEHExceptBlock(Loc);
2624 else {
2625 SourceLocation Loc = ConsumeToken();
2626 Handler = ParseSEHFinallyBlock(Loc);
2628 if(Handler.isInvalid())
2629 return Handler;
2631 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2632 TryLoc,
2633 TryBlock.get(),
2634 Handler.get());
2636 else {
2637 StmtVector Handlers;
2639 // C++11 attributes can't appear here, despite this context seeming
2640 // statement-like.
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
2651 // handlers.
2652 if (Handlers.empty())
2653 return StmtError();
2655 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2659 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2661 /// handler:
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]
2667 /// '...'
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())
2676 return StmtError();
2678 // C++ 3.3.2p3:
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 |
2682 Scope::CatchScope |
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))
2695 return StmtError();
2697 Declarator ExDecl(DS, Attributes, DeclaratorContext::CXXCatch);
2698 ParseDeclarator(ExDecl);
2699 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2700 } else
2701 ConsumeToken();
2703 T.consumeClose();
2704 if (T.getCloseLocation().isInvalid())
2705 return StmtError();
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())
2713 return Block;
2715 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2718 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2719 IfExistsCondition Result;
2720 if (ParseMicrosoftIfExistsCondition(Result))
2721 return;
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;
2730 return;
2733 StmtResult Compound = ParseCompoundStatement();
2734 if (Compound.isInvalid())
2735 return;
2737 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2738 Result.IsIfExists,
2739 Result.SS,
2740 Result.Name,
2741 Compound.get());
2742 if (DepResult.isUsable())
2743 Stmts.push_back(DepResult.get());
2744 return;
2747 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2748 if (Braces.consumeOpen()) {
2749 Diag(Tok, diag::err_expected) << tok::l_brace;
2750 return;
2753 switch (Result.Behavior) {
2754 case IEB_Parse:
2755 // Parse the statements below.
2756 break;
2758 case IEB_Dependent:
2759 llvm_unreachable("Dependent case handled above");
2761 case IEB_Skip:
2762 Braces.skipToEnd();
2763 return;
2766 // Condition is true, parse the statements.
2767 while (Tok.isNot(tok::r_brace)) {
2768 StmtResult R =
2769 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
2770 if (R.isUsable())
2771 Stmts.push_back(R.get());
2773 Braces.consumeClose();