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