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