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