clang 22.0.0git
ParseStmt.cpp
Go to the documentation of this file.
1//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Statement and Block portions of the Parser
10// interface.
11//
12//===----------------------------------------------------------------------===//
13
20#include "clang/Parse/Parser.h"
22#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Scope.h"
26#include "clang/Sema/SemaObjC.h"
30#include "llvm/ADT/STLExtras.h"
31#include "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 }
507
508 // If we reached this code, the statement must end in a semicolon.
509 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
510 // If the result was valid, then we do want to diagnose this. Use
511 // ExpectAndConsume to emit the diagnostic, even though we know it won't
512 // succeed.
513 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
514 // Skip until we see a } or ;, but don't eat it.
515 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
516 }
517
518 return Res;
519}
520
521StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
522 // If a case keyword is missing, this is where it should be inserted.
523 Token OldToken = Tok;
524
525 ExprStatementTokLoc = Tok.getLocation();
526
527 // expression[opt] ';'
529 if (Expr.isInvalid()) {
530 // If the expression is invalid, skip ahead to the next semicolon or '}'.
531 // Not doing this opens us up to the possibility of infinite loops if
532 // ParseExpression does not consume any tokens.
533 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
534 if (Tok.is(tok::semi))
535 ConsumeToken();
536 return Actions.ActOnExprStmtError();
537 }
538
539 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
540 Actions.CheckCaseExpression(Expr.get())) {
541 // If a constant expression is followed by a colon inside a switch block,
542 // suggest a missing case keyword.
543 Diag(OldToken, diag::err_expected_case_before_expression)
544 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
545
546 // Recover parsing as a case statement.
547 return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
548 }
549
550 Token *CurTok = nullptr;
551 // If the semicolon is missing at the end of REPL input, we want to print
552 // the result. Note we shouldn't eat the token since the callback needs it.
553 if (Tok.is(tok::annot_repl_input_end))
554 CurTok = &Tok;
555 else
556 // Otherwise, eat the semicolon.
557 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
558
559 StmtResult R = handleExprStmt(Expr, StmtCtx);
560 if (CurTok && !R.isInvalid())
561 CurTok->setAnnotationValue(R.get());
562
563 return R;
564}
565
566StmtResult Parser::ParseSEHTryBlock() {
567 assert(Tok.is(tok::kw___try) && "Expected '__try'");
568 SourceLocation TryLoc = ConsumeToken();
569
570 if (Tok.isNot(tok::l_brace))
571 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
572
573 StmtResult TryBlock(ParseCompoundStatement(
574 /*isStmtExpr=*/false,
576 if (TryBlock.isInvalid())
577 return TryBlock;
578
579 StmtResult Handler;
580 if (Tok.is(tok::identifier) &&
581 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
582 SourceLocation Loc = ConsumeToken();
583 Handler = ParseSEHExceptBlock(Loc);
584 } else if (Tok.is(tok::kw___finally)) {
585 SourceLocation Loc = ConsumeToken();
586 Handler = ParseSEHFinallyBlock(Loc);
587 } else {
588 return StmtError(Diag(Tok, diag::err_seh_expected_handler));
589 }
590
591 if(Handler.isInvalid())
592 return Handler;
593
594 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
595 TryLoc,
596 TryBlock.get(),
597 Handler.get());
598}
599
600StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
601 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
602 raii2(Ident___exception_code, false),
603 raii3(Ident_GetExceptionCode, false);
604
605 if (ExpectAndConsume(tok::l_paren))
606 return StmtError();
607
610
611 if (getLangOpts().Borland) {
612 Ident__exception_info->setIsPoisoned(false);
613 Ident___exception_info->setIsPoisoned(false);
614 Ident_GetExceptionInfo->setIsPoisoned(false);
615 }
616
617 ExprResult FilterExpr;
618 {
619 ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
621 FilterExpr = ParseExpression();
622 }
623
624 if (getLangOpts().Borland) {
625 Ident__exception_info->setIsPoisoned(true);
626 Ident___exception_info->setIsPoisoned(true);
627 Ident_GetExceptionInfo->setIsPoisoned(true);
628 }
629
630 if(FilterExpr.isInvalid())
631 return StmtError();
632
633 if (ExpectAndConsume(tok::r_paren))
634 return StmtError();
635
636 if (Tok.isNot(tok::l_brace))
637 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
638
639 StmtResult Block(ParseCompoundStatement());
640
641 if(Block.isInvalid())
642 return Block;
643
644 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
645}
646
647StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
648 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
649 raii2(Ident___abnormal_termination, false),
650 raii3(Ident_AbnormalTermination, false);
651
652 if (Tok.isNot(tok::l_brace))
653 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
654
655 ParseScope FinallyScope(this, 0);
656 Actions.ActOnStartSEHFinallyBlock();
657
658 StmtResult Block(ParseCompoundStatement());
659 if(Block.isInvalid()) {
660 Actions.ActOnAbortSEHFinallyBlock();
661 return Block;
662 }
663
664 return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
665}
666
667/// Handle __leave
668///
669/// seh-leave-statement:
670/// '__leave' ';'
671///
672StmtResult Parser::ParseSEHLeaveStatement() {
673 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
674 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
675}
676
677static void DiagnoseLabelFollowedByDecl(Parser &P, const Stmt *SubStmt) {
678 // When in C mode (but not Microsoft extensions mode), diagnose use of a
679 // label that is followed by a declaration rather than a statement.
680 if (!P.getLangOpts().CPlusPlus && !P.getLangOpts().MicrosoftExt &&
681 isa<DeclStmt>(SubStmt)) {
682 P.Diag(SubStmt->getBeginLoc(),
683 P.getLangOpts().C23
684 ? diag::warn_c23_compat_label_followed_by_declaration
685 : diag::ext_c_label_followed_by_declaration);
686 }
687}
688
689StmtResult Parser::ParseLabeledStatement(ParsedAttributes &Attrs,
690 ParsedStmtContext StmtCtx) {
691 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
692 "Not an identifier!");
693
694 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
695 // substatement in a selection statement, in place of the loop body in an
696 // iteration statement, or in place of the statement that follows a label.
697 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
698
699 Token IdentTok = Tok; // Save the whole token.
700 ConsumeToken(); // eat the identifier.
701
702 assert(Tok.is(tok::colon) && "Not a label!");
703
704 // identifier ':' statement
705 SourceLocation ColonLoc = ConsumeToken();
706
707 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
708 IdentTok.getLocation());
709
710 // Read label attributes, if present.
711 StmtResult SubStmt;
712 if (Tok.is(tok::kw___attribute)) {
713 ParsedAttributes TempAttrs(AttrFactory);
714 ParseGNUAttributes(TempAttrs);
715
716 // In C++, GNU attributes only apply to the label if they are followed by a
717 // semicolon, to disambiguate label attributes from attributes on a labeled
718 // declaration.
719 //
720 // This doesn't quite match what GCC does; if the attribute list is empty
721 // and followed by a semicolon, GCC will reject (it appears to parse the
722 // attributes as part of a statement in that case). That looks like a bug.
723 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
724 Attrs.takeAllAppendingFrom(TempAttrs);
725 else {
726 StmtVector Stmts;
727 ParsedAttributes EmptyCXX11Attrs(AttrFactory);
728 SubStmt = ParseStatementOrDeclarationAfterAttributes(
729 Stmts, StmtCtx, /*TrailingElseLoc=*/nullptr, EmptyCXX11Attrs,
730 TempAttrs, LD);
731 if (!TempAttrs.empty() && !SubStmt.isInvalid())
732 SubStmt = Actions.ActOnAttributedStmt(TempAttrs, SubStmt.get());
733 }
734 }
735
736 // The label may have no statement following it
737 if (SubStmt.isUnset() && Tok.is(tok::r_brace)) {
738 DiagnoseLabelAtEndOfCompoundStatement();
739 SubStmt = Actions.ActOnNullStmt(ColonLoc);
740 }
741
742 // If we've not parsed a statement yet, parse one now.
743 if (SubStmt.isUnset())
744 SubStmt = ParseStatement(nullptr, StmtCtx, LD);
745
746 // Broken substmt shouldn't prevent the label from being added to the AST.
747 if (SubStmt.isInvalid())
748 SubStmt = Actions.ActOnNullStmt(ColonLoc);
749
750 DiagnoseLabelFollowedByDecl(*this, SubStmt.get());
751
752 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
753 Attrs.clear();
754
755 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
756 SubStmt.get());
757}
758
759StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
760 bool MissingCase, ExprResult Expr) {
761 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
762
763 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
764 // substatement in a selection statement, in place of the loop body in an
765 // iteration statement, or in place of the statement that follows a label.
766 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
767
768 // It is very common for code to contain many case statements recursively
769 // nested, as in (but usually without indentation):
770 // case 1:
771 // case 2:
772 // case 3:
773 // case 4:
774 // case 5: etc.
775 //
776 // Parsing this naively works, but is both inefficient and can cause us to run
777 // out of stack space in our recursive descent parser. As a special case,
778 // flatten this recursion into an iterative loop. This is complex and gross,
779 // but all the grossness is constrained to ParseCaseStatement (and some
780 // weirdness in the actions), so this is just local grossness :).
781
782 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
783 // example above.
784 StmtResult TopLevelCase(true);
785
786 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
787 // gets updated each time a new case is parsed, and whose body is unset so
788 // far. When parsing 'case 4', this is the 'case 3' node.
789 Stmt *DeepestParsedCaseStmt = nullptr;
790
791 // While we have case statements, eat and stack them.
792 SourceLocation ColonLoc;
793 do {
794 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
795 ConsumeToken(); // eat the 'case'.
796 ColonLoc = SourceLocation();
797
798 if (Tok.is(tok::code_completion)) {
799 cutOffParsing();
800 Actions.CodeCompletion().CodeCompleteCase(getCurScope());
801 return StmtError();
802 }
803
804 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
805 /// Disable this form of error recovery while we're parsing the case
806 /// expression.
807 ColonProtectionRAIIObject ColonProtection(*this);
808
809 ExprResult LHS;
810 if (!MissingCase) {
811 LHS = ParseCaseExpression(CaseLoc);
812 if (LHS.isInvalid()) {
813 // If constant-expression is parsed unsuccessfully, recover by skipping
814 // current case statement (moving to the colon that ends it).
815 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
816 return StmtError();
817 }
818 } else {
819 LHS = Actions.ActOnCaseExpr(CaseLoc, Expr);
820 MissingCase = false;
821 }
822
823 // GNU case range extension.
824 SourceLocation DotDotDotLoc;
825 ExprResult RHS;
826 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
827 // In C++, this is a GNU extension. In C, it's a C2y extension.
828 unsigned DiagId;
830 DiagId = diag::ext_gnu_case_range;
831 else if (getLangOpts().C2y)
832 DiagId = diag::warn_c23_compat_case_range;
833 else
834 DiagId = diag::ext_c2y_case_range;
835 Diag(DotDotDotLoc, DiagId);
836 RHS = ParseCaseExpression(CaseLoc);
837 if (RHS.isInvalid()) {
838 if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
839 return StmtError();
840 }
841 }
842
843 ColonProtection.restore();
844
845 if (TryConsumeToken(tok::colon, ColonLoc)) {
846 } else if (TryConsumeToken(tok::semi, ColonLoc) ||
847 TryConsumeToken(tok::coloncolon, ColonLoc)) {
848 // Treat "case blah;" or "case blah::" as a typo for "case blah:".
849 Diag(ColonLoc, diag::err_expected_after)
850 << "'case'" << tok::colon
851 << FixItHint::CreateReplacement(ColonLoc, ":");
852 } else {
853 SourceLocation ExpectedLoc = getEndOfPreviousToken();
854
855 Diag(ExpectedLoc, diag::err_expected_after)
856 << "'case'" << tok::colon
857 << FixItHint::CreateInsertion(ExpectedLoc, ":");
858
859 ColonLoc = ExpectedLoc;
860 }
861
862 StmtResult Case =
863 Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
864
865 // If we had a sema error parsing this case, then just ignore it and
866 // continue parsing the sub-stmt.
867 if (Case.isInvalid()) {
868 if (TopLevelCase.isInvalid()) // No parsed case stmts.
869 return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
870 // Otherwise, just don't add it as a nested case.
871 } else {
872 // If this is the first case statement we parsed, it becomes TopLevelCase.
873 // Otherwise we link it into the current chain.
874 Stmt *NextDeepest = Case.get();
875 if (TopLevelCase.isInvalid())
876 TopLevelCase = Case;
877 else
878 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
879 DeepestParsedCaseStmt = NextDeepest;
880 }
881
882 // Handle all case statements.
883 } while (Tok.is(tok::kw_case));
884
885 // If we found a non-case statement, start by parsing it.
886 StmtResult SubStmt;
887
888 if (Tok.is(tok::r_brace)) {
889 // "switch (X) { case 4: }", is valid and is treated as if label was
890 // followed by a null statement.
891 DiagnoseLabelAtEndOfCompoundStatement();
892 SubStmt = Actions.ActOnNullStmt(ColonLoc);
893 } else {
894 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
895 }
896
897 // Install the body into the most deeply-nested case.
898 if (DeepestParsedCaseStmt) {
899 // Broken sub-stmt shouldn't prevent forming the case statement properly.
900 if (SubStmt.isInvalid())
901 SubStmt = Actions.ActOnNullStmt(SourceLocation());
902 DiagnoseLabelFollowedByDecl(*this, SubStmt.get());
903 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
904 }
905
906 // Return the top level parsed statement tree.
907 return TopLevelCase;
908}
909
910StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
911 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
912
913 // [OpenMP 5.1] 2.1.3: A stand-alone directive may not be used in place of a
914 // substatement in a selection statement, in place of the loop body in an
915 // iteration statement, or in place of the statement that follows a label.
916 StmtCtx &= ~ParsedStmtContext::AllowStandaloneOpenMPDirectives;
917
918 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
919
920 SourceLocation ColonLoc;
921 if (TryConsumeToken(tok::colon, ColonLoc)) {
922 } else if (TryConsumeToken(tok::semi, ColonLoc)) {
923 // Treat "default;" as a typo for "default:".
924 Diag(ColonLoc, diag::err_expected_after)
925 << "'default'" << tok::colon
926 << FixItHint::CreateReplacement(ColonLoc, ":");
927 } else {
928 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
929 Diag(ExpectedLoc, diag::err_expected_after)
930 << "'default'" << tok::colon
931 << FixItHint::CreateInsertion(ExpectedLoc, ":");
932 ColonLoc = ExpectedLoc;
933 }
934
935 StmtResult SubStmt;
936
937 if (Tok.is(tok::r_brace)) {
938 // "switch (X) {... default: }", is valid and is treated as if label was
939 // followed by a null statement.
940 DiagnoseLabelAtEndOfCompoundStatement();
941 SubStmt = Actions.ActOnNullStmt(ColonLoc);
942 } else {
943 SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
944 }
945
946 // Broken sub-stmt shouldn't prevent forming the case statement properly.
947 if (SubStmt.isInvalid())
948 SubStmt = Actions.ActOnNullStmt(ColonLoc);
949
950 DiagnoseLabelFollowedByDecl(*this, SubStmt.get());
951 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
952 SubStmt.get(), getCurScope());
953}
954
955StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
956 return ParseCompoundStatement(isStmtExpr,
958}
959
960StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
961 unsigned ScopeFlags) {
962 assert(Tok.is(tok::l_brace) && "Not a compound stmt!");
963
964 // Enter a scope to hold everything within the compound stmt. Compound
965 // statements can always hold declarations.
966 ParseScope CompoundScope(this, ScopeFlags);
967
968 // Parse the statements in the body.
969 StmtResult R;
970 StackHandler.runWithSufficientStackSpace(Tok.getLocation(), [&, this]() {
971 R = ParseCompoundStatementBody(isStmtExpr);
972 });
973 return R;
974}
975
976void Parser::ParseCompoundStatementLeadingPragmas() {
977 bool checkForPragmas = true;
978 while (checkForPragmas) {
979 switch (Tok.getKind()) {
980 case tok::annot_pragma_vis:
981 HandlePragmaVisibility();
982 break;
983 case tok::annot_pragma_pack:
984 HandlePragmaPack();
985 break;
986 case tok::annot_pragma_msstruct:
987 HandlePragmaMSStruct();
988 break;
989 case tok::annot_pragma_align:
990 HandlePragmaAlign();
991 break;
992 case tok::annot_pragma_weak:
993 HandlePragmaWeak();
994 break;
995 case tok::annot_pragma_weakalias:
996 HandlePragmaWeakAlias();
997 break;
998 case tok::annot_pragma_redefine_extname:
999 HandlePragmaRedefineExtname();
1000 break;
1001 case tok::annot_pragma_opencl_extension:
1002 HandlePragmaOpenCLExtension();
1003 break;
1004 case tok::annot_pragma_fp_contract:
1005 HandlePragmaFPContract();
1006 break;
1007 case tok::annot_pragma_fp:
1008 HandlePragmaFP();
1009 break;
1010 case tok::annot_pragma_fenv_access:
1011 case tok::annot_pragma_fenv_access_ms:
1012 HandlePragmaFEnvAccess();
1013 break;
1014 case tok::annot_pragma_fenv_round:
1015 HandlePragmaFEnvRound();
1016 break;
1017 case tok::annot_pragma_cx_limited_range:
1018 HandlePragmaCXLimitedRange();
1019 break;
1020 case tok::annot_pragma_float_control:
1021 HandlePragmaFloatControl();
1022 break;
1023 case tok::annot_pragma_ms_pointers_to_members:
1024 HandlePragmaMSPointersToMembers();
1025 break;
1026 case tok::annot_pragma_ms_pragma:
1027 HandlePragmaMSPragma();
1028 break;
1029 case tok::annot_pragma_ms_vtordisp:
1030 HandlePragmaMSVtorDisp();
1031 break;
1032 case tok::annot_pragma_dump:
1033 HandlePragmaDump();
1034 break;
1035 default:
1036 checkForPragmas = false;
1037 break;
1038 }
1039 }
1040
1041}
1042
1043void Parser::DiagnoseLabelAtEndOfCompoundStatement() {
1044 if (getLangOpts().CPlusPlus) {
1046 ? diag::warn_cxx20_compat_label_end_of_compound_statement
1047 : diag::ext_cxx_label_end_of_compound_statement);
1048 } else {
1049 Diag(Tok, getLangOpts().C23
1050 ? diag::warn_c23_compat_label_end_of_compound_statement
1051 : diag::ext_c_label_end_of_compound_statement);
1052 }
1053}
1054
1055bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
1056 if (!Tok.is(tok::semi))
1057 return false;
1058
1059 SourceLocation StartLoc = Tok.getLocation();
1060 SourceLocation EndLoc;
1061
1062 while (Tok.is(tok::semi) && !Tok.hasLeadingEmptyMacro() &&
1063 Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
1064 EndLoc = Tok.getLocation();
1065
1066 // Don't just ConsumeToken() this tok::semi, do store it in AST.
1067 StmtResult R =
1068 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
1069 if (R.isUsable())
1070 Stmts.push_back(R.get());
1071 }
1072
1073 // Did not consume any extra semi.
1074 if (EndLoc.isInvalid())
1075 return false;
1076
1077 Diag(StartLoc, diag::warn_null_statement)
1078 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
1079 return true;
1080}
1081
1082StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
1083 bool IsStmtExprResult = false;
1084 if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
1085 // Look ahead to see if the next two tokens close the statement expression;
1086 // if so, this expression statement is the last statement in a
1087 // statment expression.
1088 IsStmtExprResult = Tok.is(tok::r_brace) && NextToken().is(tok::r_paren);
1089 }
1090
1091 if (IsStmtExprResult)
1092 E = Actions.ActOnStmtExprResult(E);
1093 return Actions.ActOnExprStmt(E, /*DiscardedValue=*/!IsStmtExprResult);
1094}
1095
1096StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
1097 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
1098 Tok.getLocation(),
1099 "in compound statement ('{}')");
1100
1101 // Record the current FPFeatures, restore on leaving the
1102 // compound statement.
1103 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1104
1105 InMessageExpressionRAIIObject InMessage(*this, false);
1106 BalancedDelimiterTracker T(*this, tok::l_brace);
1107 if (T.consumeOpen())
1108 return StmtError();
1109
1110 Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
1111
1112 // Parse any pragmas at the beginning of the compound statement.
1113 ParseCompoundStatementLeadingPragmas();
1114 Actions.ActOnAfterCompoundStatementLeadingPragmas();
1115
1116 StmtVector Stmts;
1117
1118 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
1119 // only allowed at the start of a compound stmt regardless of the language.
1120 while (Tok.is(tok::kw___label__)) {
1121 SourceLocation LabelLoc = ConsumeToken();
1122
1123 SmallVector<Decl *, 4> DeclsInGroup;
1124 while (true) {
1125 if (Tok.isNot(tok::identifier)) {
1126 Diag(Tok, diag::err_expected) << tok::identifier;
1127 break;
1128 }
1129
1130 IdentifierInfo *II = Tok.getIdentifierInfo();
1131 SourceLocation IdLoc = ConsumeToken();
1132 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
1133
1134 if (!TryConsumeToken(tok::comma))
1135 break;
1136 }
1137
1138 DeclSpec DS(AttrFactory);
1139 DeclGroupPtrTy Res =
1140 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1141 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
1142
1143 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
1144 if (R.isUsable())
1145 Stmts.push_back(R.get());
1146 }
1147
1148 ParsedStmtContext SubStmtCtx =
1149 ParsedStmtContext::Compound |
1150 (isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());
1151
1152 bool LastIsError = false;
1153 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
1154 Tok.isNot(tok::eof)) {
1155 if (Tok.is(tok::annot_pragma_unused)) {
1156 HandlePragmaUnused();
1157 continue;
1158 }
1159
1160 if (ConsumeNullStmt(Stmts))
1161 continue;
1162
1163 StmtResult R;
1164 if (Tok.isNot(tok::kw___extension__)) {
1165 R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
1166 } else {
1167 // __extension__ can start declarations and it can also be a unary
1168 // operator for expressions. Consume multiple __extension__ markers here
1169 // until we can determine which is which.
1170 // FIXME: This loses extension expressions in the AST!
1171 SourceLocation ExtLoc = ConsumeToken();
1172 while (Tok.is(tok::kw___extension__))
1173 ConsumeToken();
1174
1175 ParsedAttributes attrs(AttrFactory);
1176 MaybeParseCXX11Attributes(attrs, /*MightBeObjCMessageSend*/ true);
1177
1178 // If this is the start of a declaration, parse it as such.
1179 if (isDeclarationStatement()) {
1180 // __extension__ silences extension warnings in the subdeclaration.
1181 // FIXME: Save the __extension__ on the decl as a node somehow?
1182 ExtensionRAIIObject O(Diags);
1183
1184 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1185 ParsedAttributes DeclSpecAttrs(AttrFactory);
1186 DeclGroupPtrTy Res = ParseDeclaration(DeclaratorContext::Block, DeclEnd,
1187 attrs, DeclSpecAttrs);
1188 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1189 } else {
1190 // Otherwise this was a unary __extension__ marker.
1191 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1192
1193 if (Res.isInvalid()) {
1194 SkipUntil(tok::semi);
1195 continue;
1196 }
1197
1198 // Eat the semicolon at the end of stmt and convert the expr into a
1199 // statement.
1200 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1201 R = handleExprStmt(Res, SubStmtCtx);
1202 if (R.isUsable())
1203 R = Actions.ActOnAttributedStmt(attrs, R.get());
1204 }
1205 }
1206
1207 if (R.isUsable())
1208 Stmts.push_back(R.get());
1209 LastIsError = R.isInvalid();
1210 }
1211 // StmtExpr needs to do copy initialization for last statement.
1212 // If last statement is invalid, the last statement in `Stmts` will be
1213 // incorrect. Then the whole compound statement should also be marked as
1214 // invalid to prevent subsequent errors.
1215 if (isStmtExpr && LastIsError && !Stmts.empty())
1216 return StmtError();
1217
1218 // Warn the user that using option `-ffp-eval-method=source` on a
1219 // 32-bit target and feature `sse` disabled, or using
1220 // `pragma clang fp eval_method=source` and feature `sse` disabled, is not
1221 // supported.
1222 if (!PP.getTargetInfo().supportSourceEvalMethod() &&
1223 (PP.getLastFPEvalPragmaLocation().isValid() ||
1224 PP.getCurrentFPEvalMethod() ==
1226 Diag(Tok.getLocation(),
1227 diag::warn_no_support_for_eval_method_source_on_m32);
1228
1229 SourceLocation CloseLoc = Tok.getLocation();
1230
1231 // We broke out of the while loop because we found a '}' or EOF.
1232 if (!T.consumeClose()) {
1233 // If this is the '})' of a statement expression, check that it's written
1234 // in a sensible way.
1235 if (isStmtExpr && Tok.is(tok::r_paren))
1236 checkCompoundToken(CloseLoc, tok::r_brace, CompoundToken::StmtExprEnd);
1237 } else {
1238 // Recover by creating a compound statement with what we parsed so far,
1239 // instead of dropping everything and returning StmtError().
1240 }
1241
1242 if (T.getCloseLocation().isValid())
1243 CloseLoc = T.getCloseLocation();
1244
1245 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1246 Stmts, isStmtExpr);
1247}
1248
1249bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1251 SourceLocation Loc,
1253 SourceLocation &LParenLoc,
1254 SourceLocation &RParenLoc) {
1255 BalancedDelimiterTracker T(*this, tok::l_paren);
1256 T.consumeOpen();
1257 SourceLocation Start = Tok.getLocation();
1258
1259 if (getLangOpts().CPlusPlus) {
1260 Cond = ParseCXXCondition(InitStmt, Loc, CK, false);
1261 } else {
1262 ExprResult CondExpr = ParseExpression();
1263
1264 // If required, convert to a boolean value.
1265 if (CondExpr.isInvalid())
1267 else
1268 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK,
1269 /*MissingOK=*/false);
1270 }
1271
1272 // If the parser was confused by the condition and we don't have a ')', try to
1273 // recover by skipping ahead to a semi and bailing out. If condexp is
1274 // semantically invalid but we have well formed code, keep going.
1275 if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1276 SkipUntil(tok::semi);
1277 // Skipping may have stopped if it found the containing ')'. If so, we can
1278 // continue parsing the if statement.
1279 if (Tok.isNot(tok::r_paren))
1280 return true;
1281 }
1282
1283 if (Cond.isInvalid()) {
1284 ExprResult CondExpr = Actions.CreateRecoveryExpr(
1285 Start, Tok.getLocation() == Start ? Start : PrevTokLocation, {},
1286 Actions.PreferredConditionType(CK));
1287 if (!CondExpr.isInvalid())
1288 Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK,
1289 /*MissingOK=*/false);
1290 }
1291
1292 // Either the condition is valid or the rparen is present.
1293 T.consumeClose();
1294 LParenLoc = T.getOpenLocation();
1295 RParenLoc = T.getCloseLocation();
1296
1297 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1298 // that all callers are looking for a statement after the condition, so ")"
1299 // isn't valid.
1300 while (Tok.is(tok::r_paren)) {
1301 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1302 << FixItHint::CreateRemoval(Tok.getLocation());
1303 ConsumeParen();
1304 }
1305
1306 return false;
1307}
1308
1309namespace {
1310
1311enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };
1312
1313struct MisleadingIndentationChecker {
1314 Parser &P;
1315 SourceLocation StmtLoc;
1316 SourceLocation PrevLoc;
1317 unsigned NumDirectives;
1318 MisleadingStatementKind Kind;
1319 bool ShouldSkip;
1320 MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,
1321 SourceLocation SL)
1322 : P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()),
1323 NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K),
1324 ShouldSkip(P.getCurToken().is(tok::l_brace)) {
1326 StmtLoc = P.MisleadingIndentationElseLoc;
1327 P.MisleadingIndentationElseLoc = SourceLocation();
1328 }
1329 if (Kind == MSK_else && !ShouldSkip)
1331 }
1332
1333 /// Compute the column number will aligning tabs on TabStop (-ftabstop), this
1334 /// gives the visual indentation of the SourceLocation.
1335 static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) {
1336 unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop;
1337
1338 unsigned ColNo = SM.getSpellingColumnNumber(Loc);
1339 if (ColNo == 0 || TabStop == 1)
1340 return ColNo;
1341
1342 FileIDAndOffset FIDAndOffset = SM.getDecomposedLoc(Loc);
1343
1344 bool Invalid;
1345 StringRef BufData = SM.getBufferData(FIDAndOffset.first, &Invalid);
1346 if (Invalid)
1347 return 0;
1348
1349 const char *EndPos = BufData.data() + FIDAndOffset.second;
1350 // FileOffset are 0-based and Column numbers are 1-based
1351 assert(FIDAndOffset.second + 1 >= ColNo &&
1352 "Column number smaller than file offset?");
1353
1354 unsigned VisualColumn = 0; // Stored as 0-based column, here.
1355 // Loop from beginning of line up to Loc's file position, counting columns,
1356 // expanding tabs.
1357 for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;
1358 ++CurPos) {
1359 if (*CurPos == '\t')
1360 // Advance visual column to next tabstop.
1361 VisualColumn += (TabStop - VisualColumn % TabStop);
1362 else
1363 VisualColumn++;
1364 }
1365 return VisualColumn + 1;
1366 }
1367
1368 void Check() {
1369 Token Tok = P.getCurToken();
1371 diag::warn_misleading_indentation, Tok.getLocation()) ||
1372 ShouldSkip || NumDirectives != P.getPreprocessor().getNumDirectives() ||
1373 Tok.isOneOf(tok::semi, tok::r_brace) || Tok.isAnnotation() ||
1374 Tok.getLocation().isMacroID() || PrevLoc.isMacroID() ||
1375 StmtLoc.isMacroID() ||
1376 (Kind == MSK_else && P.MisleadingIndentationElseLoc.isInvalid())) {
1377 P.MisleadingIndentationElseLoc = SourceLocation();
1378 return;
1379 }
1380 if (Kind == MSK_else)
1381 P.MisleadingIndentationElseLoc = SourceLocation();
1382
1383 SourceManager &SM = P.getPreprocessor().getSourceManager();
1384 unsigned PrevColNum = getVisualIndentation(SM, PrevLoc);
1385 unsigned CurColNum = getVisualIndentation(SM, Tok.getLocation());
1386 unsigned StmtColNum = getVisualIndentation(SM, StmtLoc);
1387
1388 if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 &&
1389 ((PrevColNum > StmtColNum && PrevColNum == CurColNum) ||
1390 !Tok.isAtStartOfLine()) &&
1391 SM.getPresumedLineNumber(StmtLoc) !=
1392 SM.getPresumedLineNumber(Tok.getLocation()) &&
1393 (Tok.isNot(tok::identifier) ||
1394 P.getPreprocessor().LookAhead(0).isNot(tok::colon))) {
1395 P.Diag(Tok.getLocation(), diag::warn_misleading_indentation) << Kind;
1396 P.Diag(StmtLoc, diag::note_previous_statement);
1397 }
1398 }
1399};
1400
1401}
1402
1403StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1404 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1405 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1406
1407 bool IsConstexpr = false;
1408 bool IsConsteval = false;
1409 SourceLocation NotLocation;
1410 SourceLocation ConstevalLoc;
1411
1412 if (Tok.is(tok::kw_constexpr)) {
1413 // C23 supports constexpr keyword, but only for object definitions.
1414 if (getLangOpts().CPlusPlus) {
1415 Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
1416 : diag::ext_constexpr_if);
1417 IsConstexpr = true;
1418 ConsumeToken();
1419 }
1420 } else {
1421 if (Tok.is(tok::exclaim)) {
1422 NotLocation = ConsumeToken();
1423 }
1424
1425 if (Tok.is(tok::kw_consteval)) {
1426 Diag(Tok, getLangOpts().CPlusPlus23 ? diag::warn_cxx20_compat_consteval_if
1427 : diag::ext_consteval_if);
1428 IsConsteval = true;
1429 ConstevalLoc = ConsumeToken();
1430 } else if (Tok.is(tok::code_completion)) {
1431 cutOffParsing();
1432 Actions.CodeCompletion().CodeCompleteKeywordAfterIf(
1433 NotLocation.isValid());
1434 return StmtError();
1435 }
1436 }
1437 if (!IsConsteval && (NotLocation.isValid() || Tok.isNot(tok::l_paren))) {
1438 Diag(Tok, diag::err_expected_lparen_after) << "if";
1439 SkipUntil(tok::semi);
1440 return StmtError();
1441 }
1442
1443 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1444
1445 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1446 // the case for C90.
1447 //
1448 // C++ 6.4p3:
1449 // A name introduced by a declaration in a condition is in scope from its
1450 // point of declaration until the end of the substatements controlled by the
1451 // condition.
1452 // C++ 3.3.2p4:
1453 // Names declared in the for-init-statement, and in the condition of if,
1454 // while, for, and switch statements are local to the if, while, for, or
1455 // switch statement (including the controlled statement).
1456 //
1457 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1458
1459 // Parse the condition.
1460 StmtResult InitStmt;
1461 Sema::ConditionResult Cond;
1462 SourceLocation LParen;
1463 SourceLocation RParen;
1464 std::optional<bool> ConstexprCondition;
1465 if (!IsConsteval) {
1466
1467 if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1470 LParen, RParen))
1471 return StmtError();
1472
1473 if (IsConstexpr)
1474 ConstexprCondition = Cond.getKnownValue();
1475 }
1476
1477 bool IsBracedThen = Tok.is(tok::l_brace);
1478
1479 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1480 // there is no compound stmt. C90 does not have this clause. We only do this
1481 // if the body isn't a compound statement to avoid push/pop in common cases.
1482 //
1483 // C++ 6.4p1:
1484 // The substatement in a selection-statement (each substatement, in the else
1485 // form of the if statement) implicitly defines a local scope.
1486 //
1487 // For C++ we create a scope for the condition and a new scope for
1488 // substatements because:
1489 // -When the 'then' scope exits, we want the condition declaration to still be
1490 // active for the 'else' scope too.
1491 // -Sema will detect name clashes by considering declarations of a
1492 // 'ControlScope' as part of its direct subscope.
1493 // -If we wanted the condition and substatement to be in the same scope, we
1494 // would have to notify ParseStatement not to create a new scope. It's
1495 // simpler to let it create a new scope.
1496 //
1497 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);
1498
1499 MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);
1500
1501 // Read the 'then' stmt.
1502 SourceLocation ThenStmtLoc = Tok.getLocation();
1503
1504 SourceLocation InnerStatementTrailingElseLoc;
1505 StmtResult ThenStmt;
1506 {
1507 bool ShouldEnter = ConstexprCondition && !*ConstexprCondition;
1510 if (NotLocation.isInvalid() && IsConsteval) {
1512 ShouldEnter = true;
1513 }
1514
1515 EnterExpressionEvaluationContext PotentiallyDiscarded(
1516 Actions, Context, nullptr,
1518 ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1519 }
1520
1521 if (Tok.isNot(tok::kw_else))
1522 MIChecker.Check();
1523
1524 // Pop the 'if' scope if needed.
1525 InnerScope.Exit();
1526
1527 // If it has an else, parse it.
1528 SourceLocation ElseLoc;
1529 SourceLocation ElseStmtLoc;
1530 StmtResult ElseStmt;
1531
1532 if (Tok.is(tok::kw_else)) {
1533 if (TrailingElseLoc)
1534 *TrailingElseLoc = Tok.getLocation();
1535
1536 ElseLoc = ConsumeToken();
1537 ElseStmtLoc = Tok.getLocation();
1538
1539 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1540 // there is no compound stmt. C90 does not have this clause. We only do
1541 // this if the body isn't a compound statement to avoid push/pop in common
1542 // cases.
1543 //
1544 // C++ 6.4p1:
1545 // The substatement in a selection-statement (each substatement, in the else
1546 // form of the if statement) implicitly defines a local scope.
1547 //
1548 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1549 Tok.is(tok::l_brace));
1550
1551 MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);
1552 bool ShouldEnter = ConstexprCondition && *ConstexprCondition;
1555 if (NotLocation.isValid() && IsConsteval) {
1557 ShouldEnter = true;
1558 }
1559
1560 EnterExpressionEvaluationContext PotentiallyDiscarded(
1561 Actions, Context, nullptr,
1563 ElseStmt = ParseStatement();
1564
1565 if (ElseStmt.isUsable())
1566 MIChecker.Check();
1567
1568 // Pop the 'else' scope if needed.
1569 InnerScope.Exit();
1570 } else if (Tok.is(tok::code_completion)) {
1571 cutOffParsing();
1572 Actions.CodeCompletion().CodeCompleteAfterIf(getCurScope(), IsBracedThen);
1573 return StmtError();
1574 } else if (InnerStatementTrailingElseLoc.isValid()) {
1575 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1576 }
1577
1578 IfScope.Exit();
1579
1580 // If the then or else stmt is invalid and the other is valid (and present),
1581 // turn the invalid one into a null stmt to avoid dropping the other
1582 // part. If both are invalid, return error.
1583 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1584 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1585 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1586 // Both invalid, or one is invalid and other is non-present: return error.
1587 return StmtError();
1588 }
1589
1590 if (IsConsteval) {
1591 auto IsCompoundStatement = [](const Stmt *S) {
1592 if (const auto *Outer = dyn_cast_if_present<AttributedStmt>(S))
1593 S = Outer->getSubStmt();
1594 return isa_and_nonnull<clang::CompoundStmt>(S);
1595 };
1596
1597 if (!IsCompoundStatement(ThenStmt.get())) {
1598 Diag(ConstevalLoc, diag::err_expected_after) << "consteval"
1599 << "{";
1600 return StmtError();
1601 }
1602 if (!ElseStmt.isUnset() && !IsCompoundStatement(ElseStmt.get())) {
1603 Diag(ElseLoc, diag::err_expected_after) << "else"
1604 << "{";
1605 return StmtError();
1606 }
1607 }
1608
1609 // Now if either are invalid, replace with a ';'.
1610 if (ThenStmt.isInvalid())
1611 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1612 if (ElseStmt.isInvalid())
1613 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1614
1616 if (IsConstexpr)
1618 else if (IsConsteval)
1621
1622 return Actions.ActOnIfStmt(IfLoc, Kind, LParen, InitStmt.get(), Cond, RParen,
1623 ThenStmt.get(), ElseLoc, ElseStmt.get());
1624}
1625
1626StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc,
1627 LabelDecl *PrecedingLabel) {
1628 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1629 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1630
1631 if (Tok.isNot(tok::l_paren)) {
1632 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1633 SkipUntil(tok::semi);
1634 return StmtError();
1635 }
1636
1637 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1638
1639 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1640 // not the case for C90. Start the switch scope.
1641 //
1642 // C++ 6.4p3:
1643 // A name introduced by a declaration in a condition is in scope from its
1644 // point of declaration until the end of the substatements controlled by the
1645 // condition.
1646 // C++ 3.3.2p4:
1647 // Names declared in the for-init-statement, and in the condition of if,
1648 // while, for, and switch statements are local to the if, while, for, or
1649 // switch statement (including the controlled statement).
1650 //
1651 unsigned ScopeFlags = Scope::SwitchScope;
1652 if (C99orCXX)
1653 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1654 ParseScope SwitchScope(this, ScopeFlags);
1655
1656 // Parse the condition.
1657 StmtResult InitStmt;
1658 Sema::ConditionResult Cond;
1659 SourceLocation LParen;
1660 SourceLocation RParen;
1661 if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1662 Sema::ConditionKind::Switch, LParen, RParen))
1663 return StmtError();
1664
1665 StmtResult Switch = Actions.ActOnStartOfSwitchStmt(
1666 SwitchLoc, LParen, InitStmt.get(), Cond, RParen);
1667
1668 if (Switch.isInvalid()) {
1669 // Skip the switch body.
1670 // FIXME: This is not optimal recovery, but parsing the body is more
1671 // dangerous due to the presence of case and default statements, which
1672 // will have no place to connect back with the switch.
1673 if (Tok.is(tok::l_brace)) {
1674 ConsumeBrace();
1675 SkipUntil(tok::r_brace);
1676 } else
1677 SkipUntil(tok::semi);
1678 return Switch;
1679 }
1680
1681 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1682 // there is no compound stmt. C90 does not have this clause. We only do this
1683 // if the body isn't a compound statement to avoid push/pop in common cases.
1684 //
1685 // C++ 6.4p1:
1686 // The substatement in a selection-statement (each substatement, in the else
1687 // form of the if statement) implicitly defines a local scope.
1688 //
1689 // See comments in ParseIfStatement for why we create a scope for the
1690 // condition and a new scope for substatement in C++.
1691 //
1693 getCurScope()->setPrecedingLabel(PrecedingLabel);
1694 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1695
1696 // We have incremented the mangling number for the SwitchScope and the
1697 // InnerScope, which is one too many.
1698 if (C99orCXX)
1700
1701 // Read the body statement.
1702 StmtResult Body(ParseStatement(TrailingElseLoc));
1703
1704 // Pop the scopes.
1705 InnerScope.Exit();
1706 SwitchScope.Exit();
1707
1708 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1709}
1710
1711StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc,
1712 LabelDecl *PrecedingLabel) {
1713 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1714 SourceLocation WhileLoc = Tok.getLocation();
1715 ConsumeToken(); // eat the 'while'.
1716
1717 if (Tok.isNot(tok::l_paren)) {
1718 Diag(Tok, diag::err_expected_lparen_after) << "while";
1719 SkipUntil(tok::semi);
1720 return StmtError();
1721 }
1722
1723 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1724
1725 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1726 // the case for C90. Start the loop scope.
1727 //
1728 // C++ 6.4p3:
1729 // A name introduced by a declaration in a condition is in scope from its
1730 // point of declaration until the end of the substatements controlled by the
1731 // condition.
1732 // C++ 3.3.2p4:
1733 // Names declared in the for-init-statement, and in the condition of if,
1734 // while, for, and switch statements are local to the if, while, for, or
1735 // switch statement (including the controlled statement).
1736 //
1737 unsigned ScopeFlags;
1738 if (C99orCXX)
1741 else
1743 ParseScope WhileScope(this, ScopeFlags);
1744
1745 // Parse the condition.
1746 Sema::ConditionResult Cond;
1747 SourceLocation LParen;
1748 SourceLocation RParen;
1749 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1750 Sema::ConditionKind::Boolean, LParen, RParen))
1751 return StmtError();
1752
1753 // OpenACC Restricts a while-loop inside of certain construct/clause
1754 // combinations, so diagnose that here in OpenACC mode.
1755 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
1756 getActions().OpenACC().ActOnWhileStmt(WhileLoc);
1757 getCurScope()->setPrecedingLabel(PrecedingLabel);
1758
1759 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1760 // there is no compound stmt. C90 does not have this clause. We only do this
1761 // if the body isn't a compound statement to avoid push/pop in common cases.
1762 //
1763 // C++ 6.5p2:
1764 // The substatement in an iteration-statement implicitly defines a local scope
1765 // which is entered and exited each time through the loop.
1766 //
1767 // See comments in ParseIfStatement for why we create a scope for the
1768 // condition and a new scope for substatement in C++.
1769 //
1770 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1771
1772 MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);
1773
1774 // Read the body statement.
1775 StmtResult Body(ParseStatement(TrailingElseLoc));
1776
1777 if (Body.isUsable())
1778 MIChecker.Check();
1779 // Pop the body scope if needed.
1780 InnerScope.Exit();
1781 WhileScope.Exit();
1782
1783 if (Cond.isInvalid() || Body.isInvalid())
1784 return StmtError();
1785
1786 return Actions.ActOnWhileStmt(WhileLoc, LParen, Cond, RParen, Body.get());
1787}
1788
1789StmtResult Parser::ParseDoStatement(LabelDecl *PrecedingLabel) {
1790 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1791 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1792
1793 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1794 // the case for C90. Start the loop scope.
1795 unsigned ScopeFlags;
1796 if (getLangOpts().C99)
1798 else
1800
1801 ParseScope DoScope(this, ScopeFlags);
1802
1803 // OpenACC Restricts a do-while-loop inside of certain construct/clause
1804 // combinations, so diagnose that here in OpenACC mode.
1805 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
1806 getActions().OpenACC().ActOnDoStmt(DoLoc);
1807 getCurScope()->setPrecedingLabel(PrecedingLabel);
1808
1809 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1810 // there is no compound stmt. C90 does not have this clause. We only do this
1811 // if the body isn't a compound statement to avoid push/pop in common cases.
1812 //
1813 // C++ 6.5p2:
1814 // The substatement in an iteration-statement implicitly defines a local scope
1815 // which is entered and exited each time through the loop.
1816 //
1817 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1818 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1819
1820 // Read the body statement.
1821 StmtResult Body(ParseStatement());
1822
1823 // Pop the body scope if needed.
1824 InnerScope.Exit();
1825
1826 // Reset this to disallow break/continue out of the condition.
1827 getCurScope()->setPrecedingLabel(nullptr);
1828
1829 if (Tok.isNot(tok::kw_while)) {
1830 if (!Body.isInvalid()) {
1831 Diag(Tok, diag::err_expected_while);
1832 Diag(DoLoc, diag::note_matching) << "'do'";
1833 SkipUntil(tok::semi, StopBeforeMatch);
1834 }
1835 return StmtError();
1836 }
1837 SourceLocation WhileLoc = ConsumeToken();
1838
1839 if (Tok.isNot(tok::l_paren)) {
1840 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1841 SkipUntil(tok::semi, StopBeforeMatch);
1842 return StmtError();
1843 }
1844
1845 // Parse the parenthesized expression.
1846 BalancedDelimiterTracker T(*this, tok::l_paren);
1847 T.consumeOpen();
1848
1849 // A do-while expression is not a condition, so can't have attributes.
1850 DiagnoseAndSkipCXX11Attributes();
1851
1852 SourceLocation Start = Tok.getLocation();
1854 if (!Cond.isUsable()) {
1855 if (!Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
1856 SkipUntil(tok::semi);
1857 Cond = Actions.CreateRecoveryExpr(
1858 Start, Start == Tok.getLocation() ? Start : PrevTokLocation, {},
1859 Actions.getASTContext().BoolTy);
1860 }
1861 T.consumeClose();
1862 DoScope.Exit();
1863
1864 if (Cond.isInvalid() || Body.isInvalid())
1865 return StmtError();
1866
1867 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1868 Cond.get(), T.getCloseLocation());
1869}
1870
1871bool Parser::isForRangeIdentifier() {
1872 assert(Tok.is(tok::identifier));
1873
1874 const Token &Next = NextToken();
1875 if (Next.is(tok::colon))
1876 return true;
1877
1878 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1879 TentativeParsingAction PA(*this);
1880 ConsumeToken();
1881 SkipCXX11Attributes();
1882 bool Result = Tok.is(tok::colon);
1883 PA.Revert();
1884 return Result;
1885 }
1886
1887 return false;
1888}
1889
1890StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc,
1891 LabelDecl *PrecedingLabel) {
1892 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1893 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1894
1895 SourceLocation CoawaitLoc;
1896 if (Tok.is(tok::kw_co_await))
1897 CoawaitLoc = ConsumeToken();
1898
1899 if (Tok.isNot(tok::l_paren)) {
1900 Diag(Tok, diag::err_expected_lparen_after) << "for";
1901 SkipUntil(tok::semi);
1902 return StmtError();
1903 }
1904
1905 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1906 getLangOpts().ObjC;
1907
1908 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1909 // the case for C90. Start the loop scope.
1910 //
1911 // C++ 6.4p3:
1912 // A name introduced by a declaration in a condition is in scope from its
1913 // point of declaration until the end of the substatements controlled by the
1914 // condition.
1915 // C++ 3.3.2p4:
1916 // Names declared in the for-init-statement, and in the condition of if,
1917 // while, for, and switch statements are local to the if, while, for, or
1918 // switch statement (including the controlled statement).
1919 // C++ 6.5.3p1:
1920 // Names declared in the for-init-statement are in the same declarative-region
1921 // as those declared in the condition.
1922 //
1923 unsigned ScopeFlags = 0;
1924 if (C99orCXXorObjC)
1926
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 /*EnterForConditionScope=*/true);
2109
2110 if (ForRangeInfo.ParsedForRangeDecl()) {
2111 Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
2112 : ForRangeInfo.ColonLoc,
2114 ? diag::warn_cxx17_compat_for_range_init_stmt
2115 : diag::ext_for_range_init_stmt)
2116 << (FirstPart.get() ? FirstPart.get()->getSourceRange()
2117 : SourceRange());
2118 if (EmptyInitStmtSemiLoc.isValid()) {
2119 Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
2120 << /*for-loop*/ 2
2121 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
2122 }
2123 }
2124
2125 if (SecondPart.isInvalid()) {
2126 ExprResult CondExpr = Actions.CreateRecoveryExpr(
2127 SecondPartStart,
2128 Tok.getLocation() == SecondPartStart ? SecondPartStart
2129 : PrevTokLocation,
2130 {}, Actions.PreferredConditionType(CK));
2131 if (!CondExpr.isInvalid())
2132 SecondPart = Actions.ActOnCondition(getCurScope(), ForLoc,
2133 CondExpr.get(), CK,
2134 /*MissingOK=*/false);
2135 }
2136
2137 } else {
2138 // We permit 'continue' and 'break' in the condition of a for loop.
2140
2141 ExprResult SecondExpr = ParseExpression();
2142 if (SecondExpr.isInvalid())
2143 SecondPart = Sema::ConditionError();
2144 else
2145 SecondPart = Actions.ActOnCondition(
2146 getCurScope(), ForLoc, SecondExpr.get(),
2147 Sema::ConditionKind::Boolean, /*MissingOK=*/true);
2148 }
2149 }
2150 }
2151
2152 // Enter a break / continue scope, if we didn't already enter one while
2153 // parsing the second part.
2154 if (!getCurScope()->isContinueScope())
2156
2157 // Parse the third part of the for statement.
2158 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
2159 if (Tok.isNot(tok::semi)) {
2160 if (!SecondPart.isInvalid())
2161 Diag(Tok, diag::err_expected_semi_for);
2162 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
2163 }
2164
2165 if (Tok.is(tok::semi)) {
2166 ConsumeToken();
2167 }
2168
2169 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
2170 ExprResult Third = ParseExpression();
2171 // FIXME: The C++11 standard doesn't actually say that this is a
2172 // discarded-value expression, but it clearly should be.
2173 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
2174 }
2175 }
2176 // Match the ')'.
2177 T.consumeClose();
2178
2179 // C++ Coroutines [stmt.iter]:
2180 // 'co_await' can only be used for a range-based for statement.
2181 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
2182 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
2183 CoawaitLoc = SourceLocation();
2184 }
2185
2186 if (CoawaitLoc.isValid() && getLangOpts().CPlusPlus20)
2187 Diag(CoawaitLoc, diag::warn_deprecated_for_co_await);
2188
2189 // We need to perform most of the semantic analysis for a C++0x for-range
2190 // statememt before parsing the body, in order to be able to deduce the type
2191 // of an auto-typed loop variable.
2192 StmtResult ForRangeStmt;
2193 StmtResult ForEachStmt;
2194
2195 if (ForRangeInfo.ParsedForRangeDecl()) {
2196 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
2197 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
2198 ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc,
2199 ForRangeInfo.RangeExpr.get(), T.getCloseLocation(), Sema::BFRK_Build,
2200 ForRangeInfo.LifetimeExtendTemps);
2201 } else if (ForEach) {
2202 // Similarly, we need to do the semantic analysis for a for-range
2203 // statement immediately in order to close over temporaries correctly.
2204 ForEachStmt = Actions.ObjC().ActOnObjCForCollectionStmt(
2205 ForLoc, FirstPart.get(), Collection.get(), T.getCloseLocation());
2206 } else {
2207 // In OpenMP loop region loop control variable must be captured and be
2208 // private. Perform analysis of first part (if any).
2209 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
2210 Actions.OpenMP().ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
2211 }
2212 }
2213
2214 // OpenACC Restricts a for-loop inside of certain construct/clause
2215 // combinations, so diagnose that here in OpenACC mode.
2216 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
2217 if (ForRangeInfo.ParsedForRangeDecl())
2218 getActions().OpenACC().ActOnRangeForStmtBegin(ForLoc, ForRangeStmt.get());
2219 else
2221 ForLoc, FirstPart.get(), SecondPart.get().second, ThirdPart.get());
2222
2223 // Set this only right before parsing the body to disallow break/continue in
2224 // the other parts.
2225 getCurScope()->setPrecedingLabel(PrecedingLabel);
2226
2227 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2228 // there is no compound stmt. C90 does not have this clause. We only do this
2229 // if the body isn't a compound statement to avoid push/pop in common cases.
2230 //
2231 // C++ 6.5p2:
2232 // The substatement in an iteration-statement implicitly defines a local scope
2233 // which is entered and exited each time through the loop.
2234 //
2235 // See comments in ParseIfStatement for why we create a scope for
2236 // for-init-statement/condition and a new scope for substatement in C++.
2237 //
2238 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
2239 Tok.is(tok::l_brace));
2240
2241 // The body of the for loop has the same local mangling number as the
2242 // for-init-statement.
2243 // It will only be incremented if the body contains other things that would
2244 // normally increment the mangling number (like a compound statement).
2245 if (C99orCXXorObjC)
2247
2248 MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
2249
2250 // Read the body statement.
2251 StmtResult Body(ParseStatement(TrailingElseLoc));
2252
2253 if (Body.isUsable())
2254 MIChecker.Check();
2255
2256 // Pop the body scope if needed.
2257 InnerScope.Exit();
2258
2259 getActions().OpenACC().ActOnForStmtEnd(ForLoc, Body);
2260
2261 // Leave the for-scope.
2262 ForScope.Exit();
2263
2264 if (Body.isInvalid())
2265 return StmtError();
2266
2267 if (ForEach)
2268 return Actions.ObjC().FinishObjCForCollectionStmt(ForEachStmt.get(),
2269 Body.get());
2270
2271 if (ForRangeInfo.ParsedForRangeDecl())
2272 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
2273
2274 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
2275 SecondPart, ThirdPart, T.getCloseLocation(),
2276 Body.get());
2277}
2278
2279StmtResult Parser::ParseGotoStatement() {
2280 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
2281 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
2282
2283 StmtResult Res;
2284 if (Tok.is(tok::identifier)) {
2285 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
2286 Tok.getLocation());
2287 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
2288 ConsumeToken();
2289 } else if (Tok.is(tok::star)) {
2290 // GNU indirect goto extension.
2291 Diag(Tok, diag::ext_gnu_indirect_goto);
2292 SourceLocation StarLoc = ConsumeToken();
2294 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
2295 SkipUntil(tok::semi, StopBeforeMatch);
2296 return StmtError();
2297 }
2298 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
2299 } else {
2300 Diag(Tok, diag::err_expected) << tok::identifier;
2301 return StmtError();
2302 }
2303
2304 return Res;
2305}
2306
2307StmtResult Parser::ParseBreakOrContinueStatement(bool IsContinue) {
2308 SourceLocation KwLoc = ConsumeToken(); // Eat the keyword.
2309 SourceLocation LabelLoc;
2310 LabelDecl *Target = nullptr;
2311 if (Tok.is(tok::identifier)) {
2312 Target =
2313 Actions.LookupExistingLabel(Tok.getIdentifierInfo(), Tok.getLocation());
2314 LabelLoc = ConsumeToken();
2315 if (!getLangOpts().NamedLoops)
2316 // TODO: Make this a compatibility/extension warning instead once the
2317 // syntax of this feature is finalised.
2318 Diag(LabelLoc, diag::err_c2y_labeled_break_continue) << IsContinue;
2319 if (!Target) {
2320 Diag(LabelLoc, diag::err_break_continue_label_not_found) << IsContinue;
2321 return StmtError();
2322 }
2323 }
2324
2325 if (IsContinue)
2326 return Actions.ActOnContinueStmt(KwLoc, getCurScope(), Target, LabelLoc);
2327 return Actions.ActOnBreakStmt(KwLoc, getCurScope(), Target, LabelLoc);
2328}
2329
2330StmtResult Parser::ParseContinueStatement() {
2331 return ParseBreakOrContinueStatement(/*IsContinue=*/true);
2332}
2333
2334StmtResult Parser::ParseBreakStatement() {
2335 return ParseBreakOrContinueStatement(/*IsContinue=*/false);
2336}
2337
2338StmtResult Parser::ParseReturnStatement() {
2339 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
2340 "Not a return stmt!");
2341 bool IsCoreturn = Tok.is(tok::kw_co_return);
2342 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
2343
2344 ExprResult R;
2345 if (Tok.isNot(tok::semi)) {
2346 if (!IsCoreturn)
2347 PreferredType.enterReturn(Actions, Tok.getLocation());
2348 // FIXME: Code completion for co_return.
2349 if (Tok.is(tok::code_completion) && !IsCoreturn) {
2350 cutOffParsing();
2351 Actions.CodeCompletion().CodeCompleteExpression(
2352 getCurScope(), PreferredType.get(Tok.getLocation()));
2353 return StmtError();
2354 }
2355
2356 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
2357 R = ParseInitializer();
2358 if (R.isUsable())
2359 Diag(R.get()->getBeginLoc(),
2361 ? diag::warn_cxx98_compat_generalized_initializer_lists
2362 : diag::ext_generalized_initializer_lists)
2363 << R.get()->getSourceRange();
2364 } else
2365 R = ParseExpression();
2366 if (R.isInvalid()) {
2367 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2368 return StmtError();
2369 }
2370 }
2371 if (IsCoreturn)
2372 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
2373 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
2374}
2375
2376StmtResult Parser::ParseDeferStatement(SourceLocation *TrailingElseLoc) {
2377 assert(Tok.is(tok::kw__Defer));
2378 SourceLocation DeferLoc = ConsumeToken();
2379
2380 Actions.ActOnStartOfDeferStmt(DeferLoc, getCurScope());
2381
2382 auto OnError = llvm::make_scope_exit(
2383 [&] { Actions.ActOnDeferStmtError(getCurScope()); });
2384
2385 StmtResult Res = ParseStatement(TrailingElseLoc);
2386 if (!Res.isUsable())
2387 return StmtError();
2388
2389 // The grammar specifically calls for an unlabeled-statement here.
2390 if (auto *L = dyn_cast<LabelStmt>(Res.get())) {
2391 Diag(L->getIdentLoc(), diag::err_defer_ts_labeled_stmt);
2392 return StmtError();
2393 }
2394
2395 OnError.release();
2396 return Actions.ActOnEndOfDeferStmt(Res.get(), getCurScope());
2397}
2398
2399StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
2400 ParsedStmtContext StmtCtx,
2401 SourceLocation *TrailingElseLoc,
2402 ParsedAttributes &Attrs,
2403 LabelDecl *PrecedingLabel) {
2404 // Create temporary attribute list.
2405 ParsedAttributes TempAttrs(AttrFactory);
2406
2407 SourceLocation StartLoc = Tok.getLocation();
2408
2409 // Get loop hints and consume annotated token.
2410 while (Tok.is(tok::annot_pragma_loop_hint)) {
2411 LoopHint Hint;
2412 if (!HandlePragmaLoopHint(Hint))
2413 continue;
2414
2415 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
2416 ArgsUnion(Hint.ValueExpr)};
2417 TempAttrs.addNew(Hint.PragmaNameLoc->getIdentifierInfo(), Hint.Range,
2418 AttributeScopeInfo(), ArgHints, /*numArgs=*/4,
2419 ParsedAttr::Form::Pragma());
2420 }
2421
2422 // Get the next statement.
2423 MaybeParseCXX11Attributes(Attrs);
2424
2425 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2426 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
2427 Stmts, StmtCtx, TrailingElseLoc, Attrs, EmptyDeclSpecAttrs,
2428 PrecedingLabel);
2429
2430 Attrs.takeAllPrependingFrom(TempAttrs);
2431
2432 // Start of attribute range may already be set for some invalid input.
2433 // See PR46336.
2434 if (Attrs.Range.getBegin().isInvalid())
2435 Attrs.Range.setBegin(StartLoc);
2436
2437 return S;
2438}
2439
2440Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2441 assert(Tok.is(tok::l_brace));
2442 SourceLocation LBraceLoc = Tok.getLocation();
2443
2444 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
2445 "parsing function body");
2446
2447 // Save and reset current vtordisp stack if we have entered a C++ method body.
2448 bool IsCXXMethod =
2449 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2450 Sema::PragmaStackSentinelRAII
2451 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2452
2453 // Do not enter a scope for the brace, as the arguments are in the same scope
2454 // (the function body) as the body itself. Instead, just read the statement
2455 // list and put it into a CompoundStmt for safe keeping.
2456 StmtResult FnBody(ParseCompoundStatementBody());
2457
2458 // If the function body could not be parsed, make a bogus compoundstmt.
2459 if (FnBody.isInvalid()) {
2460 Sema::CompoundScopeRAII CompoundScope(Actions);
2461 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, {}, false);
2462 }
2463
2464 BodyScope.Exit();
2465 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2466}
2467
2468Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2469 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2470 SourceLocation TryLoc = ConsumeToken();
2471
2472 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
2473 "parsing function try block");
2474
2475 // Constructor initializer list?
2476 if (Tok.is(tok::colon))
2477 ParseConstructorInitializer(Decl);
2478 else
2479 Actions.ActOnDefaultCtorInitializers(Decl);
2480
2481 // Save and reset current vtordisp stack if we have entered a C++ method body.
2482 bool IsCXXMethod =
2483 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2484 Sema::PragmaStackSentinelRAII
2485 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2486
2487 SourceLocation LBraceLoc = Tok.getLocation();
2488 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2489 // If we failed to parse the try-catch, we just give the function an empty
2490 // compound statement as the body.
2491 if (FnBody.isInvalid()) {
2492 Sema::CompoundScopeRAII CompoundScope(Actions);
2493 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, {}, false);
2494 }
2495
2496 BodyScope.Exit();
2497 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2498}
2499
2500bool Parser::trySkippingFunctionBody() {
2501 assert(SkipFunctionBodies &&
2502 "Should only be called when SkipFunctionBodies is enabled");
2503 if (!PP.isCodeCompletionEnabled()) {
2504 SkipFunctionBody();
2505 return true;
2506 }
2507
2508 // We're in code-completion mode. Skip parsing for all function bodies unless
2509 // the body contains the code-completion point.
2510 TentativeParsingAction PA(*this);
2511 bool IsTryCatch = Tok.is(tok::kw_try);
2512 CachedTokens Toks;
2513 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2514 if (llvm::any_of(Toks, [](const Token &Tok) {
2515 return Tok.is(tok::code_completion);
2516 })) {
2517 PA.Revert();
2518 return false;
2519 }
2520 if (ErrorInPrologue) {
2521 PA.Commit();
2523 return true;
2524 }
2525 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2526 PA.Revert();
2527 return false;
2528 }
2529 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2530 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2531 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2532 PA.Revert();
2533 return false;
2534 }
2535 }
2536 PA.Commit();
2537 return true;
2538}
2539
2540StmtResult Parser::ParseCXXTryBlock() {
2541 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2542
2543 SourceLocation TryLoc = ConsumeToken();
2544 return ParseCXXTryBlockCommon(TryLoc);
2545}
2546
2547StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2548 if (Tok.isNot(tok::l_brace))
2549 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2550
2551 StmtResult TryBlock(ParseCompoundStatement(
2552 /*isStmtExpr=*/false,
2555 if (TryBlock.isInvalid())
2556 return TryBlock;
2557
2558 // Borland allows SEH-handlers with 'try'
2559
2560 if ((Tok.is(tok::identifier) &&
2561 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2562 Tok.is(tok::kw___finally)) {
2563 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2564 StmtResult Handler;
2565 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2566 SourceLocation Loc = ConsumeToken();
2567 Handler = ParseSEHExceptBlock(Loc);
2568 }
2569 else {
2570 SourceLocation Loc = ConsumeToken();
2571 Handler = ParseSEHFinallyBlock(Loc);
2572 }
2573 if(Handler.isInvalid())
2574 return Handler;
2575
2576 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2577 TryLoc,
2578 TryBlock.get(),
2579 Handler.get());
2580 }
2581 else {
2582 StmtVector Handlers;
2583
2584 // C++11 attributes can't appear here, despite this context seeming
2585 // statement-like.
2586 DiagnoseAndSkipCXX11Attributes();
2587
2588 if (Tok.isNot(tok::kw_catch))
2589 return StmtError(Diag(Tok, diag::err_expected_catch));
2590 while (Tok.is(tok::kw_catch)) {
2591 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2592 if (!Handler.isInvalid())
2593 Handlers.push_back(Handler.get());
2594 }
2595 // Don't bother creating the full statement if we don't have any usable
2596 // handlers.
2597 if (Handlers.empty())
2598 return StmtError();
2599
2600 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2601 }
2602}
2603
2604StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2605 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2606
2607 SourceLocation CatchLoc = ConsumeToken();
2608
2609 BalancedDelimiterTracker T(*this, tok::l_paren);
2610 if (T.expectAndConsume())
2611 return StmtError();
2612
2613 // C++ 3.3.2p3:
2614 // The name in a catch exception-declaration is local to the handler and
2615 // shall not be redeclared in the outermost block of the handler.
2616 ParseScope CatchScope(
2619
2620 // exception-declaration is equivalent to '...' or a parameter-declaration
2621 // without default arguments.
2622 Decl *ExceptionDecl = nullptr;
2623 if (Tok.isNot(tok::ellipsis)) {
2624 ParsedAttributes Attributes(AttrFactory);
2625 MaybeParseCXX11Attributes(Attributes);
2626
2627 DeclSpec DS(AttrFactory);
2628
2629 if (ParseCXXTypeSpecifierSeq(DS))
2630 return StmtError();
2631
2632 Declarator ExDecl(DS, Attributes, DeclaratorContext::CXXCatch);
2633 ParseDeclarator(ExDecl);
2634 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2635 } else
2636 ConsumeToken();
2637
2638 T.consumeClose();
2639 if (T.getCloseLocation().isInvalid())
2640 return StmtError();
2641
2642 if (Tok.isNot(tok::l_brace))
2643 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2644
2645 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2646 StmtResult Block(ParseCompoundStatement());
2647 if (Block.isInvalid())
2648 return Block;
2649
2650 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2651}
2652
2653void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2654 IfExistsCondition Result;
2655 if (ParseMicrosoftIfExistsCondition(Result))
2656 return;
2657
2658 // Handle dependent statements by parsing the braces as a compound statement.
2659 // This is not the same behavior as Visual C++, which don't treat this as a
2660 // compound statement, but for Clang's type checking we can't have anything
2661 // inside these braces escaping to the surrounding code.
2662 if (Result.Behavior == IfExistsBehavior::Dependent) {
2663 if (!Tok.is(tok::l_brace)) {
2664 Diag(Tok, diag::err_expected) << tok::l_brace;
2665 return;
2666 }
2667
2668 StmtResult Compound = ParseCompoundStatement();
2669 if (Compound.isInvalid())
2670 return;
2671
2672 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2673 Result.IsIfExists,
2674 Result.SS,
2675 Result.Name,
2676 Compound.get());
2677 if (DepResult.isUsable())
2678 Stmts.push_back(DepResult.get());
2679 return;
2680 }
2681
2682 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2683 if (Braces.consumeOpen()) {
2684 Diag(Tok, diag::err_expected) << tok::l_brace;
2685 return;
2686 }
2687
2688 switch (Result.Behavior) {
2690 // Parse the statements below.
2691 break;
2692
2694 llvm_unreachable("Dependent case handled above");
2695
2697 Braces.skipToEnd();
2698 return;
2699 }
2700
2701 // Condition is true, parse the statements.
2702 while (Tok.isNot(tok::r_brace)) {
2703 StmtResult R =
2704 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
2705 if (R.isUsable())
2706 Stmts.push_back(R.get());
2707 }
2708 Braces.consumeClose();
2709}
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Token Tok
The Token.
FormatToken * Next
The next token in the unwrapped line.
bool is(tok::TokenKind Kind) const
#define SM(sm)
static void DiagnoseLabelFollowedByDecl(Parser &P, const Stmt *SubStmt)
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
This file declares facilities that support code completion.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
Defines the clang::TokenKind enum and support functions.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
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:276
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
IdentifierInfo * getIdentifierInfo() const
Represents the declaration of a label.
Definition Decl.h: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:396
Parser - This implements a parser for the C family of languages.
Definition Parser.h:171
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:85
SourceLocation getEndOfPreviousToken() const
Definition Parser.cpp:1872
Preprocessor & getPreprocessor() const
Definition Parser.h:206
Sema::FullExprArg FullExprArg
Definition Parser.h:3632
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:262
Sema & getActions() const
Definition Parser.h:207
ExprResult ParseCaseExpression(SourceLocation CaseLoc)
SmallVector< Stmt *, 24 > StmtVector
A SmallVector of statements.
Definition Parser.h:7184
friend class ColonProtectionRAIIObject
Definition Parser.h:196
StmtResult ParseOpenACCDirectiveStmt()
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:270
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:219
Scope * getCurScope() const
Definition Parser.h:211
friend class InMessageExpressionRAIIObject
Definition Parser.h:5325
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition Parser.h:495
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
const Token & getCurToken() const
Definition Parser.h:210
SourceLocation MisleadingIndentationElseLoc
The location of the first statement inside an else that might have a missleading indentation.
Definition Parser.h:7189
const LangOptions & getLangOpts() const
Definition Parser.h:204
friend class ParenBraceBracketBalancer
Definition Parser.h:198
ExprResult ParseExpression(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
Simple precedence-based parser for binary/ternary operators.
Definition ParseExpr.cpp:47
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:476
@ StopAtCodeCompletion
Stop at code completion.
Definition Parser.h:477
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:474
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:324
friend class BalancedDelimiterTracker
Definition Parser.h:199
unsigned getNumDirectives() const
Retrieve the number of Directives that have been processed by the Preprocessor.
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
SourceManager & getSourceManager() const
void AddFlags(unsigned Flags)
Sets up the specified scope flags and adjusts the scope state variables accordingly.
Definition Scope.cpp:116
void setPrecedingLabel(LabelDecl *LD)
Definition Scope.h:277
void decrementMSManglingNumber()
Definition Scope.h:379
@ SEHTryScope
This scope corresponds to an SEH try.
Definition Scope.h:125
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition Scope.h:66
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SwitchScope
This is a scope that corresponds to a switch statement.
Definition Scope.h:102
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition Scope.h:55
@ CatchScope
This is the scope of a C++ catch statement.
Definition Scope.h:141
@ CompoundStmtScope
This is a compound statement scope.
Definition Scope.h:134
@ FnTryCatchScope
This is the scope for a function-level C++ try or catch scope.
Definition Scope.h:108
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
@ TryScope
This is the scope of a C++ try statement.
Definition Scope.h:105
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
@ PCC_ForInit
Code completion occurs at the beginning of the initialization statement (or expression) in a for loop...
@ PCC_Expression
Code completion occurs within an expression.
@ PCC_Statement
Code completion occurs within a statement, which may also be an expression or a declaration.
void ActOnWhileStmt(SourceLocation WhileLoc)
void ActOnDoStmt(SourceLocation DoLoc)
void ActOnRangeForStmtBegin(SourceLocation ForLoc, const Stmt *OldRangeFor, const Stmt *RangeFor)
void ActOnForStmtEnd(SourceLocation ForLoc, StmtResult Body)
void ActOnForStmtBegin(SourceLocation ForLoc, const Stmt *First, const Stmt *Second, const Stmt *Third)
std::pair< VarDecl *, Expr * > get() const
Definition Sema.h:7804
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7824
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7826
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7825
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
SemaOpenACC & OpenACC()
Definition Sema.h:1491
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition Sema.h:6691
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6708
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6723
@ BFRK_Build
Initial building of a for-range statement.
Definition Sema.h:11037
static ConditionResult ConditionError()
Definition Sema.h:7810
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
void setBegin(SourceLocation b)
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:195
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:140
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition Token.h:284
bool isOneOf(Ts... Ks) const
Definition Token.h:103
bool isNot(tok::TokenKind K) const
Definition Token.h:109
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition Token.h:129
void setAnnotationValue(void *val)
Definition Token.h:246
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Defines the clang::TargetInfo interface.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
IfStatementKind
In an if statement, this denotes whether the statement is a constexpr or consteval if statement.
Definition Specifiers.h:39
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition ParsedAttr.h:103
@ Error
Annotation has failed and emitted an error.
Definition Parser.h:57
std::pair< FileID, unsigned > FileIDAndOffset
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
@ Skip
Skip the block entirely; this code is never used.
Definition Parser.h:139
@ Parse
Parse the block; this code is always used.
Definition Parser.h:137
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
StmtResult StmtEmpty()
Definition Ownership.h:273
void takeAndConcatenateAttrs(ParsedAttributes &First, ParsedAttributes &&Second)
Consumes the attributes from Second and concatenates them at the end of First.
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1215
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2248
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