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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/PrettyDeclStackTrace.h"
15#include "clang/Basic/Attributes.h"
16#include "clang/Basic/PrettyStackTrace.h"
17#include "clang/Basic/TargetInfo.h"
18#include "clang/Basic/TokenKinds.h"
19#include "clang/Parse/LoopHint.h"
20#include "clang/Parse/Parser.h"
21#include "clang/Parse/RAIIObjectsForParser.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/EnterExpressionEvaluationContext.h"
24#include "clang/Sema/Scope.h"
25#include "clang/Sema/SemaCodeCompletion.h"
26#include "clang/Sema/SemaObjC.h"
27#include "clang/Sema/SemaOpenACC.h"
28#include "clang/Sema/SemaOpenMP.h"
29#include "clang/Sema/TypoCorrection.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/ScopeExit.h"
32#include <optional>
33
34using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// C99 6.8: Statements and Blocks.
38//===----------------------------------------------------------------------===//
39
40StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
41 ParsedStmtContext StmtCtx,
42 LabelDecl *PrecedingLabel) {
43 StmtResult Res;
44
45 // We may get back a null statement if we found a #pragma. Keep going until
46 // we get an actual statement.
47 StmtVector Stmts;
48 do {
49 Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc,
50 PrecedingLabel);
51 } while (!Res.isInvalid() && !Res.get());
52
53 return Res;
54}
55
56StmtResult Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
57 ParsedStmtContext StmtCtx,
58 SourceLocation *TrailingElseLoc,
59 LabelDecl *PrecedingLabel) {
60
61 ParenBraceBracketBalancer BalancerRAIIObj(*this);
62
63 // Because we're parsing either a statement or a declaration, the order of
64 // attribute parsing is important. [[]] attributes at the start of a
65 // statement are different from [[]] attributes that follow an __attribute__
66 // at the start of the statement. Thus, we're not using MaybeParseAttributes
67 // here because we don't want to allow arbitrary orderings.
68 ParsedAttributes CXX11Attrs(AttrFactory);
69 bool HasStdAttr =
70 MaybeParseCXX11Attributes(Attrs&: CXX11Attrs, /*MightBeObjCMessageSend*/ OuterMightBeMessageSend: true);
71 ParsedAttributes GNUOrMSAttrs(AttrFactory);
72 if (getLangOpts().OpenCL)
73 MaybeParseGNUAttributes(Attrs&: GNUOrMSAttrs);
74
75 if (getLangOpts().HLSL)
76 MaybeParseMicrosoftAttributes(Attrs&: GNUOrMSAttrs);
77
78 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
79 Stmts, StmtCtx, TrailingElseLoc, DeclAttrs&: CXX11Attrs, DeclSpecAttrs&: GNUOrMSAttrs,
80 PrecedingLabel);
81 MaybeDestroyTemplateIds();
82
83 takeAndConcatenateAttrs(First&: CXX11Attrs, Second: std::move(GNUOrMSAttrs));
84
85 assert((CXX11Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
86 "attributes on empty statement");
87
88 if (HasStdAttr && getLangOpts().C23 &&
89 (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
90 ParsedStmtContext{} &&
91 isa_and_present<NullStmt>(Val: Res.get()))
92 Diag(Loc: CXX11Attrs.Range.getBegin(), DiagID: diag::warn_attr_in_secondary_block)
93 << CXX11Attrs.Range;
94
95 if (CXX11Attrs.empty() || Res.isInvalid())
96 return Res;
97
98 return Actions.ActOnAttributedStmt(AttrList: CXX11Attrs, SubStmt: Res.get());
99}
100
101namespace {
102class StatementFilterCCC final : public CorrectionCandidateCallback {
103public:
104 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
105 WantTypeSpecifiers = nextTok.isOneOf(Ks: tok::l_paren, Ks: tok::less, Ks: tok::l_square,
106 Ks: tok::identifier, Ks: tok::star, Ks: tok::amp);
107 WantExpressionKeywords =
108 nextTok.isOneOf(Ks: tok::l_paren, Ks: tok::identifier, Ks: tok::arrow, Ks: tok::period);
109 WantRemainingKeywords =
110 nextTok.isOneOf(Ks: tok::l_paren, Ks: tok::semi, Ks: tok::identifier, Ks: tok::l_brace);
111 WantCXXNamedCasts = false;
112 }
113
114 bool ValidateCandidate(const TypoCorrection &candidate) override {
115 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
116 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(Val: FD);
117 if (NextToken.is(K: tok::equal))
118 return candidate.getCorrectionDeclAs<VarDecl>();
119 if (NextToken.is(K: tok::period) &&
120 candidate.getCorrectionDeclAs<NamespaceDecl>())
121 return false;
122 return CorrectionCandidateCallback::ValidateCandidate(candidate);
123 }
124
125 std::unique_ptr<CorrectionCandidateCallback> clone() override {
126 return std::make_unique<StatementFilterCCC>(args&: *this);
127 }
128
129private:
130 Token NextToken;
131};
132}
133
134StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
135 StmtVector &Stmts, ParsedStmtContext StmtCtx,
136 SourceLocation *TrailingElseLoc, ParsedAttributes &CXX11Attrs,
137 ParsedAttributes &GNUAttrs, LabelDecl *PrecedingLabel) {
138 const char *SemiError = nullptr;
139 StmtResult Res;
140 SourceLocation GNUAttributeLoc;
141
142 // Cases in this switch statement should fall through if the parser expects
143 // the token to end in a semicolon (in which case SemiError should be set),
144 // or they directly 'return;' if not.
145Retry:
146 tok::TokenKind Kind = Tok.getKind();
147 SourceLocation AtLoc;
148 switch (Kind) {
149 case tok::at: // May be a @try or @throw statement
150 {
151 AtLoc = ConsumeToken(); // consume @
152 return ParseObjCAtStatement(atLoc: AtLoc, StmtCtx);
153 }
154
155 case tok::code_completion:
156 cutOffParsing();
157 Actions.CodeCompletion().CodeCompleteOrdinaryName(
158 S: getCurScope(), CompletionContext: SemaCodeCompletion::PCC_Statement);
159 return StmtError();
160
161 case tok::identifier:
162 ParseIdentifier: {
163 Token Next = NextToken();
164 if (Next.is(K: tok::colon)) { // C99 6.8.1: labeled-statement
165 // Both C++11 and GNU attributes preceding the label appertain to the
166 // label, so put them in a single list to pass on to
167 // ParseLabeledStatement().
168 takeAndConcatenateAttrs(First&: CXX11Attrs, Second: std::move(GNUAttrs));
169
170 // identifier ':' statement
171 return ParseLabeledStatement(Attrs&: CXX11Attrs, StmtCtx);
172 }
173
174 // Look up the identifier, and typo-correct it to a keyword if it's not
175 // found.
176 if (Next.isNot(K: tok::coloncolon)) {
177 // Try to limit which sets of keywords should be included in typo
178 // correction based on what the next token is.
179 StatementFilterCCC CCC(Next);
180 if (TryAnnotateName(CCC: &CCC) == AnnotatedNameKind::Error) {
181 // Handle errors here by skipping up to the next semicolon or '}', and
182 // eat the semicolon if that's what stopped us.
183 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
184 if (Tok.is(K: tok::semi))
185 ConsumeToken();
186 return StmtError();
187 }
188
189 // If the identifier was annotated, try again.
190 if (Tok.isNot(K: tok::identifier))
191 goto Retry;
192 }
193
194 // Fall through
195 [[fallthrough]];
196 }
197
198 default: {
199 if (getLangOpts().CPlusPlus && MaybeParseCXX11Attributes(Attrs&: CXX11Attrs, OuterMightBeMessageSend: true))
200 goto Retry;
201
202 bool HaveAttrs = !CXX11Attrs.empty() || !GNUAttrs.empty();
203 auto IsStmtAttr = [](ParsedAttr &Attr) { return Attr.isStmtAttr(); };
204 bool AllAttrsAreStmtAttrs = llvm::all_of(Range&: CXX11Attrs, P: IsStmtAttr) &&
205 llvm::all_of(Range&: GNUAttrs, P: IsStmtAttr);
206 // In C, the grammar production for statement (C23 6.8.1p1) does not allow
207 // for declarations, which is different from C++ (C++23 [stmt.pre]p1). So
208 // in C++, we always allow a declaration, but in C we need to check whether
209 // we're in a statement context that allows declarations. e.g., in C, the
210 // following is invalid: if (1) int x;
211 if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
212 (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
213 ParsedStmtContext()) &&
214 ((GNUAttributeLoc.isValid() && !(HaveAttrs && AllAttrsAreStmtAttrs)) ||
215 isDeclarationStatement())) {
216 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
217 DeclGroupPtrTy Decl;
218 if (GNUAttributeLoc.isValid()) {
219 DeclStart = GNUAttributeLoc;
220 Decl = ParseDeclaration(Context: DeclaratorContext::Block, DeclEnd, DeclAttrs&: CXX11Attrs,
221 DeclSpecAttrs&: GNUAttrs, DeclSpecStart: &GNUAttributeLoc);
222 } else {
223 Decl = ParseDeclaration(Context: DeclaratorContext::Block, DeclEnd, DeclAttrs&: CXX11Attrs,
224 DeclSpecAttrs&: GNUAttrs);
225 }
226 if (CXX11Attrs.Range.getBegin().isValid()) {
227 // Order of C++11 and GNU attributes is may be arbitrary.
228 DeclStart = GNUAttrs.Range.getBegin().isInvalid()
229 ? CXX11Attrs.Range.getBegin()
230 : std::min(a: CXX11Attrs.Range.getBegin(),
231 b: GNUAttrs.Range.getBegin());
232 } else if (GNUAttrs.Range.getBegin().isValid())
233 DeclStart = GNUAttrs.Range.getBegin();
234 return Actions.ActOnDeclStmt(Decl, StartLoc: DeclStart, EndLoc: DeclEnd);
235 }
236
237 if (Tok.is(K: tok::r_brace)) {
238 Diag(Tok, DiagID: diag::err_expected_statement);
239 return StmtError();
240 }
241
242 switch (Tok.getKind()) {
243#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
244#include "clang/Basic/BuiltinTraits.inc"
245 if (NextToken().is(K: tok::less)) {
246 Tok.setKind(tok::identifier);
247 Diag(Tok, DiagID: diag::ext_keyword_as_ident)
248 << Tok.getIdentifierInfo()->getName() << 0;
249 goto ParseIdentifier;
250 }
251 [[fallthrough]];
252 default:
253 return ParseExprStatement(StmtCtx);
254 }
255 }
256
257 case tok::kw___attribute: {
258 GNUAttributeLoc = Tok.getLocation();
259 ParseGNUAttributes(Attrs&: GNUAttrs);
260 goto Retry;
261 }
262
263 case tok::kw_template: {
264 if (NextToken().is(K: tok::kw_for)) {
265 // Expansion statements are not backported for now.
266 if (!getLangOpts().CPlusPlus26) {
267 Diag(Loc: Tok.getLocation(), DiagID: diag::err_expansion_stmt_requires_cxx2c);
268
269 // Trying to parse this as a regular 'for' statement instead yields
270 // better error recovery.
271 ConsumeToken();
272 return ParseForStatement(TrailingElseLoc, PrecedingLabel);
273 }
274
275 SourceLocation TemplateLoc = ConsumeToken();
276 return ParseExpansionStatement(TrailingElseLoc, PrecedingLabel,
277 TemplateLoc);
278 }
279
280 SourceLocation DeclEnd;
281 ParseTemplateDeclarationOrSpecialization(Context: DeclaratorContext::Block, DeclEnd,
282 AS: getAccessSpecifierIfPresent());
283 return StmtError();
284 }
285
286 case tok::kw_case: // C99 6.8.1: labeled-statement
287 return ParseCaseStatement(StmtCtx);
288 case tok::kw_default: // C99 6.8.1: labeled-statement
289 return ParseDefaultStatement(StmtCtx);
290
291 case tok::l_brace: // C99 6.8.2: compound-statement
292 return ParseCompoundStatement();
293 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
294 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
295 return Actions.ActOnNullStmt(SemiLoc: ConsumeToken(), HasLeadingEmptyMacro);
296 }
297
298 case tok::kw_if: // C99 6.8.4.1: if-statement
299 return ParseIfStatement(TrailingElseLoc);
300 case tok::kw_switch: // C99 6.8.4.2: switch-statement
301 return ParseSwitchStatement(TrailingElseLoc, PrecedingLabel);
302
303 case tok::kw_while: // C99 6.8.5.1: while-statement
304 return ParseWhileStatement(TrailingElseLoc, PrecedingLabel);
305 case tok::kw_do: // C99 6.8.5.2: do-statement
306 Res = ParseDoStatement(PrecedingLabel);
307 SemiError = "do/while";
308 break;
309 case tok::kw_for: // C99 6.8.5.3: for-statement
310 // Correct 'for template' to 'template for'.
311 if (NextToken().is(K: tok::kw_template)) {
312 Diag(Loc: Tok.getLocation(), DiagID: diag::err_for_template)
313 << FixItHint::CreateReplacement(
314 RemoveRange: SourceRange(Tok.getLocation(), NextToken().getEndLoc()),
315 Code: "template for");
316 Tok.setKind(tok::kw_template);
317 SourceLocation TemplateLoc = ConsumeToken();
318 Tok.setKind(tok::kw_for);
319 return ParseExpansionStatement(TrailingElseLoc, PrecedingLabel,
320 TemplateLoc);
321 }
322
323 return ParseForStatement(TrailingElseLoc, PrecedingLabel);
324
325 case tok::kw_goto: // C99 6.8.6.1: goto-statement
326 Res = ParseGotoStatement();
327 SemiError = "goto";
328 break;
329 case tok::kw_continue: // C99 6.8.6.2: continue-statement
330 Res = ParseContinueStatement();
331 SemiError = "continue";
332 break;
333 case tok::kw_break: // C99 6.8.6.3: break-statement
334 Res = ParseBreakStatement();
335 SemiError = "break";
336 break;
337 case tok::kw_return: // C99 6.8.6.4: return-statement
338 Res = ParseReturnStatement();
339 SemiError = "return";
340 break;
341 case tok::kw_co_return: // C++ Coroutines: co_return statement
342 Res = ParseReturnStatement();
343 SemiError = "co_return";
344 break;
345 case tok::kw__Defer: // C defer TS: defer-statement
346 return ParseDeferStatement(TrailingElseLoc);
347
348 case tok::kw_asm: {
349 for (const ParsedAttr &AL : CXX11Attrs)
350 // Could be relaxed if asm-related regular keyword attributes are
351 // added later.
352 (AL.isRegularKeywordAttribute()
353 ? Diag(Loc: AL.getRange().getBegin(), DiagID: diag::err_keyword_not_allowed)
354 : Diag(Loc: AL.getRange().getBegin(), DiagID: diag::warn_attribute_ignored))
355 << AL;
356 // Prevent these from being interpreted as statement attributes later on.
357 CXX11Attrs.clear();
358 ProhibitAttributes(Attrs&: GNUAttrs);
359 bool msAsm = false;
360 Res = ParseAsmStatement(msAsm);
361 if (msAsm) return Res;
362 SemiError = "asm";
363 break;
364 }
365
366 case tok::kw___if_exists:
367 case tok::kw___if_not_exists:
368 ProhibitAttributes(Attrs&: CXX11Attrs);
369 ProhibitAttributes(Attrs&: GNUAttrs);
370 ParseMicrosoftIfExistsStatement(Stmts);
371 // An __if_exists block is like a compound statement, but it doesn't create
372 // a new scope.
373 return StmtEmpty();
374
375 case tok::kw_try: // C++ 15: try-block
376 return ParseCXXTryBlock();
377
378 case tok::kw___try:
379 ProhibitAttributes(Attrs&: CXX11Attrs);
380 ProhibitAttributes(Attrs&: GNUAttrs);
381 return ParseSEHTryBlock();
382
383 case tok::kw___leave:
384 Res = ParseSEHLeaveStatement();
385 SemiError = "__leave";
386 break;
387
388 case tok::annot_pragma_vis:
389 ProhibitAttributes(Attrs&: CXX11Attrs);
390 ProhibitAttributes(Attrs&: GNUAttrs);
391 HandlePragmaVisibility();
392 return StmtEmpty();
393
394 case tok::annot_pragma_pack:
395 ProhibitAttributes(Attrs&: CXX11Attrs);
396 ProhibitAttributes(Attrs&: GNUAttrs);
397 HandlePragmaPack();
398 return StmtEmpty();
399
400 case tok::annot_pragma_msstruct:
401 ProhibitAttributes(Attrs&: CXX11Attrs);
402 ProhibitAttributes(Attrs&: GNUAttrs);
403 HandlePragmaMSStruct();
404 return StmtEmpty();
405
406 case tok::annot_pragma_align:
407 ProhibitAttributes(Attrs&: CXX11Attrs);
408 ProhibitAttributes(Attrs&: GNUAttrs);
409 HandlePragmaAlign();
410 return StmtEmpty();
411
412 case tok::annot_pragma_weak:
413 ProhibitAttributes(Attrs&: CXX11Attrs);
414 ProhibitAttributes(Attrs&: GNUAttrs);
415 HandlePragmaWeak();
416 return StmtEmpty();
417
418 case tok::annot_pragma_weakalias:
419 ProhibitAttributes(Attrs&: CXX11Attrs);
420 ProhibitAttributes(Attrs&: GNUAttrs);
421 HandlePragmaWeakAlias();
422 return StmtEmpty();
423
424 case tok::annot_pragma_redefine_extname:
425 ProhibitAttributes(Attrs&: CXX11Attrs);
426 ProhibitAttributes(Attrs&: GNUAttrs);
427 HandlePragmaRedefineExtname();
428 return StmtEmpty();
429
430 case tok::annot_pragma_fp_contract:
431 ProhibitAttributes(Attrs&: CXX11Attrs);
432 ProhibitAttributes(Attrs&: GNUAttrs);
433 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope) << "fp_contract";
434 ConsumeAnnotationToken();
435 return StmtError();
436
437 case tok::annot_pragma_fp:
438 ProhibitAttributes(Attrs&: CXX11Attrs);
439 ProhibitAttributes(Attrs&: GNUAttrs);
440 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope) << "clang fp";
441 ConsumeAnnotationToken();
442 return StmtError();
443
444 case tok::annot_pragma_fenv_access:
445 case tok::annot_pragma_fenv_access_ms:
446 ProhibitAttributes(Attrs&: CXX11Attrs);
447 ProhibitAttributes(Attrs&: GNUAttrs);
448 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope)
449 << (Kind == tok::annot_pragma_fenv_access ? "STDC FENV_ACCESS"
450 : "fenv_access");
451 ConsumeAnnotationToken();
452 return StmtEmpty();
453
454 case tok::annot_pragma_fenv_round:
455 ProhibitAttributes(Attrs&: CXX11Attrs);
456 ProhibitAttributes(Attrs&: GNUAttrs);
457 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope) << "STDC FENV_ROUND";
458 ConsumeAnnotationToken();
459 return StmtError();
460
461 case tok::annot_pragma_cx_limited_range:
462 ProhibitAttributes(Attrs&: CXX11Attrs);
463 ProhibitAttributes(Attrs&: GNUAttrs);
464 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope)
465 << "STDC CX_LIMITED_RANGE";
466 ConsumeAnnotationToken();
467 return StmtError();
468
469 case tok::annot_pragma_float_control:
470 ProhibitAttributes(Attrs&: CXX11Attrs);
471 ProhibitAttributes(Attrs&: GNUAttrs);
472 Diag(Tok, DiagID: diag::err_pragma_file_or_compound_scope) << "float_control";
473 ConsumeAnnotationToken();
474 return StmtError();
475
476 case tok::annot_pragma_opencl_extension:
477 ProhibitAttributes(Attrs&: CXX11Attrs);
478 ProhibitAttributes(Attrs&: GNUAttrs);
479 HandlePragmaOpenCLExtension();
480 return StmtEmpty();
481
482 case tok::annot_pragma_captured:
483 ProhibitAttributes(Attrs&: CXX11Attrs);
484 ProhibitAttributes(Attrs&: GNUAttrs);
485 return HandlePragmaCaptured();
486
487 case tok::annot_pragma_openmp:
488 // Prohibit attributes that are not OpenMP attributes, but only before
489 // processing a #pragma omp clause.
490 ProhibitAttributes(Attrs&: CXX11Attrs);
491 ProhibitAttributes(Attrs&: GNUAttrs);
492 [[fallthrough]];
493 case tok::annot_attr_openmp:
494 // Do not prohibit attributes if they were OpenMP attributes.
495 return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
496
497 case tok::annot_pragma_openacc:
498 return ParseOpenACCDirectiveStmt();
499
500 case tok::annot_pragma_ms_pointers_to_members:
501 ProhibitAttributes(Attrs&: CXX11Attrs);
502 ProhibitAttributes(Attrs&: GNUAttrs);
503 HandlePragmaMSPointersToMembers();
504 return StmtEmpty();
505
506 case tok::annot_pragma_ms_pragma:
507 ProhibitAttributes(Attrs&: CXX11Attrs);
508 ProhibitAttributes(Attrs&: GNUAttrs);
509 HandlePragmaMSPragma();
510 return StmtEmpty();
511
512 case tok::annot_pragma_ms_vtordisp:
513 ProhibitAttributes(Attrs&: CXX11Attrs);
514 ProhibitAttributes(Attrs&: GNUAttrs);
515 HandlePragmaMSVtorDisp();
516 return StmtEmpty();
517
518 case tok::annot_pragma_loop_hint:
519 ProhibitAttributes(Attrs&: CXX11Attrs);
520 ProhibitAttributes(Attrs&: GNUAttrs);
521 return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, Attrs&: CXX11Attrs,
522 PrecedingLabel);
523
524 case tok::annot_pragma_dump:
525 ProhibitAttributes(Attrs&: CXX11Attrs);
526 ProhibitAttributes(Attrs&: GNUAttrs);
527 HandlePragmaDump();
528 return StmtEmpty();
529
530 case tok::annot_pragma_attribute:
531 ProhibitAttributes(Attrs&: CXX11Attrs);
532 ProhibitAttributes(Attrs&: GNUAttrs);
533 HandlePragmaAttribute();
534 return StmtEmpty();
535 case tok::annot_pragma_export:
536 ProhibitAttributes(Attrs&: CXX11Attrs);
537 ProhibitAttributes(Attrs&: GNUAttrs);
538 HandlePragmaExport();
539 return StmtEmpty();
540 }
541
542 // If we reached this code, the statement must end in a semicolon.
543 if (!TryConsumeToken(Expected: tok::semi) && !Res.isInvalid()) {
544 // If the result was valid, then we do want to diagnose this. Use
545 // ExpectAndConsume to emit the diagnostic, even though we know it won't
546 // succeed.
547 ExpectAndConsume(ExpectedTok: tok::semi, Diag: diag::err_expected_semi_after_stmt, DiagMsg: SemiError);
548 // Skip until we see a } or ;, but don't eat it.
549 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
550 }
551
552 return Res;
553}
554
555StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
556 // If a case keyword is missing, this is where it should be inserted.
557 Token OldToken = Tok;
558
559 ExprStatementTokLoc = Tok.getLocation();
560
561 // expression[opt] ';'
562 ExprResult Expr(ParseExpression());
563 if (Expr.isInvalid()) {
564 // If the expression is invalid, skip ahead to the next semicolon or '}'.
565 // Not doing this opens us up to the possibility of infinite loops if
566 // ParseExpression does not consume any tokens.
567 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
568 if (Tok.is(K: tok::semi))
569 ConsumeToken();
570 return Actions.ActOnExprStmtError();
571 }
572
573 if (Tok.is(K: tok::colon) && getCurScope()->isSwitchScope() &&
574 Actions.CheckCaseExpression(E: Expr.get())) {
575 // If a constant expression is followed by a colon inside a switch block,
576 // suggest a missing case keyword.
577 Diag(Tok: OldToken, DiagID: diag::err_expected_case_before_expression)
578 << FixItHint::CreateInsertion(InsertionLoc: OldToken.getLocation(), Code: "case ");
579
580 // Recover parsing as a case statement.
581 return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
582 }
583
584 Token *CurTok = nullptr;
585 // If the semicolon is missing at the end of REPL input, we want to print
586 // the result. Note we shouldn't eat the token since the callback needs it.
587 // Preserve the data on EOF tokens that delimit cached declarations.
588 if (Tok.is(K: tok::eof) && getLangOpts().IncrementalExtensions &&
589 !Tok.getEofData())
590 CurTok = &Tok;
591 else
592 // Otherwise, eat the semicolon.
593 ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_after_expr);
594
595 StmtResult R = handleExprStmt(E: Expr, StmtCtx);
596 if (CurTok && !R.isInvalid())
597 CurTok->setEofData(R.get());
598
599 return R;
600}
601
602StmtResult Parser::ParseSEHTryBlock() {
603 assert(Tok.is(tok::kw___try) && "Expected '__try'");
604 SourceLocation TryLoc = ConsumeToken();
605
606 if (Tok.isNot(K: tok::l_brace))
607 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
608
609 StmtResult TryBlock(ParseCompoundStatement(
610 /*isStmtExpr=*/false,
611 ScopeFlags: Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
612 if (TryBlock.isInvalid())
613 return TryBlock;
614
615 StmtResult Handler;
616 if (isTokenSEHExcept()) {
617 SourceLocation Loc = ConsumeToken();
618 Handler = ParseSEHExceptBlock(Loc);
619 } else if (Tok.is(K: tok::kw___finally)) {
620 SourceLocation Loc = ConsumeToken();
621 Handler = ParseSEHFinallyBlock(Loc);
622 } else {
623 return StmtError(Diag(Tok, DiagID: diag::err_seh_expected_handler));
624 }
625
626 if(Handler.isInvalid())
627 return Handler;
628
629 return Actions.ActOnSEHTryBlock(IsCXXTry: false /* IsCXXTry */,
630 TryLoc,
631 TryBlock: TryBlock.get(),
632 Handler: Handler.get());
633}
634
635StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
636 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
637 raii2(Ident___exception_code, false),
638 raii3(Ident_GetExceptionCode, false);
639
640 if (ExpectAndConsume(ExpectedTok: tok::l_paren))
641 return StmtError();
642
643 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
644 Scope::SEHExceptScope);
645
646 if (getLangOpts().Borland) {
647 Ident__exception_info->setIsPoisoned(false);
648 Ident___exception_info->setIsPoisoned(false);
649 Ident_GetExceptionInfo->setIsPoisoned(false);
650 }
651
652 ExprResult FilterExpr;
653 {
654 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
655 Scope::SEHFilterScope);
656 FilterExpr = ParseExpression();
657 }
658
659 if (getLangOpts().Borland) {
660 Ident__exception_info->setIsPoisoned(true);
661 Ident___exception_info->setIsPoisoned(true);
662 Ident_GetExceptionInfo->setIsPoisoned(true);
663 }
664
665 if(FilterExpr.isInvalid())
666 return StmtError();
667
668 if (ExpectAndConsume(ExpectedTok: tok::r_paren))
669 return StmtError();
670
671 if (Tok.isNot(K: tok::l_brace))
672 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
673
674 StmtResult Block(ParseCompoundStatement());
675
676 if(Block.isInvalid())
677 return Block;
678
679 return Actions.ActOnSEHExceptBlock(Loc: ExceptLoc, FilterExpr: FilterExpr.get(), Block: Block.get());
680}
681
682StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
683 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
684 raii2(Ident___abnormal_termination, false),
685 raii3(Ident_AbnormalTermination, false);
686
687 if (Tok.isNot(K: tok::l_brace))
688 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
689
690 ParseScope FinallyScope(this, 0);
691 Actions.ActOnStartSEHFinallyBlock();
692
693 StmtResult Block(ParseCompoundStatement());
694 if(Block.isInvalid()) {
695 Actions.ActOnAbortSEHFinallyBlock();
696 return Block;
697 }
698
699 return Actions.ActOnFinishSEHFinallyBlock(Loc: FinallyLoc, Block: Block.get());
700}
701
702/// Handle __leave
703///
704/// seh-leave-statement:
705/// '__leave' ';'
706///
707StmtResult Parser::ParseSEHLeaveStatement() {
708 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
709 return Actions.ActOnSEHLeaveStmt(Loc: LeaveLoc, CurScope: getCurScope());
710}
711
712static void DiagnoseLabelFollowedByDecl(Parser &P, const Stmt *SubStmt) {
713 // When in C mode (but not Microsoft extensions mode), diagnose use of a
714 // label that is followed by a declaration rather than a statement.
715 if (!P.getLangOpts().CPlusPlus && !P.getLangOpts().MicrosoftExt &&
716 isa<DeclStmt>(Val: SubStmt)) {
717 P.DiagCompat(Loc: SubStmt->getBeginLoc(),
718 CompatDiagId: diag_compat::label_followed_by_declaration);
719 }
720}
721
722StmtResult Parser::ParseLabeledStatement(ParsedAttributes &Attrs,
723 ParsedStmtContext StmtCtx) {
724 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
725 "Not an identifier!");
726
727 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
728 // substatement in a selection statement, in place of the loop body in an
729 // iteration statement, or in place of the statement that follows a label.
730 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
731
732 Token IdentTok = Tok; // Save the whole token.
733 ConsumeToken(); // eat the identifier.
734
735 assert(Tok.is(tok::colon) && "Not a label!");
736
737 // identifier ':' statement
738 SourceLocation ColonLoc = ConsumeToken();
739
740 LabelDecl *LD = Actions.LookupOrCreateLabel(
741 II: IdentTok.getIdentifierInfo(), IdentLoc: IdentTok.getLocation(), /*GnuLabelLoc=*/{},
742 /*IsLabelStmt=*/true);
743
744 // Read label attributes, if present.
745 StmtResult SubStmt;
746 if (Tok.is(K: tok::kw___attribute)) {
747 ParsedAttributes TempAttrs(AttrFactory);
748 ParseGNUAttributes(Attrs&: TempAttrs);
749
750 // In C++, GNU attributes only apply to the label if they are followed by a
751 // semicolon, to disambiguate label attributes from attributes on a labeled
752 // declaration.
753 //
754 // This doesn't quite match what GCC does; if the attribute list is empty
755 // and followed by a semicolon, GCC will reject (it appears to parse the
756 // attributes as part of a statement in that case). That looks like a bug.
757 if (!getLangOpts().CPlusPlus || Tok.is(K: tok::semi))
758 Attrs.takeAllAppendingFrom(Other&: TempAttrs);
759 else {
760 StmtVector Stmts;
761 ParsedAttributes EmptyCXX11Attrs(AttrFactory);
762 SubStmt = ParseStatementOrDeclarationAfterAttributes(
763 Stmts, StmtCtx, /*TrailingElseLoc=*/nullptr, CXX11Attrs&: EmptyCXX11Attrs,
764 GNUAttrs&: TempAttrs, PrecedingLabel: LD);
765 if (!TempAttrs.empty() && !SubStmt.isInvalid())
766 SubStmt = Actions.ActOnAttributedStmt(AttrList: TempAttrs, SubStmt: SubStmt.get());
767 }
768 }
769
770 // The label may have no statement following it
771 if (SubStmt.isUnset() && Tok.is(K: tok::r_brace)) {
772 DiagnoseLabelAtEndOfCompoundStatement();
773 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
774 }
775
776 // If we've not parsed a statement yet, parse one now.
777 if (SubStmt.isUnset())
778 SubStmt = ParseStatement(TrailingElseLoc: nullptr, StmtCtx, PrecedingLabel: LD);
779
780 // Broken substmt shouldn't prevent the label from being added to the AST.
781 if (SubStmt.isInvalid())
782 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
783
784 DiagnoseLabelFollowedByDecl(P&: *this, SubStmt: SubStmt.get());
785
786 // If a label cannot appear here, just return the underlying statement. We
787 // already diagnosed this as invalid in LookupOrCreateLabel() above.
788 if (!LD) {
789 Attrs.clear();
790 return SubStmt.get();
791 }
792
793 Actions.ProcessDeclAttributeList(S: Actions.CurScope, D: LD, AttrList: Attrs);
794 Attrs.clear();
795
796 return Actions.ActOnLabelStmt(IdentLoc: IdentTok.getLocation(), TheDecl: LD, ColonLoc,
797 SubStmt: SubStmt.get());
798}
799
800StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
801 bool MissingCase, ExprResult Expr) {
802 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
803
804 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
805 // substatement in a selection statement, in place of the loop body in an
806 // iteration statement, or in place of the statement that follows a label.
807 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
808
809 // It is very common for code to contain many case statements recursively
810 // nested, as in (but usually without indentation):
811 // case 1:
812 // case 2:
813 // case 3:
814 // case 4:
815 // case 5: etc.
816 //
817 // Parsing this naively works, but is both inefficient and can cause us to run
818 // out of stack space in our recursive descent parser. As a special case,
819 // flatten this recursion into an iterative loop. This is complex and gross,
820 // but all the grossness is constrained to ParseCaseStatement (and some
821 // weirdness in the actions), so this is just local grossness :).
822
823 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
824 // example above.
825 StmtResult TopLevelCase(true);
826
827 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
828 // gets updated each time a new case is parsed, and whose body is unset so
829 // far. When parsing 'case 4', this is the 'case 3' node.
830 Stmt *DeepestParsedCaseStmt = nullptr;
831
832 // While we have case statements, eat and stack them.
833 SourceLocation ColonLoc;
834 do {
835 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
836 ConsumeToken(); // eat the 'case'.
837 ColonLoc = SourceLocation();
838
839 if (Tok.is(K: tok::code_completion)) {
840 cutOffParsing();
841 Actions.CodeCompletion().CodeCompleteCase(S: getCurScope());
842 return StmtError();
843 }
844
845 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
846 /// Disable this form of error recovery while we're parsing the case
847 /// expression.
848 ColonProtectionRAIIObject ColonProtection(*this);
849
850 ExprResult LHS;
851 if (!MissingCase) {
852 LHS = ParseCaseExpression(CaseLoc);
853 if (LHS.isInvalid()) {
854 // If constant-expression is parsed unsuccessfully, recover by skipping
855 // current case statement (moving to the colon that ends it).
856 if (!SkipUntil(T1: tok::colon, T2: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch))
857 return StmtError();
858 }
859 } else {
860 LHS = Actions.ActOnCaseExpr(CaseLoc, Val: Expr);
861 MissingCase = false;
862 }
863
864 // GNU case range extension.
865 SourceLocation DotDotDotLoc;
866 ExprResult RHS;
867 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: DotDotDotLoc)) {
868 // In C++, this is a GNU extension. In C, it's a C2y extension.
869 unsigned DiagId;
870 if (getLangOpts().CPlusPlus)
871 DiagId = diag::ext_gnu_case_range;
872 else if (getLangOpts().C2y)
873 DiagId = diag::warn_c23_compat_case_range;
874 else
875 DiagId = diag::ext_c2y_case_range;
876 Diag(Loc: DotDotDotLoc, DiagID: DiagId);
877 RHS = ParseCaseExpression(CaseLoc);
878 if (RHS.isInvalid()) {
879 if (!SkipUntil(T1: tok::colon, T2: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch))
880 return StmtError();
881 }
882 }
883
884 ColonProtection.restore();
885
886 if (TryConsumeToken(Expected: tok::colon, Loc&: ColonLoc)) {
887 } else if (TryConsumeToken(Expected: tok::semi, Loc&: ColonLoc) ||
888 TryConsumeToken(Expected: tok::coloncolon, Loc&: ColonLoc)) {
889 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
890 Diag(Loc: ColonLoc, DiagID: diag::err_expected_after)
891 << "'case'" << tok::colon
892 << FixItHint::CreateReplacement(RemoveRange: ColonLoc, Code: ":");
893 } else {
894 SourceLocation ExpectedLoc = getEndOfPreviousToken();
895
896 Diag(Loc: ExpectedLoc, DiagID: diag::err_expected_after)
897 << "'case'" << tok::colon
898 << FixItHint::CreateInsertion(InsertionLoc: ExpectedLoc, Code: ":");
899
900 ColonLoc = ExpectedLoc;
901 }
902
903 StmtResult Case =
904 Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
905
906 // If we had a sema error parsing this case, then just ignore it and
907 // continue parsing the sub-stmt.
908 if (Case.isInvalid()) {
909 if (TopLevelCase.isInvalid()) // No parsed case stmts.
910 return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
911 // Otherwise, just don't add it as a nested case.
912 } else {
913 // If this is the first case statement we parsed, it becomes TopLevelCase.
914 // Otherwise we link it into the current chain.
915 Stmt *NextDeepest = Case.get();
916 if (TopLevelCase.isInvalid())
917 TopLevelCase = Case;
918 else
919 Actions.ActOnCaseStmtBody(CaseStmt: DeepestParsedCaseStmt, SubStmt: Case.get());
920 DeepestParsedCaseStmt = NextDeepest;
921 }
922
923 // Handle all case statements.
924 } while (Tok.is(K: tok::kw_case));
925
926 // If we found a non-case statement, start by parsing it.
927 StmtResult SubStmt;
928
929 if (Tok.is(K: tok::r_brace)) {
930 // "switch (X) { case 4: }", is valid and is treated as if label was
931 // followed by a null statement.
932 DiagnoseLabelAtEndOfCompoundStatement();
933 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
934 } else {
935 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
936 }
937
938 // Install the body into the most deeply-nested case.
939 if (DeepestParsedCaseStmt) {
940 // Broken sub-stmt shouldn't prevent forming the case statement properly.
941 if (SubStmt.isInvalid())
942 SubStmt = Actions.ActOnNullStmt(SemiLoc: SourceLocation());
943 DiagnoseLabelFollowedByDecl(P&: *this, SubStmt: SubStmt.get());
944 Actions.ActOnCaseStmtBody(CaseStmt: DeepestParsedCaseStmt, SubStmt: SubStmt.get());
945 }
946
947 // Return the top level parsed statement tree.
948 return TopLevelCase;
949}
950
951StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
952 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
953
954 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
955 // substatement in a selection statement, in place of the loop body in an
956 // iteration statement, or in place of the statement that follows a label.
957 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
958
959 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
960
961 SourceLocation ColonLoc;
962 if (TryConsumeToken(Expected: tok::colon, Loc&: ColonLoc)) {
963 } else if (TryConsumeToken(Expected: tok::semi, Loc&: ColonLoc)) {
964 // Treat "default;" as a typo for "default:".
965 Diag(Loc: ColonLoc, DiagID: diag::err_expected_after)
966 << "'default'" << tok::colon
967 << FixItHint::CreateReplacement(RemoveRange: ColonLoc, Code: ":");
968 } else {
969 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(Loc: PrevTokLocation);
970 Diag(Loc: ExpectedLoc, DiagID: diag::err_expected_after)
971 << "'default'" << tok::colon
972 << FixItHint::CreateInsertion(InsertionLoc: ExpectedLoc, Code: ":");
973 ColonLoc = ExpectedLoc;
974 }
975
976 StmtResult SubStmt;
977
978 if (Tok.is(K: tok::r_brace)) {
979 // "switch (X) {... default: }", is valid and is treated as if label was
980 // followed by a null statement.
981 DiagnoseLabelAtEndOfCompoundStatement();
982 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
983 } else {
984 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
985 }
986
987 // Broken sub-stmt shouldn't prevent forming the case statement properly.
988 if (SubStmt.isInvalid())
989 SubStmt = Actions.ActOnNullStmt(SemiLoc: ColonLoc);
990
991 DiagnoseLabelFollowedByDecl(P&: *this, SubStmt: SubStmt.get());
992 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
993 SubStmt: SubStmt.get(), CurScope: getCurScope());
994}
995
996StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
997 return ParseCompoundStatement(isStmtExpr,
998 ScopeFlags: Scope::DeclScope | Scope::CompoundStmtScope);
999}
1000
1001StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
1002 unsigned ScopeFlags) {
1003 assert(Tok.is(tok::l_brace) && "Not a compound stmt!");
1004
1005 // Enter a scope to hold everything within the compound stmt. Compound
1006 // statements can always hold declarations.
1007 ParseScope CompoundScope(this, ScopeFlags);
1008
1009 // Parse the statements in the body.
1010 StmtResult R;
1011 StackHandler.runWithSufficientStackSpace(Loc: Tok.getLocation(), Fn: [&, this]() {
1012 R = ParseCompoundStatementBody(isStmtExpr);
1013 });
1014 return R;
1015}
1016
1017void Parser::ParseCompoundStatementLeadingPragmas() {
1018 bool checkForPragmas = true;
1019 while (checkForPragmas) {
1020 switch (Tok.getKind()) {
1021 case tok::annot_pragma_vis:
1022 HandlePragmaVisibility();
1023 break;
1024 case tok::annot_pragma_pack:
1025 HandlePragmaPack();
1026 break;
1027 case tok::annot_pragma_msstruct:
1028 HandlePragmaMSStruct();
1029 break;
1030 case tok::annot_pragma_align:
1031 HandlePragmaAlign();
1032 break;
1033 case tok::annot_pragma_weak:
1034 HandlePragmaWeak();
1035 break;
1036 case tok::annot_pragma_weakalias:
1037 HandlePragmaWeakAlias();
1038 break;
1039 case tok::annot_pragma_redefine_extname:
1040 HandlePragmaRedefineExtname();
1041 break;
1042 case tok::annot_pragma_opencl_extension:
1043 HandlePragmaOpenCLExtension();
1044 break;
1045 case tok::annot_pragma_fp_contract:
1046 HandlePragmaFPContract();
1047 break;
1048 case tok::annot_pragma_fp:
1049 HandlePragmaFP();
1050 break;
1051 case tok::annot_pragma_fenv_access:
1052 case tok::annot_pragma_fenv_access_ms:
1053 HandlePragmaFEnvAccess();
1054 break;
1055 case tok::annot_pragma_fenv_round:
1056 HandlePragmaFEnvRound();
1057 break;
1058 case tok::annot_pragma_cx_limited_range:
1059 HandlePragmaCXLimitedRange();
1060 break;
1061 case tok::annot_pragma_float_control:
1062 HandlePragmaFloatControl();
1063 break;
1064 case tok::annot_pragma_ms_pointers_to_members:
1065 HandlePragmaMSPointersToMembers();
1066 break;
1067 case tok::annot_pragma_ms_pragma:
1068 HandlePragmaMSPragma();
1069 break;
1070 case tok::annot_pragma_ms_vtordisp:
1071 HandlePragmaMSVtorDisp();
1072 break;
1073 case tok::annot_pragma_dump:
1074 HandlePragmaDump();
1075 break;
1076 case tok::annot_pragma_export:
1077 HandlePragmaExport();
1078 break;
1079 default:
1080 checkForPragmas = false;
1081 break;
1082 }
1083 }
1084
1085}
1086
1087void Parser::DiagnoseLabelAtEndOfCompoundStatement() {
1088 DiagCompat(Tok, CompatDiagId: getLangOpts().CPlusPlus
1089 ? diag_compat::cxx_label_at_end_of_compound_statement
1090 : diag_compat::c_label_at_end_of_compound_statement);
1091}
1092
1093bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
1094 if (!Tok.is(K: tok::semi))
1095 return false;
1096
1097 SourceLocation StartLoc = Tok.getLocation();
1098 SourceLocation EndLoc;
1099
1100 while (Tok.is(K: tok::semi) && !Tok.hasLeadingEmptyMacro() &&
1101 Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
1102 EndLoc = Tok.getLocation();
1103
1104 // Don't just ConsumeToken() this tok::semi, do store it in AST.
1105 StmtResult R =
1106 ParseStatementOrDeclaration(Stmts, StmtCtx: ParsedStmtContext::SubStmt);
1107 if (R.isUsable())
1108 Stmts.push_back(Elt: R.get());
1109 }
1110
1111 // Did not consume any extra semi.
1112 if (EndLoc.isInvalid())
1113 return false;
1114
1115 Diag(Loc: StartLoc, DiagID: diag::warn_null_statement)
1116 << FixItHint::CreateRemoval(RemoveRange: SourceRange(StartLoc, EndLoc));
1117 return true;
1118}
1119
1120StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
1121 bool IsStmtExprResult = false;
1122 if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
1123 // Look ahead to see if the next two tokens close the statement expression;
1124 // if so, this expression statement is the last statement in a
1125 // statment expression.
1126 IsStmtExprResult = Tok.is(K: tok::r_brace) && NextToken().is(K: tok::r_paren);
1127 }
1128
1129 if (IsStmtExprResult)
1130 E = Actions.ActOnStmtExprResult(E);
1131 return Actions.ActOnExprStmt(Arg: E, /*DiscardedValue=*/!IsStmtExprResult);
1132}
1133
1134StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
1135 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
1136 Tok.getLocation(),
1137 "in compound statement ('{}')");
1138
1139 // Record the current FPFeatures, restore on leaving the
1140 // compound statement.
1141 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1142
1143 InMessageExpressionRAIIObject InMessage(*this, false);
1144 BalancedDelimiterTracker T(*this, tok::l_brace);
1145 if (T.consumeOpen())
1146 return StmtError();
1147
1148 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
1149
1150 // Parse any pragmas at the beginning of the compound statement.
1151 ParseCompoundStatementLeadingPragmas();
1152 Actions.ActOnAfterCompoundStatementLeadingPragmas();
1153
1154 StmtVector Stmts;
1155
1156 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1157 // only allowed at the start of a compound stmt regardless of the language.
1158 while (Tok.is(K: tok::kw___label__)) {
1159 SourceLocation LabelLoc = ConsumeToken();
1160
1161 SmallVector<Decl *, 4> DeclsInGroup;
1162 while (true) {
1163 if (Tok.isNot(K: tok::identifier)) {
1164 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
1165 break;
1166 }
1167
1168 IdentifierInfo *II = Tok.getIdentifierInfo();
1169 SourceLocation IdLoc = ConsumeToken();
1170 DeclsInGroup.push_back(Elt: Actions.LookupOrCreateLabel(II, IdentLoc: IdLoc, GnuLabelLoc: LabelLoc));
1171
1172 if (!TryConsumeToken(Expected: tok::comma))
1173 break;
1174 }
1175
1176 DeclSpec DS(AttrFactory);
1177 DeclGroupPtrTy Res =
1178 Actions.FinalizeDeclaratorGroup(S: getCurScope(), DS, Group: DeclsInGroup);
1179 StmtResult R = Actions.ActOnDeclStmt(Decl: Res, StartLoc: LabelLoc, EndLoc: Tok.getLocation());
1180
1181 ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_declaration);
1182 if (R.isUsable())
1183 Stmts.push_back(Elt: R.get());
1184 }
1185
1186 ParsedStmtContext SubStmtCtx =
1187 ParsedStmtContext::Compound |
1188 (isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());
1189
1190 bool LastIsError = false;
1191 while (!tryParseMisplacedModuleImport() && Tok.isNot(K: tok::r_brace) &&
1192 Tok.isNot(K: tok::eof)) {
1193 if (Tok.is(K: tok::annot_pragma_unused)) {
1194 HandlePragmaUnused();
1195 continue;
1196 }
1197
1198 if (ConsumeNullStmt(Stmts))
1199 continue;
1200
1201 StmtResult R;
1202 if (Tok.isNot(K: tok::kw___extension__)) {
1203 R = ParseStatementOrDeclaration(Stmts, StmtCtx: SubStmtCtx);
1204 } else {
1205 // __extension__ can start declarations and it can also be a unary
1206 // operator for expressions. Consume multiple __extension__ markers here
1207 // until we can determine which is which.
1208 // FIXME: This loses extension expressions in the AST!
1209 SourceLocation ExtLoc = ConsumeToken();
1210 while (Tok.is(K: tok::kw___extension__))
1211 ConsumeToken();
1212
1213 ParsedAttributes attrs(AttrFactory);
1214 MaybeParseCXX11Attributes(Attrs&: attrs, /*MightBeObjCMessageSend*/ OuterMightBeMessageSend: true);
1215
1216 // If this is the start of a declaration, parse it as such.
1217 if (isDeclarationStatement()) {
1218 // __extension__ silences extension warnings in the subdeclaration.
1219 // FIXME: Save the __extension__ on the decl as a node somehow?
1220 ExtensionRAIIObject O(Diags);
1221
1222 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1223 ParsedAttributes DeclSpecAttrs(AttrFactory);
1224 DeclGroupPtrTy Res = ParseDeclaration(Context: DeclaratorContext::Block, DeclEnd,
1225 DeclAttrs&: attrs, DeclSpecAttrs);
1226 R = Actions.ActOnDeclStmt(Decl: Res, StartLoc: DeclStart, EndLoc: DeclEnd);
1227 } else {
1228 // Otherwise this was a unary __extension__ marker.
1229 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1230
1231 if (Res.isInvalid()) {
1232 SkipUntil(T: tok::semi);
1233 continue;
1234 }
1235
1236 // Eat the semicolon at the end of stmt and convert the expr into a
1237 // statement.
1238 ExpectAndConsumeSemi(DiagID: diag::err_expected_semi_after_expr);
1239 R = handleExprStmt(E: Res, StmtCtx: SubStmtCtx);
1240 if (R.isUsable())
1241 R = Actions.ActOnAttributedStmt(AttrList: attrs, SubStmt: R.get());
1242 }
1243 }
1244
1245 if (R.isUsable())
1246 Stmts.push_back(Elt: R.get());
1247 LastIsError = R.isInvalid();
1248 }
1249 // StmtExpr needs to do copy initialization for last statement.
1250 // If last statement is invalid, the last statement in `Stmts` will be
1251 // incorrect. Then the whole compound statement should also be marked as
1252 // invalid to prevent subsequent errors.
1253 if (isStmtExpr && LastIsError && !Stmts.empty())
1254 return StmtError();
1255
1256 // Warn the user that using option `-ffp-eval-method=source` on a
1257 // 32-bit target and feature `sse` disabled, or using
1258 // `pragma clang fp eval_method=source` and feature `sse` disabled, is not
1259 // supported.
1260 if (!PP.getTargetInfo().supportSourceEvalMethod() &&
1261 (PP.getLastFPEvalPragmaLocation().isValid() ||
1262 PP.getCurrentFPEvalMethod() ==
1263 LangOptions::FPEvalMethodKind::FEM_Source))
1264 Diag(Loc: Tok.getLocation(),
1265 DiagID: diag::warn_no_support_for_eval_method_source_on_m32);
1266
1267 SourceLocation CloseLoc = Tok.getLocation();
1268
1269 // We broke out of the while loop because we found a '}' or EOF.
1270 if (!T.consumeClose()) {
1271 // If this is the '})' of a statement expression, check that it's written
1272 // in a sensible way.
1273 if (isStmtExpr && Tok.is(K: tok::r_paren))
1274 checkCompoundToken(FirstTokLoc: CloseLoc, FirstTokKind: tok::r_brace, Op: CompoundToken::StmtExprEnd);
1275 } else {
1276 // Recover by creating a compound statement with what we parsed so far,
1277 // instead of dropping everything and returning StmtError().
1278 }
1279
1280 if (T.getCloseLocation().isValid())
1281 CloseLoc = T.getCloseLocation();
1282
1283 return Actions.ActOnCompoundStmt(L: T.getOpenLocation(), R: CloseLoc,
1284 Elts: Stmts, isStmtExpr);
1285}
1286
1287bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1288 Sema::ConditionResult &Cond,
1289 SourceLocation Loc,
1290 Sema::ConditionKind CK,
1291 SourceLocation &LParenLoc,
1292 SourceLocation &RParenLoc) {
1293 BalancedDelimiterTracker T(*this, tok::l_paren);
1294 T.consumeOpen();
1295 SourceLocation Start = Tok.getLocation();
1296
1297 Cond = ParseCondition(InitStmt, Loc, CK, MissingOK: false);
1298
1299 // If the parser was confused by the condition and we don't have a ')', try to
1300 // recover by skipping ahead to a semi and bailing out. If condexp is
1301 // semantically invalid but we have well formed code, keep going.
1302 if (Cond.isInvalid() && Tok.isNot(K: tok::r_paren)) {
1303 SkipUntil(T: tok::semi);
1304 // Skipping may have stopped if it found the containing ')'. If so, we can
1305 // continue parsing the if statement.
1306 if (Tok.isNot(K: tok::r_paren))
1307 return true;
1308 }
1309
1310 if (Cond.isInvalid()) {
1311 ExprResult CondExpr = Actions.CreateRecoveryExpr(
1312 Begin: Start, End: Tok.getLocation() == Start ? Start : PrevTokLocation, SubExprs: {},
1313 T: Actions.PreferredConditionType(K: CK));
1314 if (!CondExpr.isInvalid())
1315 Cond = Actions.ActOnCondition(S: getCurScope(), Loc, SubExpr: CondExpr.get(), CK,
1316 /*MissingOK=*/false);
1317 }
1318
1319 if (!getLangOpts().CPlusPlus) {
1320 if (InitStmt != nullptr && InitStmt->isUsable()) {
1321 // Handle the 2 clauses of declaration: (clause1; clause2). We need to
1322 // allow NullStmt because that’s what we end up with if we have an empty
1323 // attribute-specifier-sequence, which is valid: if ([[]]; true).
1324 if (!isa<DeclStmt, AttributedStmt, NullStmt>(Val: InitStmt->get()))
1325 // C2y only permits declaration in the first clause of an if condition.
1326 Diag(Loc: InitStmt->get()->getBeginLoc(),
1327 DiagID: diag::err_c2y_first_condition_clause_is_not_declaration)
1328 << InitStmt->get()->getSourceRange();
1329
1330 if (Cond.get().first != nullptr)
1331 // C2y only permits expression in the second clause of an if condition.
1332 Diag(Loc: Cond.get().first->getBeginLoc(), DiagID: diag::err_expected_expression)
1333 << Cond.get().first->getSourceRange();
1334 } else if (Cond.get().first != nullptr)
1335 // Handle: if (int decl = 0) {}.
1336 DiagCompat(Loc: Cond.get().first->getBeginLoc(), CompatDiagId: diag_compat::decl_statement)
1337 << (CK == Sema::ConditionKind::Switch);
1338 }
1339
1340 if (Tok.is(K: tok::comma)) {
1341 Diag(Tok, DiagID: diag::err_c2y_multiple_declarations);
1342 // Skip until the next token is ')' (stop when current token is r_paren)
1343 while (Tok.isNot(K: tok::r_paren) && !Tok.is(K: tok::eof))
1344 ConsumeAnyToken();
1345 }
1346 // Either the condition is valid or the rparen is present.
1347 T.consumeClose();
1348 LParenLoc = T.getOpenLocation();
1349 RParenLoc = T.getCloseLocation();
1350
1351 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1352 // that all callers are looking for a statement after the condition, so ")"
1353 // isn't valid.
1354 while (Tok.is(K: tok::r_paren)) {
1355 Diag(Tok, DiagID: diag::err_extraneous_rparen_in_condition)
1356 << FixItHint::CreateRemoval(RemoveRange: Tok.getLocation());
1357 ConsumeParen();
1358 }
1359
1360 return false;
1361}
1362
1363namespace {
1364
1365enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };
1366
1367struct MisleadingIndentationChecker {
1368 Parser &P;
1369 SourceLocation StmtLoc;
1370 SourceLocation PrevLoc;
1371 unsigned NumDirectives;
1372 MisleadingStatementKind Kind;
1373 bool ShouldSkip;
1374 MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,
1375 SourceLocation SL)
1376 : P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()),
1377 NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K),
1378 ShouldSkip(P.getCurToken().is(K: tok::l_brace)) {
1379 if (!P.MisleadingIndentationElseLoc.isInvalid()) {
1380 StmtLoc = P.MisleadingIndentationElseLoc;
1381 P.MisleadingIndentationElseLoc = SourceLocation();
1382 }
1383 if (Kind == MSK_else && !ShouldSkip)
1384 P.MisleadingIndentationElseLoc = SL;
1385 }
1386
1387 /// Compute the column number will aligning tabs on TabStop (-ftabstop), this
1388 /// gives the visual indentation of the SourceLocation.
1389 static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) {
1390 unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop;
1391
1392 unsigned ColNo = SM.getSpellingColumnNumber(Loc);
1393 if (ColNo == 0 || TabStop == 1)
1394 return ColNo;
1395
1396 FileIDAndOffset FIDAndOffset = SM.getDecomposedLoc(Loc);
1397
1398 bool Invalid;
1399 StringRef BufData = SM.getBufferData(FID: FIDAndOffset.first, Invalid: &Invalid);
1400 if (Invalid)
1401 return 0;
1402
1403 const char *EndPos = BufData.data() + FIDAndOffset.second;
1404 // FileOffset are 0-based and Column numbers are 1-based
1405 assert(FIDAndOffset.second + 1 >= ColNo &&
1406 "Column number smaller than file offset?");
1407
1408 unsigned VisualColumn = 0; // Stored as 0-based column, here.
1409 // Loop from beginning of line up to Loc's file position, counting columns,
1410 // expanding tabs.
1411 for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;
1412 ++CurPos) {
1413 if (*CurPos == '\t')
1414 // Advance visual column to next tabstop.
1415 VisualColumn += (TabStop - VisualColumn % TabStop);
1416 else
1417 VisualColumn++;
1418 }
1419 return VisualColumn + 1;
1420 }
1421
1422 void Check() {
1423 Token Tok = P.getCurToken();
1424 if (P.getActions().getDiagnostics().isIgnored(
1425 DiagID: diag::warn_misleading_indentation, Loc: Tok.getLocation()) ||
1426 ShouldSkip || NumDirectives != P.getPreprocessor().getNumDirectives() ||
1427 Tok.isOneOf(Ks: tok::semi, Ks: tok::r_brace) || Tok.isAnnotation() ||
1428 Tok.getLocation().isMacroID() || PrevLoc.isMacroID() ||
1429 StmtLoc.isMacroID() ||
1430 (Kind == MSK_else && P.MisleadingIndentationElseLoc.isInvalid())) {
1431 P.MisleadingIndentationElseLoc = SourceLocation();
1432 return;
1433 }
1434 if (Kind == MSK_else)
1435 P.MisleadingIndentationElseLoc = SourceLocation();
1436
1437 SourceManager &SM = P.getPreprocessor().getSourceManager();
1438 unsigned PrevColNum = getVisualIndentation(SM, Loc: PrevLoc);
1439 unsigned CurColNum = getVisualIndentation(SM, Loc: Tok.getLocation());
1440 unsigned StmtColNum = getVisualIndentation(SM, Loc: StmtLoc);
1441
1442 if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 &&
1443 ((PrevColNum > StmtColNum && PrevColNum == CurColNum) ||
1444 !Tok.isAtStartOfLine()) &&
1445 SM.getPresumedLineNumber(Loc: StmtLoc) !=
1446 SM.getPresumedLineNumber(Loc: Tok.getLocation()) &&
1447 (Tok.isNot(K: tok::identifier) ||
1448 P.getPreprocessor().LookAhead(N: 0).isNot(K: tok::colon))) {
1449 P.Diag(Loc: Tok.getLocation(), DiagID: diag::warn_misleading_indentation) << Kind;
1450 P.Diag(Loc: StmtLoc, DiagID: diag::note_previous_statement);
1451 }
1452 }
1453};
1454
1455}
1456
1457StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1458 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1459 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1460
1461 bool IsConstexpr = false;
1462 bool IsConsteval = false;
1463 SourceLocation NotLocation;
1464 SourceLocation ConstevalLoc;
1465
1466 if (Tok.is(K: tok::kw_constexpr)) {
1467 // C23 supports constexpr keyword, but only for object definitions.
1468 if (getLangOpts().CPlusPlus) {
1469 DiagCompat(Tok, CompatDiagId: diag_compat::constexpr_if);
1470 IsConstexpr = true;
1471 ConsumeToken();
1472 }
1473 } else {
1474 if (Tok.is(K: tok::exclaim)) {
1475 NotLocation = ConsumeToken();
1476 }
1477
1478 if (Tok.is(K: tok::kw_consteval)) {
1479 DiagCompat(Tok, CompatDiagId: diag_compat::consteval_if);
1480 IsConsteval = true;
1481 ConstevalLoc = ConsumeToken();
1482 } else if (Tok.is(K: tok::code_completion)) {
1483 cutOffParsing();
1484 Actions.CodeCompletion().CodeCompleteKeywordAfterIf(
1485 AfterExclaim: NotLocation.isValid());
1486 return StmtError();
1487 }
1488 }
1489 if (!IsConsteval && (NotLocation.isValid() || Tok.isNot(K: tok::l_paren))) {
1490 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "if";
1491 SkipUntil(T: tok::semi);
1492 return StmtError();
1493 }
1494
1495 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1496
1497 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1498 // the case for C90.
1499 //
1500 // C++ 6.4p3:
1501 // A name introduced by a declaration in a condition is in scope from its
1502 // point of declaration until the end of the substatements controlled by the
1503 // condition.
1504 // C++ 3.3.2p4:
1505 // Names declared in the for-init-statement, and in the condition of if,
1506 // while, for, and switch statements are local to the if, while, for, or
1507 // switch statement (including the controlled statement).
1508 //
1509 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1510
1511 // Parse the condition.
1512 StmtResult InitStmt;
1513 Sema::ConditionResult Cond;
1514 SourceLocation LParen;
1515 SourceLocation RParen;
1516 std::optional<bool> ConstexprCondition;
1517 if (!IsConsteval) {
1518
1519 if (ParseParenExprOrCondition(InitStmt: &InitStmt, Cond, Loc: IfLoc,
1520 CK: IsConstexpr ? Sema::ConditionKind::ConstexprIf
1521 : Sema::ConditionKind::Boolean,
1522 LParenLoc&: LParen, RParenLoc&: RParen))
1523 return StmtError();
1524
1525 if (IsConstexpr)
1526 ConstexprCondition = Cond.getKnownValue();
1527 }
1528
1529 bool IsBracedThen = Tok.is(K: tok::l_brace);
1530
1531 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1532 // there is no compound stmt. C90 does not have this clause. We only do this
1533 // if the body isn't a compound statement to avoid push/pop in common cases.
1534 //
1535 // C++ 6.4p1:
1536 // The substatement in a selection-statement (each substatement, in the else
1537 // form of the if statement) implicitly defines a local scope.
1538 //
1539 // For C++ we create a scope for the condition and a new scope for
1540 // substatements because:
1541 // -When the 'then' scope exits, we want the condition declaration to still be
1542 // active for the 'else' scope too.
1543 // -Sema will detect name clashes by considering declarations of a
1544 // 'ControlScope' as part of its direct subscope.
1545 // -If we wanted the condition and substatement to be in the same scope, we
1546 // would have to notify ParseStatement not to create a new scope. It's
1547 // simpler to let it create a new scope.
1548 //
1549 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);
1550
1551 MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);
1552
1553 // Read the 'then' stmt.
1554 SourceLocation ThenStmtLoc = Tok.getLocation();
1555
1556 SourceLocation InnerStatementTrailingElseLoc;
1557 StmtResult ThenStmt;
1558 {
1559 bool ShouldEnter = ConstexprCondition && !*ConstexprCondition;
1560 Sema::ExpressionEvaluationContext Context =
1561 Sema::ExpressionEvaluationContext::DiscardedStatement;
1562 if (NotLocation.isInvalid() && IsConsteval) {
1563 Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
1564 ShouldEnter = true;
1565 }
1566
1567 EnterExpressionEvaluationContext PotentiallyDiscarded(
1568 Actions, Context, nullptr,
1569 Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
1570 ThenStmt = ParseStatement(TrailingElseLoc: &InnerStatementTrailingElseLoc);
1571 }
1572
1573 if (Tok.isNot(K: tok::kw_else))
1574 MIChecker.Check();
1575
1576 // Pop the 'if' scope if needed.
1577 InnerScope.Exit();
1578
1579 // If it has an else, parse it.
1580 SourceLocation ElseLoc;
1581 SourceLocation ElseStmtLoc;
1582 StmtResult ElseStmt;
1583
1584 if (Tok.is(K: tok::kw_else)) {
1585 if (TrailingElseLoc)
1586 *TrailingElseLoc = Tok.getLocation();
1587
1588 ElseLoc = ConsumeToken();
1589 ElseStmtLoc = Tok.getLocation();
1590
1591 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1592 // there is no compound stmt. C90 does not have this clause. We only do
1593 // this if the body isn't a compound statement to avoid push/pop in common
1594 // cases.
1595 //
1596 // C++ 6.4p1:
1597 // The substatement in a selection-statement (each substatement, in the else
1598 // form of the if statement) implicitly defines a local scope.
1599 //
1600 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1601 Tok.is(K: tok::l_brace));
1602
1603 MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);
1604 bool ShouldEnter = ConstexprCondition && *ConstexprCondition;
1605 Sema::ExpressionEvaluationContext Context =
1606 Sema::ExpressionEvaluationContext::DiscardedStatement;
1607 if (NotLocation.isValid() && IsConsteval) {
1608 Context = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
1609 ShouldEnter = true;
1610 }
1611
1612 EnterExpressionEvaluationContext PotentiallyDiscarded(
1613 Actions, Context, nullptr,
1614 Sema::ExpressionEvaluationContextRecord::EK_Other, ShouldEnter);
1615 ElseStmt = ParseStatement();
1616
1617 if (ElseStmt.isUsable())
1618 MIChecker.Check();
1619
1620 // Pop the 'else' scope if needed.
1621 InnerScope.Exit();
1622 } else if (Tok.is(K: tok::code_completion)) {
1623 cutOffParsing();
1624 Actions.CodeCompletion().CodeCompleteAfterIf(S: getCurScope(), IsBracedThen);
1625 return StmtError();
1626 } else if (InnerStatementTrailingElseLoc.isValid()) {
1627 Diag(Loc: InnerStatementTrailingElseLoc, DiagID: diag::warn_dangling_else);
1628 }
1629
1630 IfScope.Exit();
1631
1632 // If the then or else stmt is invalid and the other is valid (and present),
1633 // turn the invalid one into a null stmt to avoid dropping the other
1634 // part. If both are invalid, return error.
1635 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1636 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1637 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1638 // Both invalid, or one is invalid and other is non-present: return error.
1639 return StmtError();
1640 }
1641
1642 if (IsConsteval) {
1643 auto IsCompoundStatement = [](const Stmt *S) {
1644 if (const auto *Outer = dyn_cast_if_present<AttributedStmt>(Val: S))
1645 S = Outer->getSubStmt();
1646 return isa_and_nonnull<clang::CompoundStmt>(Val: S);
1647 };
1648
1649 if (!IsCompoundStatement(ThenStmt.get())) {
1650 Diag(Loc: ConstevalLoc, DiagID: diag::err_expected_after) << "consteval"
1651 << "{";
1652 return StmtError();
1653 }
1654 if (!ElseStmt.isUnset() && !IsCompoundStatement(ElseStmt.get())) {
1655 Diag(Loc: ElseLoc, DiagID: diag::err_expected_after) << "else"
1656 << "{";
1657 return StmtError();
1658 }
1659 }
1660
1661 // Now if either are invalid, replace with a ';'.
1662 if (ThenStmt.isInvalid())
1663 ThenStmt = Actions.ActOnNullStmt(SemiLoc: ThenStmtLoc);
1664 if (ElseStmt.isInvalid())
1665 ElseStmt = Actions.ActOnNullStmt(SemiLoc: ElseStmtLoc);
1666
1667 IfStatementKind Kind = IfStatementKind::Ordinary;
1668 if (IsConstexpr)
1669 Kind = IfStatementKind::Constexpr;
1670 else if (IsConsteval)
1671 Kind = NotLocation.isValid() ? IfStatementKind::ConstevalNegated
1672 : IfStatementKind::ConstevalNonNegated;
1673
1674 return Actions.ActOnIfStmt(IfLoc, StatementKind: Kind, LParenLoc: LParen, InitStmt: InitStmt.get(), Cond, RParenLoc: RParen,
1675 ThenVal: ThenStmt.get(), ElseLoc, ElseVal: ElseStmt.get());
1676}
1677
1678StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc,
1679 LabelDecl *PrecedingLabel) {
1680 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1681 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1682
1683 if (Tok.isNot(K: tok::l_paren)) {
1684 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "switch";
1685 SkipUntil(T: tok::semi);
1686 return StmtError();
1687 }
1688
1689 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1690
1691 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1692 // not the case for C90. Start the switch scope.
1693 //
1694 // C++ 6.4p3:
1695 // A name introduced by a declaration in a condition is in scope from its
1696 // point of declaration until the end of the substatements controlled by the
1697 // condition.
1698 // C++ 3.3.2p4:
1699 // Names declared in the for-init-statement, and in the condition of if,
1700 // while, for, and switch statements are local to the if, while, for, or
1701 // switch statement (including the controlled statement).
1702 //
1703 unsigned ScopeFlags = Scope::SwitchScope;
1704 if (C99orCXX)
1705 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1706 ParseScope SwitchScope(this, ScopeFlags);
1707
1708 // Parse the condition.
1709 StmtResult InitStmt;
1710 Sema::ConditionResult Cond;
1711 SourceLocation LParen;
1712 SourceLocation RParen;
1713 if (ParseParenExprOrCondition(InitStmt: &InitStmt, Cond, Loc: SwitchLoc,
1714 CK: Sema::ConditionKind::Switch, LParenLoc&: LParen, RParenLoc&: RParen))
1715 return StmtError();
1716
1717 StmtResult Switch = Actions.ActOnStartOfSwitchStmt(
1718 SwitchLoc, LParenLoc: LParen, InitStmt: InitStmt.get(), Cond, RParenLoc: RParen);
1719
1720 if (Switch.isInvalid()) {
1721 // Skip the switch body.
1722 // FIXME: This is not optimal recovery, but parsing the body is more
1723 // dangerous due to the presence of case and default statements, which
1724 // will have no place to connect back with the switch.
1725 if (Tok.is(K: tok::l_brace)) {
1726 ConsumeBrace();
1727 SkipUntil(T: tok::r_brace);
1728 } else
1729 SkipUntil(T: tok::semi);
1730 return Switch;
1731 }
1732
1733 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1734 // there is no compound stmt. C90 does not have this clause. We only do this
1735 // if the body isn't a compound statement to avoid push/pop in common cases.
1736 //
1737 // C++ 6.4p1:
1738 // The substatement in a selection-statement (each substatement, in the else
1739 // form of the if statement) implicitly defines a local scope.
1740 //
1741 // See comments in ParseIfStatement for why we create a scope for the
1742 // condition and a new scope for substatement in C++.
1743 //
1744 getCurScope()->EnterSwitchBody(PrecedingLabel);
1745 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(K: tok::l_brace));
1746
1747 // We have incremented the mangling number for the SwitchScope and the
1748 // InnerScope, which is one too many.
1749 if (C99orCXX)
1750 getCurScope()->decrementMSManglingNumber();
1751
1752 // Read the body statement.
1753 StmtResult Body(ParseStatement(TrailingElseLoc));
1754
1755 // Pop the scopes.
1756 InnerScope.Exit();
1757 SwitchScope.Exit();
1758
1759 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch: Switch.get(), Body: Body.get());
1760}
1761
1762StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc,
1763 LabelDecl *PrecedingLabel) {
1764 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1765 SourceLocation WhileLoc = Tok.getLocation();
1766 ConsumeToken(); // eat the 'while'.
1767
1768 if (Tok.isNot(K: tok::l_paren)) {
1769 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "while";
1770 SkipUntil(T: tok::semi);
1771 return StmtError();
1772 }
1773
1774 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1775
1776 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1777 // the case for C90. Start the loop scope.
1778 //
1779 // C++ 6.4p3:
1780 // A name introduced by a declaration in a condition is in scope from its
1781 // point of declaration until the end of the substatements controlled by the
1782 // condition.
1783 // C++ 3.3.2p4:
1784 // Names declared in the for-init-statement, and in the condition of if,
1785 // while, for, and switch statements are local to the if, while, for, or
1786 // switch statement (including the controlled statement).
1787 //
1788 unsigned ScopeFlags =
1789 Scope::ControlScope | (C99orCXX ? Scope::DeclScope : Scope::NoScope);
1790 ParseScope WhileScope(this, ScopeFlags);
1791
1792 // Parse the condition.
1793 Sema::ConditionResult Cond;
1794 SourceLocation LParen;
1795 SourceLocation RParen;
1796 if (ParseParenExprOrCondition(InitStmt: nullptr, Cond, Loc: WhileLoc,
1797 CK: Sema::ConditionKind::Boolean, LParenLoc&: LParen, RParenLoc&: RParen))
1798 return StmtError();
1799
1800 // OpenACC Restricts a while-loop inside of certain construct/clause
1801 // combinations, so diagnose that here in OpenACC mode.
1802 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
1803 getActions().OpenACC().ActOnWhileStmt(WhileLoc);
1804 getCurScope()->EnterLoopBody(PrecedingLabel);
1805
1806 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1807 // there is no compound stmt. C90 does not have this clause. We only do this
1808 // if the body isn't a compound statement to avoid push/pop in common cases.
1809 //
1810 // C++ 6.5p2:
1811 // The substatement in an iteration-statement implicitly defines a local scope
1812 // which is entered and exited each time through the loop.
1813 //
1814 // See comments in ParseIfStatement for why we create a scope for the
1815 // condition and a new scope for substatement in C++.
1816 //
1817 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(K: tok::l_brace));
1818
1819 MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);
1820
1821 // Read the body statement.
1822 StmtResult Body(ParseStatement(TrailingElseLoc));
1823
1824 if (Body.isUsable())
1825 MIChecker.Check();
1826 // Pop the body scope if needed.
1827 InnerScope.Exit();
1828 WhileScope.Exit();
1829
1830 if (Cond.isInvalid() || Body.isInvalid())
1831 return StmtError();
1832
1833 return Actions.ActOnWhileStmt(WhileLoc, LParenLoc: LParen, Cond, RParenLoc: RParen, Body: Body.get());
1834}
1835
1836StmtResult Parser::ParseDoStatement(LabelDecl *PrecedingLabel) {
1837 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1838 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1839
1840 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1841 // the case for C90. Start the loop scope.
1842 unsigned ScopeFlags = getLangOpts().C99 ? Scope::DeclScope : Scope::NoScope;
1843 ParseScope DoScope(this, ScopeFlags);
1844
1845 // OpenACC Restricts a do-while-loop inside of certain construct/clause
1846 // combinations, so diagnose that here in OpenACC mode.
1847 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
1848 getActions().OpenACC().ActOnDoStmt(DoLoc);
1849 getCurScope()->EnterLoopBody(PrecedingLabel);
1850
1851 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1852 // there is no compound stmt. C90 does not have this clause. We only do this
1853 // if the body isn't a compound statement to avoid push/pop in common cases.
1854 //
1855 // C++ 6.5p2:
1856 // The substatement in an iteration-statement implicitly defines a local scope
1857 // which is entered and exited each time through the loop.
1858 //
1859 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1860 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(K: tok::l_brace));
1861
1862 // Read the body statement.
1863 StmtResult Body(ParseStatement());
1864
1865 // Pop the body scope if needed.
1866 InnerScope.Exit();
1867
1868 // Reset this to disallow break/continue out of the condition.
1869 getCurScope()->LeaveLoopBody();
1870
1871 if (Tok.isNot(K: tok::kw_while)) {
1872 if (!Body.isInvalid()) {
1873 Diag(Tok, DiagID: diag::err_expected_while);
1874 Diag(Loc: DoLoc, DiagID: diag::note_matching) << "'do'";
1875 SkipUntil(T: tok::semi, Flags: StopBeforeMatch);
1876 }
1877 return StmtError();
1878 }
1879 SourceLocation WhileLoc = ConsumeToken();
1880
1881 if (Tok.isNot(K: tok::l_paren)) {
1882 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "do/while";
1883 SkipUntil(T: tok::semi, Flags: StopBeforeMatch);
1884 return StmtError();
1885 }
1886
1887 // Parse the parenthesized expression.
1888 BalancedDelimiterTracker T(*this, tok::l_paren);
1889 T.consumeOpen();
1890
1891 // A do-while expression is not a condition, so can't have attributes.
1892 DiagnoseAndSkipCXX11Attributes();
1893
1894 SourceLocation Start = Tok.getLocation();
1895 ExprResult Cond = ParseExpression();
1896 if (!Cond.isUsable()) {
1897 if (!Tok.isOneOf(Ks: tok::r_paren, Ks: tok::r_square, Ks: tok::r_brace))
1898 SkipUntil(T: tok::semi);
1899 Cond = Actions.CreateRecoveryExpr(
1900 Begin: Start, End: Start == Tok.getLocation() ? Start : PrevTokLocation, SubExprs: {},
1901 T: Actions.getASTContext().BoolTy);
1902 }
1903 T.consumeClose();
1904 DoScope.Exit();
1905
1906 if (Cond.isInvalid() || Body.isInvalid())
1907 return StmtError();
1908
1909 return Actions.ActOnDoStmt(DoLoc, Body: Body.get(), WhileLoc, CondLParen: T.getOpenLocation(),
1910 Cond: Cond.get(), CondRParen: T.getCloseLocation());
1911}
1912
1913bool Parser::isForRangeIdentifier() {
1914 assert(Tok.is(tok::identifier));
1915
1916 const Token &Next = NextToken();
1917 if (Next.is(K: tok::colon))
1918 return true;
1919
1920 if (Next.isOneOf(Ks: tok::l_square, Ks: tok::kw_alignas)) {
1921 TentativeParsingAction PA(*this);
1922 ConsumeToken();
1923 SkipCXX11Attributes();
1924 bool Result = Tok.is(K: tok::colon);
1925 PA.Revert();
1926 return Result;
1927 }
1928
1929 return false;
1930}
1931
1932void Parser::ParseForRangeInitializerAfterColon(ForRangeInit &FRI,
1933 ParsingDeclSpec *VarDeclSpec) {
1934 // Use an immediate function context if this is the initializer for a
1935 // constexpr variable in an expansion statement.
1936 auto Ctx = Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
1937 if (FRI.ExpansionStmt && VarDeclSpec && VarDeclSpec->hasConstexprSpecifier())
1938 Ctx = Sema::ExpressionEvaluationContext::ImmediateFunctionContext;
1939
1940 EnterExpressionEvaluationContext InitContext(
1941 Actions, Ctx,
1942 /*LambdaContextDecl=*/nullptr,
1943 Sema::ExpressionEvaluationContextRecord::EK_Other,
1944 getLangOpts().CPlusPlus23);
1945
1946 // P2718R0 - Lifetime extension in range-based for loops.
1947 if (getLangOpts().CPlusPlus23) {
1948 auto &LastRecord = Actions.currentEvaluationContext();
1949 LastRecord.InLifetimeExtendingContext = true;
1950 LastRecord.RebuildDefaultArgOrDefaultInit = true;
1951 }
1952
1953 if (FRI.ExpansionStmt) {
1954 // The expansion-initializer is not in a dependent context and should
1955 // thus be parsed in the parent context of the expansion statement.
1956 assert(Actions.CurContext->isExpansionStmt());
1957 Sema::ContextRAII CtxGuard(Actions, Actions.CurContext->getParent(),
1958 /*NewThis=*/false);
1959 FRI.RangeExpr =
1960 Tok.is(K: tok::l_brace) ? ParseExpansionInitList() : ParseExpression();
1961 FRI.RangeExpr = Actions.MaybeCreateExprWithCleanups(SubExpr: FRI.RangeExpr);
1962 } else if (Tok.is(K: tok::l_brace)) {
1963 FRI.RangeExpr = ParseBraceInitializer();
1964 } else {
1965 FRI.RangeExpr = ParseExpression();
1966 }
1967
1968 // Before c++23, ForRangeLifetimeExtendTemps should be empty.
1969 assert(getLangOpts().CPlusPlus23 ||
1970 Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps.empty());
1971
1972 // Move the collected materialized temporaries into ForRangeInit before
1973 // ForRangeInitContext exit.
1974 FRI.LifetimeExtendTemps =
1975 std::move(Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps);
1976}
1977
1978StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc,
1979 LabelDecl *PrecedingLabel,
1980 CXXExpansionStmtDecl *ESD) {
1981 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1982 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1983
1984 SourceLocation CoawaitLoc;
1985 if (Tok.is(K: tok::kw_co_await))
1986 CoawaitLoc = ConsumeToken();
1987
1988 if (Tok.isNot(K: tok::l_paren)) {
1989 Diag(Tok, DiagID: diag::err_expected_lparen_after) << "for";
1990 SkipUntil(T: tok::semi);
1991 return StmtError();
1992 }
1993
1994 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1995 getLangOpts().ObjC;
1996
1997 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1998 // the case for C90. Start the loop scope.
1999 //
2000 // C++ 6.4p3:
2001 // A name introduced by a declaration in a condition is in scope from its
2002 // point of declaration until the end of the substatements controlled by the
2003 // condition.
2004 // C++ 3.3.2p4:
2005 // Names declared in the for-init-statement, and in the condition of if,
2006 // while, for, and switch statements are local to the if, while, for, or
2007 // switch statement (including the controlled statement).
2008 // C++ 6.5.3p1:
2009 // Names declared in the for-init-statement are in the same declarative-region
2010 // as those declared in the condition.
2011 //
2012 // Always enter a ControlScope, even in C90 mode; this is harmless as it
2013 // doesn't cause declarations to bind to this scope. We use this to avoid
2014 // diagnosing a comma operator in e.g. the third part of a for loop when
2015 // '-Wcomma' is enabled.
2016 unsigned ScopeFlags = Scope::ControlScope |
2017 (C99orCXXorObjC ? Scope::DeclScope : Scope::NoScope);
2018 if (ESD)
2019 ScopeFlags |= Scope::TemplateParamScope | Scope::ExpansionStmtScope;
2020 ParseScope ForScope(this, ScopeFlags);
2021 BalancedDelimiterTracker T(*this, tok::l_paren);
2022 T.consumeOpen();
2023
2024 ExprResult Value;
2025
2026 bool ForEach = false;
2027 StmtResult FirstPart;
2028 Sema::ConditionResult SecondPart;
2029 ExprResult Collection;
2030 ForRangeInfo ForRangeInfo;
2031 FullExprArg ThirdPart(Actions);
2032 ForRangeInfo.ExpansionStmt = ESD;
2033
2034 // RAII helper to enter a context if we're parsing an expansion statement.
2035 //
2036 // This is required because some parts of an expansion statement (e.g. the
2037 // init-statement) are not in a dependent context and must thus be parsed in
2038 // the parent context.
2039 struct [[nodiscard]] ExpansionStmtContextRAII : Sema::ContextRAII {
2040 ExpansionStmtContextRAII(Sema &S, struct ForRangeInfo &Info,
2041 DeclContext *Ctx)
2042 : ContextRAII(S, Info.ExpansionStmt ? Ctx : S.CurContext,
2043 /*NewThis=*/false) {}
2044 };
2045
2046 assert(!ESD || Actions.CurContext->isExpansionStmt());
2047 if (Tok.is(K: tok::code_completion)) {
2048 cutOffParsing();
2049 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2050 S: getCurScope(), CompletionContext: C99orCXXorObjC ? SemaCodeCompletion::PCC_ForInit
2051 : SemaCodeCompletion::PCC_Expression);
2052 return StmtError();
2053 }
2054
2055 ParsedAttributes attrs(AttrFactory);
2056 MaybeParseCXX11Attributes(Attrs&: attrs);
2057
2058 SourceLocation EmptyInitStmtSemiLoc;
2059
2060 // Parse the first part of the for specifier.
2061 if (Tok.is(K: tok::semi)) { // for (;
2062 ProhibitAttributes(Attrs&: attrs);
2063 // no first part, eat the ';'.
2064 SourceLocation SemiLoc = Tok.getLocation();
2065 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
2066 EmptyInitStmtSemiLoc = SemiLoc;
2067 ConsumeToken();
2068 } else if (getLangOpts().CPlusPlus && Tok.is(K: tok::identifier) &&
2069 isForRangeIdentifier()) {
2070 // Note: This path is solely for error recovery if a user omits the type-id
2071 // and writes 'for (x : ...)'; normally, the for-range-declaration is parsed
2072 // in the 'if (isForInitDeclaration())' branch below.
2073 ProhibitAttributes(Attrs&: attrs);
2074 IdentifierInfo *Name = Tok.getIdentifierInfo();
2075 SourceLocation Loc = ConsumeToken();
2076 MaybeParseCXX11Attributes(Attrs&: attrs);
2077
2078 ForRangeInfo.ColonLoc = ConsumeToken();
2079 ParseForRangeInitializerAfterColon(FRI&: ForRangeInfo, /*VarDeclSpec=*/nullptr);
2080
2081 Diag(Loc, DiagID: diag::err_for_range_identifier)
2082 << (ForRangeInfo.ExpansionStmt != nullptr)
2083 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
2084 ? FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "auto &&")
2085 : FixItHint());
2086
2087 if (!ForRangeInfo.ExpansionStmt)
2088 ForRangeInfo.LoopVar =
2089 Actions.ActOnCXXForRangeIdentifier(S: getCurScope(), IdentLoc: Loc, Ident: Name, Attrs&: attrs);
2090 } else if (isForInitDeclaration()) { // for (int X = 4;
2091 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2092 ExpansionStmtContextRAII EnterParentContext{
2093 Actions, ForRangeInfo, Actions.CurContext->getParent()};
2094
2095 // Parse declaration, which eats the ';'.
2096 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
2097 Diag(Tok, DiagID: diag::ext_c99_variable_decl_in_for_loop);
2098 Diag(Tok, DiagID: diag::warn_gcc_variable_decl_in_for_loop);
2099 }
2100 DeclGroupPtrTy DG;
2101 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2102 if (!getLangOpts().CPlusPlus &&
2103 Tok.isOneOf(Ks: tok::kw_static_assert, Ks: tok::kw__Static_assert)) {
2104 ProhibitAttributes(Attrs&: attrs);
2105 Decl *D = ParseStaticAssertDeclaration(DeclEnd);
2106 DG = Actions.ConvertDeclToDeclGroup(Ptr: D);
2107 FirstPart = Actions.ActOnDeclStmt(Decl: DG, StartLoc: DeclStart, EndLoc: Tok.getLocation());
2108 } else if (Tok.is(K: tok::kw_using)) {
2109 DG = ParseAliasDeclarationInInitStatement(Context: DeclaratorContext::ForInit,
2110 Attrs&: attrs);
2111 FirstPart = Actions.ActOnDeclStmt(Decl: DG, StartLoc: DeclStart, EndLoc: Tok.getLocation());
2112 } else {
2113 // In C++0x, "for (T NS:a" might not be a typo for ::
2114 bool MightBeForRangeStmt = getLangOpts().CPlusPlus || getLangOpts().ObjC;
2115 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
2116 ParsedAttributes DeclSpecAttrs(AttrFactory);
2117 DG = ParseSimpleDeclaration(
2118 Context: DeclaratorContext::ForInit, DeclEnd, DeclAttrs&: attrs, DeclSpecAttrs, RequireSemi: false,
2119 FRI: MightBeForRangeStmt ? &ForRangeInfo : nullptr);
2120 FirstPart = Actions.ActOnDeclStmt(Decl: DG, StartLoc: DeclStart, EndLoc: Tok.getLocation());
2121 if (ForRangeInfo.ParsedForRangeDecl()) {
2122 DiagCompat(Loc: ForRangeInfo.ColonLoc, CompatDiagId: diag_compat::for_range);
2123 ForRangeInfo.LoopVar = FirstPart;
2124 FirstPart = StmtResult();
2125 } else if (Tok.is(K: tok::semi)) { // for (int x = 4;
2126 ConsumeToken();
2127 } else if ((ForEach = isTokIdentifier_in())) {
2128 Actions.ActOnForEachDeclStmt(Decl: DG);
2129 // ObjC: for (id x in expr)
2130 ConsumeToken(); // consume 'in'
2131
2132 if (Tok.is(K: tok::code_completion)) {
2133 cutOffParsing();
2134 Actions.CodeCompletion().CodeCompleteObjCForCollection(S: getCurScope(),
2135 IterationVar: DG);
2136 return StmtError();
2137 }
2138 Collection = ParseExpression();
2139 } else {
2140 Diag(Tok, DiagID: diag::err_expected_semi_for);
2141 }
2142 }
2143 } else {
2144 // An expression here should not be inside the expansion statement context.
2145 ExpansionStmtContextRAII EnterParentContext{
2146 Actions, ForRangeInfo, Actions.CurContext->getParent()};
2147 ProhibitAttributes(Attrs&: attrs);
2148 Value = ParseExpression();
2149
2150 ForEach = isTokIdentifier_in();
2151
2152 // Turn the expression into a stmt.
2153 if (!Value.isInvalid()) {
2154 if (ForEach)
2155 FirstPart = Actions.ActOnForEachLValueExpr(E: Value.get());
2156 else {
2157 // We already know this is not an init-statement within a for loop, so
2158 // if we are parsing a C++11 range-based for loop, we should treat this
2159 // expression statement as being a discarded value expression because
2160 // we will err below. This way we do not warn on an unused expression
2161 // that was an error in the first place, like with: for (expr : expr);
2162 bool IsRangeBasedFor =
2163 getLangOpts().CPlusPlus11 && !ForEach && Tok.is(K: tok::colon);
2164 FirstPart = Actions.ActOnExprStmt(Arg: Value, DiscardedValue: !IsRangeBasedFor);
2165 }
2166 }
2167
2168 if (Tok.is(K: tok::semi)) {
2169 ConsumeToken();
2170 } else if (ForEach) {
2171 ConsumeToken(); // consume 'in'
2172
2173 if (Tok.is(K: tok::code_completion)) {
2174 cutOffParsing();
2175 Actions.CodeCompletion().CodeCompleteObjCForCollection(S: getCurScope(),
2176 IterationVar: nullptr);
2177 return StmtError();
2178 }
2179 Collection = ParseExpression();
2180 } else if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::colon) && FirstPart.get()) {
2181 // User tried to write the reasonable, but ill-formed, for-range-statement
2182 // for (expr : expr) { ... }
2183 Diag(Tok, DiagID: diag::err_for_range_expected_decl)
2184 << (ESD != nullptr) << FirstPart.get()->getSourceRange();
2185 SkipUntil(T: tok::r_paren, Flags: StopBeforeMatch);
2186 SecondPart = Sema::ConditionError();
2187 } else {
2188 if (!Value.isInvalid()) {
2189 Diag(Tok, DiagID: diag::err_expected_semi_for);
2190 } else {
2191 // Skip until semicolon or rparen, don't consume it.
2192 SkipUntil(T: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch);
2193 if (Tok.is(K: tok::semi))
2194 ConsumeToken();
2195 }
2196 }
2197 }
2198
2199 // Parse the second part of the for specifier.
2200 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
2201 !SecondPart.isInvalid()) {
2202 // Parse the second part of the for specifier.
2203 if (Tok.is(K: tok::semi)) { // for (...;;
2204 // no second part.
2205 } else if (Tok.is(K: tok::r_paren)) {
2206 // missing both semicolons.
2207 } else {
2208 if (getLangOpts().CPlusPlus) {
2209 // C++2a: We've parsed an init-statement; we might have a
2210 // for-range-declaration next.
2211 bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
2212 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
2213 SourceLocation SecondPartStart = Tok.getLocation();
2214 Sema::ConditionKind CK = Sema::ConditionKind::Boolean;
2215 SecondPart = ParseCondition(
2216 /*InitStmt=*/nullptr, Loc: ForLoc, CK,
2217 // FIXME: recovery if we don't see another semi!
2218 /*MissingOK=*/true, FRI: MightBeForRangeStmt ? &ForRangeInfo : nullptr);
2219
2220 if (ForRangeInfo.ParsedForRangeDecl()) {
2221 DiagCompat(Loc: FirstPart.get() ? FirstPart.get()->getBeginLoc()
2222 : ForRangeInfo.ColonLoc,
2223 CompatDiagId: diag_compat::for_range_init_stmt)
2224 << (FirstPart.get() ? FirstPart.get()->getSourceRange()
2225 : SourceRange());
2226 if (EmptyInitStmtSemiLoc.isValid()) {
2227 Diag(Loc: EmptyInitStmtSemiLoc, DiagID: diag::warn_empty_init_statement)
2228 << /*for-loop*/ 2
2229 << FixItHint::CreateRemoval(RemoveRange: EmptyInitStmtSemiLoc);
2230 }
2231 }
2232
2233 if (SecondPart.isInvalid()) {
2234 ExprResult CondExpr = Actions.CreateRecoveryExpr(
2235 Begin: SecondPartStart,
2236 End: Tok.getLocation() == SecondPartStart ? SecondPartStart
2237 : PrevTokLocation,
2238 SubExprs: {}, T: Actions.PreferredConditionType(K: CK));
2239 if (!CondExpr.isInvalid())
2240 SecondPart = Actions.ActOnCondition(S: getCurScope(), Loc: ForLoc,
2241 SubExpr: CondExpr.get(), CK,
2242 /*MissingOK=*/false);
2243 }
2244
2245 } else {
2246 ExprResult SecondExpr = ParseExpression();
2247 if (SecondExpr.isInvalid())
2248 SecondPart = Sema::ConditionError();
2249 else
2250 SecondPart = Actions.ActOnCondition(
2251 S: getCurScope(), Loc: ForLoc, SubExpr: SecondExpr.get(),
2252 CK: Sema::ConditionKind::Boolean, /*MissingOK=*/true);
2253 }
2254 }
2255 }
2256
2257 // Parse the third part of the for statement.
2258 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
2259 if (Tok.isNot(K: tok::semi)) {
2260 if (!SecondPart.isInvalid())
2261 Diag(Tok, DiagID: diag::err_expected_semi_for);
2262 SkipUntil(T: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch);
2263 }
2264
2265 if (Tok.is(K: tok::semi)) {
2266 ConsumeToken();
2267 }
2268
2269 if (Tok.isNot(K: tok::r_paren)) { // for (...;...;)
2270 ExprResult Third = ParseExpression();
2271 // FIXME: The C++11 standard doesn't actually say that this is a
2272 // discarded-value expression, but it clearly should be.
2273 ThirdPart = Actions.MakeFullDiscardedValueExpr(Arg: Third.get());
2274 }
2275 }
2276 // Match the ')'.
2277 T.consumeClose();
2278
2279 // C++ Coroutines [stmt.iter]:
2280 // 'co_await' can only be used for a range-based for statement.
2281 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
2282 Diag(Loc: CoawaitLoc, DiagID: diag::err_for_co_await_not_range_for);
2283 CoawaitLoc = SourceLocation();
2284 }
2285
2286 if (CoawaitLoc.isValid() && getLangOpts().CPlusPlus20)
2287 Diag(Loc: CoawaitLoc, DiagID: diag::warn_deprecated_for_co_await);
2288
2289 // We need to perform most of the semantic analysis for a C++0x for-range
2290 // statememt before parsing the body, in order to be able to deduce the type
2291 // of an auto-typed loop variable.
2292 StmtResult ForRangeStmt;
2293 StmtResult ForEachStmt;
2294
2295 if (ESD) {
2296 ForRangeStmt = Actions.ActOnCXXExpansionStmtPattern(
2297 ESD, Init: FirstPart.get(), ExpansionVarStmt: ForRangeInfo.LoopVar.get(),
2298 ExpansionInitializer: ForRangeInfo.RangeExpr.get(), LParenLoc: T.getOpenLocation(),
2299 ColonLoc: ForRangeInfo.ColonLoc, RParenLoc: T.getCloseLocation(),
2300 LifetimeExtendTemps: ForRangeInfo.LifetimeExtendTemps);
2301 } else if (ForRangeInfo.ParsedForRangeDecl()) {
2302 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
2303 S: getCurScope(), ForLoc, CoawaitLoc, InitStmt: FirstPart.get(),
2304 LoopVar: ForRangeInfo.LoopVar.get(), ColonLoc: ForRangeInfo.ColonLoc,
2305 Collection: ForRangeInfo.RangeExpr.get(), RParenLoc: T.getCloseLocation(), Kind: Sema::BFRK_Build,
2306 LifetimeExtendTemps: ForRangeInfo.LifetimeExtendTemps);
2307 } else if (ForEach) {
2308 // Similarly, we need to do the semantic analysis for a for-range
2309 // statement immediately in order to close over temporaries correctly.
2310 ForEachStmt = Actions.ObjC().ActOnObjCForCollectionStmt(
2311 ForColLoc: ForLoc, First: FirstPart.get(), collection: Collection.get(), RParenLoc: T.getCloseLocation());
2312 } else {
2313 // In OpenMP loop region loop control variable must be captured and be
2314 // private. Perform analysis of first part (if any).
2315 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
2316 Actions.OpenMP().ActOnOpenMPLoopInitialization(ForLoc, Init: FirstPart.get());
2317 }
2318 }
2319
2320 // OpenACC Restricts a for-loop inside of certain construct/clause
2321 // combinations, so diagnose that here in OpenACC mode.
2322 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
2323 if (ESD)
2324 ; // Nothing.
2325 else if (ForRangeInfo.ParsedForRangeDecl())
2326 getActions().OpenACC().ActOnRangeForStmtBegin(ForLoc, RangeFor: ForRangeStmt.get());
2327 else
2328 getActions().OpenACC().ActOnForStmtBegin(
2329 ForLoc, First: FirstPart.get(), Second: SecondPart.get().second, Third: ThirdPart.get());
2330
2331 // Set this only right before parsing the body to disallow break/continue in
2332 // the other parts.
2333 getCurScope()->EnterLoopBody(PrecedingLabel);
2334
2335 bool BodyStartsWithAttr = Tok.isOneOf(Ks: tok::l_square, Ks: tok::kw___attribute);
2336 SourceLocation BodyBeginLoc = Tok.getLocation();
2337
2338 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2339 // there is no compound stmt. C90 does not have this clause. We only do this
2340 // if the body isn't a compound statement to avoid push/pop in common cases.
2341 //
2342 // C++ 6.5p2:
2343 // The substatement in an iteration-statement implicitly defines a local scope
2344 // which is entered and exited each time through the loop.
2345 //
2346 // See comments in ParseIfStatement for why we create a scope for
2347 // for-init-statement/condition and a new scope for substatement in C++.
2348 //
2349 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
2350 Tok.is(K: tok::l_brace));
2351
2352 // The body of the for loop has the same local mangling number as the
2353 // for-init-statement.
2354 // It will only be incremented if the body contains other things that would
2355 // normally increment the mangling number (like a compound statement).
2356 if (C99orCXXorObjC)
2357 getCurScope()->decrementMSManglingNumber();
2358
2359 MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
2360
2361 // Read the body statement.
2362 StmtResult Body(ParseStatement(TrailingElseLoc));
2363
2364 if (Body.isUsable())
2365 MIChecker.Check();
2366
2367 // Pop the body scope if needed.
2368 InnerScope.Exit();
2369
2370 getActions().OpenACC().ActOnForStmtEnd(ForLoc, Body);
2371
2372 // Leave the for-scope.
2373 ForScope.Exit();
2374
2375 if (Body.isInvalid())
2376 return StmtError();
2377
2378 if (ForEach)
2379 return Actions.ObjC().FinishObjCForCollectionStmt(ForCollection: ForEachStmt.get(),
2380 Body: Body.get());
2381
2382 if (ESD) {
2383 if (!ForRangeInfo.ParsedForRangeDecl()) {
2384 Diag(Loc: ForLoc, DiagID: diag::err_expansion_stmt_requires_range);
2385 return StmtError();
2386 }
2387
2388 // attribute-specifier without attribute (`[[]]`) isn't in AST.
2389 // `__declspec()` is only applied to declarations, so we can ignore it.
2390 if (!isa<CompoundStmt>(Val: Body.get()) || BodyStartsWithAttr)
2391 Diag(Loc: BodyBeginLoc,
2392 DiagID: isa<CompoundStmt>(Val: Body.get()->stripLabelLikeStatements())
2393 ? diag::ext_expansion_stmt_body_attr
2394 : diag::ext_expansion_stmt_body_not_compound_stmt);
2395
2396 return Actions.FinishCXXExpansionStmt(Expansion: ForRangeStmt.get(), Body: Body.get());
2397 }
2398
2399 if (ForRangeInfo.ParsedForRangeDecl())
2400 return Actions.FinishCXXForRangeStmt(ForRange: ForRangeStmt.get(), Body: Body.get());
2401
2402 return Actions.ActOnForStmt(ForLoc, LParenLoc: T.getOpenLocation(), First: FirstPart.get(),
2403 Second: SecondPart, Third: ThirdPart, RParenLoc: T.getCloseLocation(),
2404 Body: Body.get());
2405}
2406
2407StmtResult Parser::ParseGotoStatement() {
2408 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
2409 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
2410
2411 StmtResult Res;
2412 if (Tok.is(K: tok::identifier)) {
2413 LabelDecl *LD = Actions.LookupOrCreateLabel(II: Tok.getIdentifierInfo(),
2414 IdentLoc: Tok.getLocation());
2415 Res = Actions.ActOnGotoStmt(GotoLoc, LabelLoc: Tok.getLocation(), TheDecl: LD);
2416 ConsumeToken();
2417 } else if (Tok.is(K: tok::star)) {
2418 // GNU indirect goto extension.
2419 Diag(Tok, DiagID: diag::ext_gnu_indirect_goto);
2420 SourceLocation StarLoc = ConsumeToken();
2421 ExprResult R(ParseExpression());
2422 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
2423 SkipUntil(T: tok::semi, Flags: StopBeforeMatch);
2424 return StmtError();
2425 }
2426 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, DestExp: R.get());
2427 } else {
2428 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
2429 return StmtError();
2430 }
2431
2432 return Res;
2433}
2434
2435StmtResult Parser::ParseBreakOrContinueStatement(bool IsContinue) {
2436 SourceLocation KwLoc = ConsumeToken(); // Eat the keyword.
2437 SourceLocation LabelLoc;
2438 LabelDecl *Target = nullptr;
2439 if (Tok.is(K: tok::identifier)) {
2440 Target =
2441 Actions.LookupExistingLabel(II: Tok.getIdentifierInfo(), IdentLoc: Tok.getLocation());
2442 LabelLoc = ConsumeToken();
2443 if (!getLangOpts().NamedLoops)
2444 // TODO: Make this a compatibility/extension warning instead once the
2445 // syntax of this feature is finalised.
2446 Diag(Loc: LabelLoc, DiagID: diag::err_c2y_labeled_break_continue) << IsContinue;
2447 if (!Target) {
2448 Diag(Loc: LabelLoc, DiagID: diag::err_break_continue_label_not_found) << IsContinue;
2449 return StmtError();
2450 }
2451 }
2452
2453 if (IsContinue)
2454 return Actions.ActOnContinueStmt(ContinueLoc: KwLoc, CurScope: getCurScope(), Label: Target, LabelLoc);
2455 return Actions.ActOnBreakStmt(BreakLoc: KwLoc, CurScope: getCurScope(), Label: Target, LabelLoc);
2456}
2457
2458StmtResult Parser::ParseContinueStatement() {
2459 return ParseBreakOrContinueStatement(/*IsContinue=*/true);
2460}
2461
2462StmtResult Parser::ParseBreakStatement() {
2463 return ParseBreakOrContinueStatement(/*IsContinue=*/false);
2464}
2465
2466StmtResult Parser::ParseReturnStatement() {
2467 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
2468 "Not a return stmt!");
2469 bool IsCoreturn = Tok.is(K: tok::kw_co_return);
2470 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
2471
2472 ExprResult R;
2473 if (Tok.isNot(K: tok::semi)) {
2474 if (!IsCoreturn)
2475 PreferredType.enterReturn(S&: Actions, Tok: Tok.getLocation());
2476 // FIXME: Code completion for co_return.
2477 if (Tok.is(K: tok::code_completion) && !IsCoreturn) {
2478 cutOffParsing();
2479 Actions.CodeCompletion().CodeCompleteExpression(
2480 S: getCurScope(), PreferredType: PreferredType.get(Tok: Tok.getLocation()));
2481 return StmtError();
2482 }
2483
2484 if (Tok.is(K: tok::l_brace) && getLangOpts().CPlusPlus) {
2485 R = ParseInitializer();
2486 if (R.isUsable())
2487 DiagCompat(Loc: R.get()->getBeginLoc(),
2488 CompatDiagId: diag_compat::generalized_initializer_lists);
2489 } else
2490 R = ParseExpression();
2491 if (R.isInvalid()) {
2492 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
2493 return StmtError();
2494 }
2495 }
2496 if (IsCoreturn)
2497 return Actions.ActOnCoreturnStmt(S: getCurScope(), KwLoc: ReturnLoc, E: R.get());
2498 return Actions.ActOnReturnStmt(ReturnLoc, RetValExp: R.get(), CurScope: getCurScope());
2499}
2500
2501StmtResult Parser::ParseDeferStatement(SourceLocation *TrailingElseLoc) {
2502 assert(Tok.is(tok::kw__Defer));
2503 SourceLocation DeferLoc = ConsumeToken();
2504
2505 Actions.ActOnStartOfDeferStmt(DeferLoc, CurScope: getCurScope());
2506
2507 llvm::scope_exit OnError([&] { Actions.ActOnDeferStmtError(CurScope: getCurScope()); });
2508
2509 StmtResult Res = ParseStatement(TrailingElseLoc);
2510 if (!Res.isUsable())
2511 return StmtError();
2512
2513 // The grammar specifically calls for an unlabeled-statement here.
2514 if (auto *L = dyn_cast<LabelStmt>(Val: Res.get())) {
2515 Diag(Loc: L->getIdentLoc(), DiagID: diag::err_defer_ts_labeled_stmt);
2516 return StmtError();
2517 }
2518
2519 OnError.release();
2520 return Actions.ActOnEndOfDeferStmt(Body: Res.get(), CurScope: getCurScope());
2521}
2522
2523StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
2524 ParsedStmtContext StmtCtx,
2525 SourceLocation *TrailingElseLoc,
2526 ParsedAttributes &Attrs,
2527 LabelDecl *PrecedingLabel) {
2528 // Create temporary attribute list.
2529 ParsedAttributes TempAttrs(AttrFactory);
2530
2531 SourceLocation StartLoc = Tok.getLocation();
2532
2533 // Get loop hints and consume annotated token.
2534 while (Tok.is(K: tok::annot_pragma_loop_hint)) {
2535 LoopHint Hint;
2536 if (!HandlePragmaLoopHint(Hint))
2537 continue;
2538
2539 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
2540 ArgsUnion(Hint.ValueExpr)};
2541 TempAttrs.addNew(attrName: Hint.PragmaNameLoc->getIdentifierInfo(), attrRange: Hint.Range,
2542 scope: AttributeScopeInfo(), args: ArgHints, /*numArgs=*/4,
2543 form: ParsedAttr::Form::Pragma());
2544 }
2545
2546 // Get the next statement.
2547 MaybeParseCXX11Attributes(Attrs);
2548
2549 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2550 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
2551 Stmts, StmtCtx, TrailingElseLoc, CXX11Attrs&: Attrs, GNUAttrs&: EmptyDeclSpecAttrs,
2552 PrecedingLabel);
2553
2554 Attrs.takeAllPrependingFrom(Other&: TempAttrs);
2555
2556 // Start of attribute range may already be set for some invalid input.
2557 // See PR46336.
2558 if (Attrs.Range.getBegin().isInvalid())
2559 Attrs.Range.setBegin(StartLoc);
2560
2561 return S;
2562}
2563
2564Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2565 assert(Tok.is(tok::l_brace));
2566 SourceLocation LBraceLoc = Tok.getLocation();
2567
2568 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
2569 "parsing function body");
2570
2571 // Save and reset current vtordisp stack if we have entered a C++ method body.
2572 bool IsCXXMethod =
2573 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Val: Decl);
2574 Sema::PragmaStackSentinelRAII
2575 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2576
2577 // Do not enter a scope for the brace, as the arguments are in the same scope
2578 // (the function body) as the body itself. Instead, just read the statement
2579 // list and put it into a CompoundStmt for safe keeping.
2580 StmtResult FnBody(ParseCompoundStatementBody());
2581
2582 // If the function body could not be parsed, make a bogus compoundstmt.
2583 if (FnBody.isInvalid()) {
2584 Sema::CompoundScopeRAII CompoundScope(Actions);
2585 FnBody = Actions.ActOnCompoundStmt(L: LBraceLoc, R: LBraceLoc, Elts: {}, isStmtExpr: false);
2586 }
2587
2588 BodyScope.Exit();
2589 return Actions.ActOnFinishFunctionBody(Decl, Body: FnBody.get());
2590}
2591
2592Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2593 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2594 SourceLocation TryLoc = ConsumeToken();
2595
2596 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
2597 "parsing function try block");
2598
2599 // Constructor initializer list?
2600 if (Tok.is(K: tok::colon))
2601 ParseConstructorInitializer(ConstructorDecl: Decl);
2602 else
2603 Actions.ActOnDefaultCtorInitializers(CDtorDecl: Decl);
2604
2605 // Save and reset current vtordisp stack if we have entered a C++ method body.
2606 bool IsCXXMethod =
2607 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Val: Decl);
2608 Sema::PragmaStackSentinelRAII
2609 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2610
2611 SourceLocation LBraceLoc = Tok.getLocation();
2612 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2613 // If we failed to parse the try-catch, we just give the function an empty
2614 // compound statement as the body.
2615 if (FnBody.isInvalid()) {
2616 Sema::CompoundScopeRAII CompoundScope(Actions);
2617 FnBody = Actions.ActOnCompoundStmt(L: LBraceLoc, R: LBraceLoc, Elts: {}, isStmtExpr: false);
2618 }
2619
2620 BodyScope.Exit();
2621 return Actions.ActOnFinishFunctionBody(Decl, Body: FnBody.get());
2622}
2623
2624bool Parser::trySkippingFunctionBody() {
2625 assert(SkipFunctionBodies &&
2626 "Should only be called when SkipFunctionBodies is enabled");
2627 if (!PP.isCodeCompletionEnabled()) {
2628 SkipFunctionBody();
2629 return true;
2630 }
2631
2632 // We're in code-completion mode. Skip parsing for all function bodies unless
2633 // the body contains the code-completion point.
2634 TentativeParsingAction PA(*this);
2635 bool IsTryCatch = Tok.is(K: tok::kw_try);
2636 CachedTokens Toks;
2637 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2638 if (llvm::any_of(Range&: Toks, P: [](const Token &Tok) {
2639 return Tok.is(K: tok::code_completion);
2640 })) {
2641 PA.Revert();
2642 return false;
2643 }
2644 if (ErrorInPrologue) {
2645 PA.Commit();
2646 SkipMalformedDecl();
2647 return true;
2648 }
2649 if (!SkipUntil(T: tok::r_brace, Flags: StopAtCodeCompletion)) {
2650 PA.Revert();
2651 return false;
2652 }
2653 while (IsTryCatch && Tok.is(K: tok::kw_catch)) {
2654 if (!SkipUntil(T: tok::l_brace, Flags: StopAtCodeCompletion) ||
2655 !SkipUntil(T: tok::r_brace, Flags: StopAtCodeCompletion)) {
2656 PA.Revert();
2657 return false;
2658 }
2659 }
2660 PA.Commit();
2661 return true;
2662}
2663
2664StmtResult Parser::ParseCXXTryBlock() {
2665 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2666
2667 SourceLocation TryLoc = ConsumeToken();
2668 return ParseCXXTryBlockCommon(TryLoc);
2669}
2670
2671StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2672 if (Tok.isNot(K: tok::l_brace))
2673 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
2674
2675 StmtResult TryBlock(ParseCompoundStatement(
2676 /*isStmtExpr=*/false,
2677 ScopeFlags: Scope::DeclScope | Scope::TryScope | Scope::CompoundStmtScope |
2678 (FnTry ? Scope::FnTryCatchScope : Scope::NoScope)));
2679 if (TryBlock.isInvalid())
2680 return TryBlock;
2681
2682 // Borland allows SEH-handlers with 'try'
2683
2684 if (isTokenSEHExcept() || Tok.is(K: tok::kw___finally)) {
2685 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2686 StmtResult Handler;
2687 if (isTokenSEHExcept()) {
2688 SourceLocation Loc = ConsumeToken();
2689 Handler = ParseSEHExceptBlock(ExceptLoc: Loc);
2690 } else {
2691 SourceLocation Loc = ConsumeToken();
2692 Handler = ParseSEHFinallyBlock(FinallyLoc: Loc);
2693 }
2694 if(Handler.isInvalid())
2695 return Handler;
2696
2697 return Actions.ActOnSEHTryBlock(IsCXXTry: true /* IsCXXTry */,
2698 TryLoc,
2699 TryBlock: TryBlock.get(),
2700 Handler: Handler.get());
2701 } else {
2702 StmtVector Handlers;
2703
2704 // C++11 attributes can't appear here, despite this context seeming
2705 // statement-like.
2706 DiagnoseAndSkipCXX11Attributes();
2707
2708 if (Tok.isNot(K: tok::kw_catch))
2709 return StmtError(Diag(Tok, DiagID: diag::err_expected_catch));
2710 while (Tok.is(K: tok::kw_catch)) {
2711 StmtResult Handler(ParseCXXCatchBlock(FnCatch: FnTry));
2712 if (!Handler.isInvalid())
2713 Handlers.push_back(Elt: Handler.get());
2714 }
2715 // Don't bother creating the full statement if we don't have any usable
2716 // handlers.
2717 if (Handlers.empty())
2718 return StmtError();
2719
2720 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock: TryBlock.get(), Handlers);
2721 }
2722}
2723
2724StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2725 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2726
2727 SourceLocation CatchLoc = ConsumeToken();
2728
2729 BalancedDelimiterTracker T(*this, tok::l_paren);
2730 if (T.expectAndConsume())
2731 return StmtError();
2732
2733 // C++ 3.3.2p3:
2734 // The name in a catch exception-declaration is local to the handler and
2735 // shall not be redeclared in the outermost block of the handler.
2736 ParseScope CatchScope(
2737 this, Scope::DeclScope | Scope::ControlScope | Scope::CatchScope |
2738 (FnCatch ? Scope::FnTryCatchScope : Scope::NoScope));
2739
2740 // exception-declaration is equivalent to '...' or a parameter-declaration
2741 // without default arguments.
2742 Decl *ExceptionDecl = nullptr;
2743 if (Tok.isNot(K: tok::ellipsis)) {
2744 ParsedAttributes Attributes(AttrFactory);
2745 MaybeParseCXX11Attributes(Attrs&: Attributes);
2746
2747 DeclSpec DS(AttrFactory);
2748
2749 if (ParseCXXTypeSpecifierSeq(DS))
2750 return StmtError();
2751
2752 Declarator ExDecl(DS, Attributes, DeclaratorContext::CXXCatch);
2753 ParseDeclarator(D&: ExDecl);
2754 ExceptionDecl = Actions.ActOnExceptionDeclarator(S: getCurScope(), D&: ExDecl);
2755 } else
2756 ConsumeToken();
2757
2758 T.consumeClose();
2759 if (T.getCloseLocation().isInvalid())
2760 return StmtError();
2761
2762 if (Tok.isNot(K: tok::l_brace))
2763 return StmtError(Diag(Tok, DiagID: diag::err_expected) << tok::l_brace);
2764
2765 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2766 StmtResult Block(ParseCompoundStatement());
2767 if (Block.isInvalid())
2768 return Block;
2769
2770 return Actions.ActOnCXXCatchBlock(CatchLoc, ExDecl: ExceptionDecl, HandlerBlock: Block.get());
2771}
2772
2773StmtResult Parser::ParseExpansionStatement(SourceLocation *TrailingElseLoc,
2774 LabelDecl *PrecedingLabel,
2775 SourceLocation TemplateLoc) {
2776 assert(Tok.is(tok::kw_for));
2777
2778 CXXExpansionStmtDecl *ExpansionDecl =
2779 Actions.ActOnCXXExpansionStmtDecl(TemplateDepth: TemplateParameterDepth, TemplateKWLoc: TemplateLoc);
2780
2781 CXXExpansionStmtPattern *Expansion;
2782 {
2783 Sema::ContextRAII CtxGuard(Actions, ExpansionDecl, /*NewThis=*/false);
2784 TemplateParameterDepthRAII TParamDepthGuard(TemplateParameterDepth);
2785 ++TParamDepthGuard;
2786
2787 StmtResult SR =
2788 ParseForStatement(TrailingElseLoc, PrecedingLabel, ESD: ExpansionDecl);
2789 if (SR.isInvalid())
2790 return SR;
2791
2792 Expansion = cast<CXXExpansionStmtPattern>(Val: SR.get());
2793 ExpansionDecl->setExpansionPattern(Expansion);
2794 }
2795
2796 DeclSpec DS(AttrFactory);
2797 DeclGroupPtrTy DeclGroupPtr =
2798 Actions.FinalizeDeclaratorGroup(S: getCurScope(), DS, Group: {ExpansionDecl});
2799
2800 return Actions.ActOnDeclStmt(Decl: DeclGroupPtr, StartLoc: Expansion->getBeginLoc(),
2801 EndLoc: Expansion->getEndLoc());
2802}
2803
2804void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2805 IfExistsCondition Result;
2806 if (ParseMicrosoftIfExistsCondition(Result))
2807 return;
2808
2809 // Handle dependent statements by parsing the braces as a compound statement.
2810 // This is not the same behavior as Visual C++, which don't treat this as a
2811 // compound statement, but for Clang's type checking we can't have anything
2812 // inside these braces escaping to the surrounding code.
2813 if (Result.Behavior == IfExistsBehavior::Dependent) {
2814 if (!Tok.is(K: tok::l_brace)) {
2815 Diag(Tok, DiagID: diag::err_expected) << tok::l_brace;
2816 return;
2817 }
2818
2819 StmtResult Compound = ParseCompoundStatement();
2820 if (Compound.isInvalid())
2821 return;
2822
2823 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(KeywordLoc: Result.KeywordLoc,
2824 IsIfExists: Result.IsIfExists,
2825 SS&: Result.SS,
2826 Name&: Result.Name,
2827 Nested: Compound.get());
2828 if (DepResult.isUsable())
2829 Stmts.push_back(Elt: DepResult.get());
2830 return;
2831 }
2832
2833 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2834 if (Braces.consumeOpen()) {
2835 Diag(Tok, DiagID: diag::err_expected) << tok::l_brace;
2836 return;
2837 }
2838
2839 switch (Result.Behavior) {
2840 case IfExistsBehavior::Parse:
2841 // Parse the statements below.
2842 break;
2843
2844 case IfExistsBehavior::Dependent:
2845 llvm_unreachable("Dependent case handled above");
2846
2847 case IfExistsBehavior::Skip:
2848 Braces.skipToEnd();
2849 return;
2850 }
2851
2852 // Condition is true, parse the statements.
2853 while (Tok.isNot(K: tok::r_brace)) {
2854 StmtResult R =
2855 ParseStatementOrDeclaration(Stmts, StmtCtx: ParsedStmtContext::Compound);
2856 if (R.isUsable())
2857 Stmts.push_back(Elt: R.get());
2858 }
2859 Braces.consumeClose();
2860}
2861