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