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