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