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