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.
974 StmtResult R;
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 //
1701 getCurScope()->setPrecedingLabel(PrecedingLabel);
1702 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1703
1704 // We have incremented the mangling number for the SwitchScope and the
1705 // InnerScope, which is one too many.
1706 if (C99orCXX)
1708
1709 // Read the body statement.
1710 StmtResult Body(ParseStatement(TrailingElseLoc));
1711
1712 // Pop the scopes.
1713 InnerScope.Exit();
1714 SwitchScope.Exit();
1715
1716 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1717}
1718
1719StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc,
1720 LabelDecl *PrecedingLabel) {
1721 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1722 SourceLocation WhileLoc = Tok.getLocation();
1723 ConsumeToken(); // eat the 'while'.
1724
1725 if (Tok.isNot(tok::l_paren)) {
1726 Diag(Tok, diag::err_expected_lparen_after) << "while";
1727 SkipUntil(tok::semi);
1728 return StmtError();
1729 }
1730
1731 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1732
1733 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1734 // the case for C90. Start the loop scope.
1735 //
1736 // C++ 6.4p3:
1737 // A name introduced by a declaration in a condition is in scope from its
1738 // point of declaration until the end of the substatements controlled by the
1739 // condition.
1740 // C++ 3.3.2p4:
1741 // Names declared in the for-init-statement, and in the condition of if,
1742 // while, for, and switch statements are local to the if, while, for, or
1743 // switch statement (including the controlled statement).
1744 //
1745 unsigned ScopeFlags;
1746 if (C99orCXX)
1749 else
1751 ParseScope WhileScope(this, ScopeFlags);
1752
1753 // Parse the condition.
1754 Sema::ConditionResult Cond;
1755 SourceLocation LParen;
1756 SourceLocation RParen;
1757 if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1758 Sema::ConditionKind::Boolean, LParen, RParen))
1759 return StmtError();
1760
1761 // OpenACC Restricts a while-loop inside of certain construct/clause
1762 // combinations, so diagnose that here in OpenACC mode.
1763 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
1764 getActions().OpenACC().ActOnWhileStmt(WhileLoc);
1765 getCurScope()->setPrecedingLabel(PrecedingLabel);
1766
1767 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1768 // there is no compound stmt. C90 does not have this clause. We only do this
1769 // if the body isn't a compound statement to avoid push/pop in common cases.
1770 //
1771 // C++ 6.5p2:
1772 // The substatement in an iteration-statement implicitly defines a local scope
1773 // which is entered and exited each time through the loop.
1774 //
1775 // See comments in ParseIfStatement for why we create a scope for the
1776 // condition and a new scope for substatement in C++.
1777 //
1778 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1779
1780 MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);
1781
1782 // Read the body statement.
1783 StmtResult Body(ParseStatement(TrailingElseLoc));
1784
1785 if (Body.isUsable())
1786 MIChecker.Check();
1787 // Pop the body scope if needed.
1788 InnerScope.Exit();
1789 WhileScope.Exit();
1790
1791 if (Cond.isInvalid() || Body.isInvalid())
1792 return StmtError();
1793
1794 return Actions.ActOnWhileStmt(WhileLoc, LParen, Cond, RParen, Body.get());
1795}
1796
1797StmtResult Parser::ParseDoStatement(LabelDecl *PrecedingLabel) {
1798 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1799 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1800
1801 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1802 // the case for C90. Start the loop scope.
1803 unsigned ScopeFlags;
1804 if (getLangOpts().C99)
1806 else
1808
1809 ParseScope DoScope(this, ScopeFlags);
1810
1811 // OpenACC Restricts a do-while-loop inside of certain construct/clause
1812 // combinations, so diagnose that here in OpenACC mode.
1813 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
1814 getActions().OpenACC().ActOnDoStmt(DoLoc);
1815 getCurScope()->setPrecedingLabel(PrecedingLabel);
1816
1817 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1818 // there is no compound stmt. C90 does not have this clause. We only do this
1819 // if the body isn't a compound statement to avoid push/pop in common cases.
1820 //
1821 // C++ 6.5p2:
1822 // The substatement in an iteration-statement implicitly defines a local scope
1823 // which is entered and exited each time through the loop.
1824 //
1825 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1826 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1827
1828 // Read the body statement.
1829 StmtResult Body(ParseStatement());
1830
1831 // Pop the body scope if needed.
1832 InnerScope.Exit();
1833
1834 // Reset this to disallow break/continue out of the condition.
1835 getCurScope()->setPrecedingLabel(nullptr);
1836
1837 if (Tok.isNot(tok::kw_while)) {
1838 if (!Body.isInvalid()) {
1839 Diag(Tok, diag::err_expected_while);
1840 Diag(DoLoc, diag::note_matching) << "'do'";
1841 SkipUntil(tok::semi, StopBeforeMatch);
1842 }
1843 return StmtError();
1844 }
1845 SourceLocation WhileLoc = ConsumeToken();
1846
1847 if (Tok.isNot(tok::l_paren)) {
1848 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1849 SkipUntil(tok::semi, StopBeforeMatch);
1850 return StmtError();
1851 }
1852
1853 // Parse the parenthesized expression.
1854 BalancedDelimiterTracker T(*this, tok::l_paren);
1855 T.consumeOpen();
1856
1857 // A do-while expression is not a condition, so can't have attributes.
1858 DiagnoseAndSkipCXX11Attributes();
1859
1860 SourceLocation Start = Tok.getLocation();
1862 if (!Cond.isUsable()) {
1863 if (!Tok.isOneOf(tok::r_paren, tok::r_square, tok::r_brace))
1864 SkipUntil(tok::semi);
1865 Cond = Actions.CreateRecoveryExpr(
1866 Start, Start == Tok.getLocation() ? Start : PrevTokLocation, {},
1867 Actions.getASTContext().BoolTy);
1868 }
1869 T.consumeClose();
1870 DoScope.Exit();
1871
1872 if (Cond.isInvalid() || Body.isInvalid())
1873 return StmtError();
1874
1875 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1876 Cond.get(), T.getCloseLocation());
1877}
1878
1879bool Parser::isForRangeIdentifier() {
1880 assert(Tok.is(tok::identifier));
1881
1882 const Token &Next = NextToken();
1883 if (Next.is(tok::colon))
1884 return true;
1885
1886 if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1887 TentativeParsingAction PA(*this);
1888 ConsumeToken();
1889 SkipCXX11Attributes();
1890 bool Result = Tok.is(tok::colon);
1891 PA.Revert();
1892 return Result;
1893 }
1894
1895 return false;
1896}
1897
1898StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc,
1899 LabelDecl *PrecedingLabel) {
1900 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1901 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1902
1903 SourceLocation CoawaitLoc;
1904 if (Tok.is(tok::kw_co_await))
1905 CoawaitLoc = ConsumeToken();
1906
1907 if (Tok.isNot(tok::l_paren)) {
1908 Diag(Tok, diag::err_expected_lparen_after) << "for";
1909 SkipUntil(tok::semi);
1910 return StmtError();
1911 }
1912
1913 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1914 getLangOpts().ObjC;
1915
1916 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1917 // the case for C90. Start the loop scope.
1918 //
1919 // C++ 6.4p3:
1920 // A name introduced by a declaration in a condition is in scope from its
1921 // point of declaration until the end of the substatements controlled by the
1922 // condition.
1923 // C++ 3.3.2p4:
1924 // Names declared in the for-init-statement, and in the condition of if,
1925 // while, for, and switch statements are local to the if, while, for, or
1926 // switch statement (including the controlled statement).
1927 // C++ 6.5.3p1:
1928 // Names declared in the for-init-statement are in the same declarative-region
1929 // as those declared in the condition.
1930 //
1931 unsigned ScopeFlags = 0;
1932 if (C99orCXXorObjC)
1934
1935 ParseScope ForScope(this, ScopeFlags);
1936
1937 BalancedDelimiterTracker T(*this, tok::l_paren);
1938 T.consumeOpen();
1939
1941
1942 bool ForEach = false;
1943 StmtResult FirstPart;
1944 Sema::ConditionResult SecondPart;
1945 ExprResult Collection;
1946 ForRangeInfo ForRangeInfo;
1947 FullExprArg ThirdPart(Actions);
1948
1949 if (Tok.is(tok::code_completion)) {
1950 cutOffParsing();
1951 Actions.CodeCompletion().CodeCompleteOrdinaryName(
1954 return StmtError();
1955 }
1956
1957 ParsedAttributes attrs(AttrFactory);
1958 MaybeParseCXX11Attributes(attrs);
1959
1960 SourceLocation EmptyInitStmtSemiLoc;
1961
1962 // Parse the first part of the for specifier.
1963 if (Tok.is(tok::semi)) { // for (;
1964 ProhibitAttributes(attrs);
1965 // no first part, eat the ';'.
1966 SourceLocation SemiLoc = Tok.getLocation();
1967 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
1968 EmptyInitStmtSemiLoc = SemiLoc;
1969 ConsumeToken();
1970 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1971 isForRangeIdentifier()) {
1972 ProhibitAttributes(attrs);
1973 IdentifierInfo *Name = Tok.getIdentifierInfo();
1974 SourceLocation Loc = ConsumeToken();
1975 MaybeParseCXX11Attributes(attrs);
1976
1977 ForRangeInfo.ColonLoc = ConsumeToken();
1978 if (Tok.is(tok::l_brace))
1979 ForRangeInfo.RangeExpr = ParseBraceInitializer();
1980 else
1981 ForRangeInfo.RangeExpr = ParseExpression();
1982
1983 Diag(Loc, diag::err_for_range_identifier)
1984 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
1985 ? FixItHint::CreateInsertion(Loc, "auto &&")
1986 : FixItHint());
1987
1988 ForRangeInfo.LoopVar =
1989 Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name, attrs);
1990 } else if (isForInitDeclaration()) { // for (int X = 4;
1991 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1992
1993 // Parse declaration, which eats the ';'.
1994 if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
1995 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1996 Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
1997 }
1998 DeclGroupPtrTy DG;
1999 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2000 if (!getLangOpts().CPlusPlus &&
2001 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2002 ProhibitAttributes(attrs);
2003 Decl *D = ParseStaticAssertDeclaration(DeclEnd);
2004 DG = Actions.ConvertDeclToDeclGroup(D);
2005 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2006 } else if (Tok.is(tok::kw_using)) {
2007 DG = ParseAliasDeclarationInInitStatement(DeclaratorContext::ForInit,
2008 attrs);
2009 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2010 } else {
2011 // In C++0x, "for (T NS:a" might not be a typo for ::
2012 bool MightBeForRangeStmt = getLangOpts().CPlusPlus || getLangOpts().ObjC;
2013 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
2014 ParsedAttributes DeclSpecAttrs(AttrFactory);
2015 DG = ParseSimpleDeclaration(
2016 DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false,
2017 MightBeForRangeStmt ? &ForRangeInfo : nullptr);
2018 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2019 if (ForRangeInfo.ParsedForRangeDecl()) {
2020 Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11
2021 ? diag::warn_cxx98_compat_for_range
2022 : diag::ext_for_range);
2023 ForRangeInfo.LoopVar = FirstPart;
2024 FirstPart = StmtResult();
2025 } else if (Tok.is(tok::semi)) { // for (int x = 4;
2026 ConsumeToken();
2027 } else if ((ForEach = isTokIdentifier_in())) {
2028 Actions.ActOnForEachDeclStmt(DG);
2029 // ObjC: for (id x in expr)
2030 ConsumeToken(); // consume 'in'
2031
2032 if (Tok.is(tok::code_completion)) {
2033 cutOffParsing();
2034 Actions.CodeCompletion().CodeCompleteObjCForCollection(getCurScope(),
2035 DG);
2036 return StmtError();
2037 }
2038 Collection = ParseExpression();
2039 } else {
2040 Diag(Tok, diag::err_expected_semi_for);
2041 }
2042 }
2043 } else {
2044 ProhibitAttributes(attrs);
2046
2047 ForEach = isTokIdentifier_in();
2048
2049 // Turn the expression into a stmt.
2050 if (!Value.isInvalid()) {
2051 if (ForEach)
2052 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
2053 else {
2054 // We already know this is not an init-statement within a for loop, so
2055 // if we are parsing a C++11 range-based for loop, we should treat this
2056 // expression statement as being a discarded value expression because
2057 // we will err below. This way we do not warn on an unused expression
2058 // that was an error in the first place, like with: for (expr : expr);
2059 bool IsRangeBasedFor =
2060 getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon);
2061 FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
2062 }
2063 }
2064
2065 if (Tok.is(tok::semi)) {
2066 ConsumeToken();
2067 } else if (ForEach) {
2068 ConsumeToken(); // consume 'in'
2069
2070 if (Tok.is(tok::code_completion)) {
2071 cutOffParsing();
2072 Actions.CodeCompletion().CodeCompleteObjCForCollection(getCurScope(),
2073 nullptr);
2074 return StmtError();
2075 }
2076 Collection = ParseExpression();
2077 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
2078 // User tried to write the reasonable, but ill-formed, for-range-statement
2079 // for (expr : expr) { ... }
2080 Diag(Tok, diag::err_for_range_expected_decl)
2081 << FirstPart.get()->getSourceRange();
2082 SkipUntil(tok::r_paren, StopBeforeMatch);
2083 SecondPart = Sema::ConditionError();
2084 } else {
2085 if (!Value.isInvalid()) {
2086 Diag(Tok, diag::err_expected_semi_for);
2087 } else {
2088 // Skip until semicolon or rparen, don't consume it.
2089 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
2090 if (Tok.is(tok::semi))
2091 ConsumeToken();
2092 }
2093 }
2094 }
2095
2096 // Parse the second part of the for specifier.
2097 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
2098 !SecondPart.isInvalid()) {
2099 // Parse the second part of the for specifier.
2100 if (Tok.is(tok::semi)) { // for (...;;
2101 // no second part.
2102 } else if (Tok.is(tok::r_paren)) {
2103 // missing both semicolons.
2104 } else {
2105 if (getLangOpts().CPlusPlus) {
2106 // C++2a: We've parsed an init-statement; we might have a
2107 // for-range-declaration next.
2108 bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
2109 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
2110 SourceLocation SecondPartStart = Tok.getLocation();
2112 SecondPart = ParseCXXCondition(
2113 /*InitStmt=*/nullptr, ForLoc, CK,
2114 // FIXME: recovery if we don't see another semi!
2115 /*MissingOK=*/true, MightBeForRangeStmt ? &ForRangeInfo : nullptr,
2116 /*EnterForConditionScope=*/true);
2117
2118 if (ForRangeInfo.ParsedForRangeDecl()) {
2119 Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
2120 : ForRangeInfo.ColonLoc,
2122 ? diag::warn_cxx17_compat_for_range_init_stmt
2123 : diag::ext_for_range_init_stmt)
2124 << (FirstPart.get() ? FirstPart.get()->getSourceRange()
2125 : SourceRange());
2126 if (EmptyInitStmtSemiLoc.isValid()) {
2127 Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
2128 << /*for-loop*/ 2
2129 << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
2130 }
2131 }
2132
2133 if (SecondPart.isInvalid()) {
2134 ExprResult CondExpr = Actions.CreateRecoveryExpr(
2135 SecondPartStart,
2136 Tok.getLocation() == SecondPartStart ? SecondPartStart
2137 : PrevTokLocation,
2138 {}, Actions.PreferredConditionType(CK));
2139 if (!CondExpr.isInvalid())
2140 SecondPart = Actions.ActOnCondition(getCurScope(), ForLoc,
2141 CondExpr.get(), CK,
2142 /*MissingOK=*/false);
2143 }
2144
2145 } else {
2146 // We permit 'continue' and 'break' in the condition of a for loop.
2148
2149 ExprResult SecondExpr = ParseExpression();
2150 if (SecondExpr.isInvalid())
2151 SecondPart = Sema::ConditionError();
2152 else
2153 SecondPart = Actions.ActOnCondition(
2154 getCurScope(), ForLoc, SecondExpr.get(),
2155 Sema::ConditionKind::Boolean, /*MissingOK=*/true);
2156 }
2157 }
2158 }
2159
2160 // Enter a break / continue scope, if we didn't already enter one while
2161 // parsing the second part.
2162 if (!getCurScope()->isContinueScope())
2164
2165 // Parse the third part of the for statement.
2166 if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
2167 if (Tok.isNot(tok::semi)) {
2168 if (!SecondPart.isInvalid())
2169 Diag(Tok, diag::err_expected_semi_for);
2170 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
2171 }
2172
2173 if (Tok.is(tok::semi)) {
2174 ConsumeToken();
2175 }
2176
2177 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
2178 ExprResult Third = ParseExpression();
2179 // FIXME: The C++11 standard doesn't actually say that this is a
2180 // discarded-value expression, but it clearly should be.
2181 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
2182 }
2183 }
2184 // Match the ')'.
2185 T.consumeClose();
2186
2187 // C++ Coroutines [stmt.iter]:
2188 // 'co_await' can only be used for a range-based for statement.
2189 if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
2190 Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
2191 CoawaitLoc = SourceLocation();
2192 }
2193
2194 if (CoawaitLoc.isValid() && getLangOpts().CPlusPlus20)
2195 Diag(CoawaitLoc, diag::warn_deprecated_for_co_await);
2196
2197 // We need to perform most of the semantic analysis for a C++0x for-range
2198 // statememt before parsing the body, in order to be able to deduce the type
2199 // of an auto-typed loop variable.
2200 StmtResult ForRangeStmt;
2201 StmtResult ForEachStmt;
2202
2203 if (ForRangeInfo.ParsedForRangeDecl()) {
2204 ForRangeStmt = Actions.ActOnCXXForRangeStmt(
2205 getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
2206 ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc,
2207 ForRangeInfo.RangeExpr.get(), T.getCloseLocation(), Sema::BFRK_Build,
2208 ForRangeInfo.LifetimeExtendTemps);
2209 } else if (ForEach) {
2210 // Similarly, we need to do the semantic analysis for a for-range
2211 // statement immediately in order to close over temporaries correctly.
2212 ForEachStmt = Actions.ObjC().ActOnObjCForCollectionStmt(
2213 ForLoc, FirstPart.get(), Collection.get(), T.getCloseLocation());
2214 } else {
2215 // In OpenMP loop region loop control variable must be captured and be
2216 // private. Perform analysis of first part (if any).
2217 if (getLangOpts().OpenMP && FirstPart.isUsable()) {
2218 Actions.OpenMP().ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
2219 }
2220 }
2221
2222 // OpenACC Restricts a for-loop inside of certain construct/clause
2223 // combinations, so diagnose that here in OpenACC mode.
2224 SemaOpenACC::LoopInConstructRAII LCR{getActions().OpenACC()};
2225 if (ForRangeInfo.ParsedForRangeDecl())
2226 getActions().OpenACC().ActOnRangeForStmtBegin(ForLoc, ForRangeStmt.get());
2227 else
2229 ForLoc, FirstPart.get(), SecondPart.get().second, ThirdPart.get());
2230
2231 // Set this only right before parsing the body to disallow break/continue in
2232 // the other parts.
2233 getCurScope()->setPrecedingLabel(PrecedingLabel);
2234
2235 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2236 // there is no compound stmt. C90 does not have this clause. We only do this
2237 // if the body isn't a compound statement to avoid push/pop in common cases.
2238 //
2239 // C++ 6.5p2:
2240 // The substatement in an iteration-statement implicitly defines a local scope
2241 // which is entered and exited each time through the loop.
2242 //
2243 // See comments in ParseIfStatement for why we create a scope for
2244 // for-init-statement/condition and a new scope for substatement in C++.
2245 //
2246 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
2247 Tok.is(tok::l_brace));
2248
2249 // The body of the for loop has the same local mangling number as the
2250 // for-init-statement.
2251 // It will only be incremented if the body contains other things that would
2252 // normally increment the mangling number (like a compound statement).
2253 if (C99orCXXorObjC)
2255
2256 MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
2257
2258 // Read the body statement.
2259 StmtResult Body(ParseStatement(TrailingElseLoc));
2260
2261 if (Body.isUsable())
2262 MIChecker.Check();
2263
2264 // Pop the body scope if needed.
2265 InnerScope.Exit();
2266
2267 getActions().OpenACC().ActOnForStmtEnd(ForLoc, Body);
2268
2269 // Leave the for-scope.
2270 ForScope.Exit();
2271
2272 if (Body.isInvalid())
2273 return StmtError();
2274
2275 if (ForEach)
2276 return Actions.ObjC().FinishObjCForCollectionStmt(ForEachStmt.get(),
2277 Body.get());
2278
2279 if (ForRangeInfo.ParsedForRangeDecl())
2280 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
2281
2282 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
2283 SecondPart, ThirdPart, T.getCloseLocation(),
2284 Body.get());
2285}
2286
2287StmtResult Parser::ParseGotoStatement() {
2288 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
2289 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
2290
2291 StmtResult Res;
2292 if (Tok.is(tok::identifier)) {
2293 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
2294 Tok.getLocation());
2295 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
2296 ConsumeToken();
2297 } else if (Tok.is(tok::star)) {
2298 // GNU indirect goto extension.
2299 Diag(Tok, diag::ext_gnu_indirect_goto);
2300 SourceLocation StarLoc = ConsumeToken();
2302 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
2303 SkipUntil(tok::semi, StopBeforeMatch);
2304 return StmtError();
2305 }
2306 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
2307 } else {
2308 Diag(Tok, diag::err_expected) << tok::identifier;
2309 return StmtError();
2310 }
2311
2312 return Res;
2313}
2314
2315StmtResult Parser::ParseBreakOrContinueStatement(bool IsContinue) {
2316 SourceLocation KwLoc = ConsumeToken(); // Eat the keyword.
2317 SourceLocation LabelLoc;
2318 LabelDecl *Target = nullptr;
2319 if (Tok.is(tok::identifier)) {
2320 Target =
2321 Actions.LookupExistingLabel(Tok.getIdentifierInfo(), Tok.getLocation());
2322 LabelLoc = ConsumeToken();
2323 if (!getLangOpts().NamedLoops)
2324 // TODO: Make this a compatibility/extension warning instead once the
2325 // syntax of this feature is finalised.
2326 Diag(LabelLoc, diag::err_c2y_labeled_break_continue) << IsContinue;
2327 if (!Target) {
2328 Diag(LabelLoc, diag::err_break_continue_label_not_found) << IsContinue;
2329 return StmtError();
2330 }
2331 }
2332
2333 if (IsContinue)
2334 return Actions.ActOnContinueStmt(KwLoc, getCurScope(), Target, LabelLoc);
2335 return Actions.ActOnBreakStmt(KwLoc, getCurScope(), Target, LabelLoc);
2336}
2337
2338StmtResult Parser::ParseContinueStatement() {
2339 return ParseBreakOrContinueStatement(/*IsContinue=*/true);
2340}
2341
2342StmtResult Parser::ParseBreakStatement() {
2343 return ParseBreakOrContinueStatement(/*IsContinue=*/false);
2344}
2345
2346StmtResult Parser::ParseReturnStatement() {
2347 assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
2348 "Not a return stmt!");
2349 bool IsCoreturn = Tok.is(tok::kw_co_return);
2350 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
2351
2352 ExprResult R;
2353 if (Tok.isNot(tok::semi)) {
2354 if (!IsCoreturn)
2355 PreferredType.enterReturn(Actions, Tok.getLocation());
2356 // FIXME: Code completion for co_return.
2357 if (Tok.is(tok::code_completion) && !IsCoreturn) {
2358 cutOffParsing();
2359 Actions.CodeCompletion().CodeCompleteExpression(
2360 getCurScope(), PreferredType.get(Tok.getLocation()));
2361 return StmtError();
2362 }
2363
2364 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
2365 R = ParseInitializer();
2366 if (R.isUsable())
2367 Diag(R.get()->getBeginLoc(),
2369 ? diag::warn_cxx98_compat_generalized_initializer_lists
2370 : diag::ext_generalized_initializer_lists)
2371 << R.get()->getSourceRange();
2372 } else
2373 R = ParseExpression();
2374 if (R.isInvalid()) {
2375 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2376 return StmtError();
2377 }
2378 }
2379 if (IsCoreturn)
2380 return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
2381 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
2382}
2383
2384StmtResult Parser::ParseDeferStatement(SourceLocation *TrailingElseLoc) {
2385 assert(Tok.is(tok::kw__Defer));
2386 SourceLocation DeferLoc = ConsumeToken();
2387
2388 Actions.ActOnStartOfDeferStmt(DeferLoc, getCurScope());
2389
2390 llvm::scope_exit OnError([&] { Actions.ActOnDeferStmtError(getCurScope()); });
2391
2392 StmtResult Res = ParseStatement(TrailingElseLoc);
2393 if (!Res.isUsable())
2394 return StmtError();
2395
2396 // The grammar specifically calls for an unlabeled-statement here.
2397 if (auto *L = dyn_cast<LabelStmt>(Res.get())) {
2398 Diag(L->getIdentLoc(), diag::err_defer_ts_labeled_stmt);
2399 return StmtError();
2400 }
2401
2402 OnError.release();
2403 return Actions.ActOnEndOfDeferStmt(Res.get(), getCurScope());
2404}
2405
2406StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
2407 ParsedStmtContext StmtCtx,
2408 SourceLocation *TrailingElseLoc,
2409 ParsedAttributes &Attrs,
2410 LabelDecl *PrecedingLabel) {
2411 // Create temporary attribute list.
2412 ParsedAttributes TempAttrs(AttrFactory);
2413
2414 SourceLocation StartLoc = Tok.getLocation();
2415
2416 // Get loop hints and consume annotated token.
2417 while (Tok.is(tok::annot_pragma_loop_hint)) {
2418 LoopHint Hint;
2419 if (!HandlePragmaLoopHint(Hint))
2420 continue;
2421
2422 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
2423 ArgsUnion(Hint.ValueExpr)};
2424 TempAttrs.addNew(Hint.PragmaNameLoc->getIdentifierInfo(), Hint.Range,
2425 AttributeScopeInfo(), ArgHints, /*numArgs=*/4,
2426 ParsedAttr::Form::Pragma());
2427 }
2428
2429 // Get the next statement.
2430 MaybeParseCXX11Attributes(Attrs);
2431
2432 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2433 StmtResult S = ParseStatementOrDeclarationAfterAttributes(
2434 Stmts, StmtCtx, TrailingElseLoc, Attrs, EmptyDeclSpecAttrs,
2435 PrecedingLabel);
2436
2437 Attrs.takeAllPrependingFrom(TempAttrs);
2438
2439 // Start of attribute range may already be set for some invalid input.
2440 // See PR46336.
2441 if (Attrs.Range.getBegin().isInvalid())
2442 Attrs.Range.setBegin(StartLoc);
2443
2444 return S;
2445}
2446
2447Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2448 assert(Tok.is(tok::l_brace));
2449 SourceLocation LBraceLoc = Tok.getLocation();
2450
2451 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
2452 "parsing function body");
2453
2454 // Save and reset current vtordisp stack if we have entered a C++ method body.
2455 bool IsCXXMethod =
2456 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2457 Sema::PragmaStackSentinelRAII
2458 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2459
2460 // Do not enter a scope for the brace, as the arguments are in the same scope
2461 // (the function body) as the body itself. Instead, just read the statement
2462 // list and put it into a CompoundStmt for safe keeping.
2463 StmtResult FnBody(ParseCompoundStatementBody());
2464
2465 // If the function body could not be parsed, make a bogus compoundstmt.
2466 if (FnBody.isInvalid()) {
2467 Sema::CompoundScopeRAII CompoundScope(Actions);
2468 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, {}, false);
2469 }
2470
2471 BodyScope.Exit();
2472 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2473}
2474
2475Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2476 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2477 SourceLocation TryLoc = ConsumeToken();
2478
2479 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
2480 "parsing function try block");
2481
2482 // Constructor initializer list?
2483 if (Tok.is(tok::colon))
2484 ParseConstructorInitializer(Decl);
2485 else
2486 Actions.ActOnDefaultCtorInitializers(Decl);
2487
2488 // Save and reset current vtordisp stack if we have entered a C++ method body.
2489 bool IsCXXMethod =
2490 getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2491 Sema::PragmaStackSentinelRAII
2492 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2493
2494 SourceLocation LBraceLoc = Tok.getLocation();
2495 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2496 // If we failed to parse the try-catch, we just give the function an empty
2497 // compound statement as the body.
2498 if (FnBody.isInvalid()) {
2499 Sema::CompoundScopeRAII CompoundScope(Actions);
2500 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, {}, false);
2501 }
2502
2503 BodyScope.Exit();
2504 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2505}
2506
2507bool Parser::trySkippingFunctionBody() {
2508 assert(SkipFunctionBodies &&
2509 "Should only be called when SkipFunctionBodies is enabled");
2510 if (!PP.isCodeCompletionEnabled()) {
2511 SkipFunctionBody();
2512 return true;
2513 }
2514
2515 // We're in code-completion mode. Skip parsing for all function bodies unless
2516 // the body contains the code-completion point.
2517 TentativeParsingAction PA(*this);
2518 bool IsTryCatch = Tok.is(tok::kw_try);
2519 CachedTokens Toks;
2520 bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2521 if (llvm::any_of(Toks, [](const Token &Tok) {
2522 return Tok.is(tok::code_completion);
2523 })) {
2524 PA.Revert();
2525 return false;
2526 }
2527 if (ErrorInPrologue) {
2528 PA.Commit();
2530 return true;
2531 }
2532 if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2533 PA.Revert();
2534 return false;
2535 }
2536 while (IsTryCatch && Tok.is(tok::kw_catch)) {
2537 if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2538 !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2539 PA.Revert();
2540 return false;
2541 }
2542 }
2543 PA.Commit();
2544 return true;
2545}
2546
2547StmtResult Parser::ParseCXXTryBlock() {
2548 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2549
2550 SourceLocation TryLoc = ConsumeToken();
2551 return ParseCXXTryBlockCommon(TryLoc);
2552}
2553
2554StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2555 if (Tok.isNot(tok::l_brace))
2556 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2557
2558 StmtResult TryBlock(ParseCompoundStatement(
2559 /*isStmtExpr=*/false,
2562 if (TryBlock.isInvalid())
2563 return TryBlock;
2564
2565 // Borland allows SEH-handlers with 'try'
2566
2567 if ((Tok.is(tok::identifier) &&
2568 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2569 Tok.is(tok::kw___finally)) {
2570 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2571 StmtResult Handler;
2572 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2573 SourceLocation Loc = ConsumeToken();
2574 Handler = ParseSEHExceptBlock(Loc);
2575 }
2576 else {
2577 SourceLocation Loc = ConsumeToken();
2578 Handler = ParseSEHFinallyBlock(Loc);
2579 }
2580 if(Handler.isInvalid())
2581 return Handler;
2582
2583 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2584 TryLoc,
2585 TryBlock.get(),
2586 Handler.get());
2587 }
2588 else {
2589 StmtVector Handlers;
2590
2591 // C++11 attributes can't appear here, despite this context seeming
2592 // statement-like.
2593 DiagnoseAndSkipCXX11Attributes();
2594
2595 if (Tok.isNot(tok::kw_catch))
2596 return StmtError(Diag(Tok, diag::err_expected_catch));
2597 while (Tok.is(tok::kw_catch)) {
2598 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2599 if (!Handler.isInvalid())
2600 Handlers.push_back(Handler.get());
2601 }
2602 // Don't bother creating the full statement if we don't have any usable
2603 // handlers.
2604 if (Handlers.empty())
2605 return StmtError();
2606
2607 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2608 }
2609}
2610
2611StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2612 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2613
2614 SourceLocation CatchLoc = ConsumeToken();
2615
2616 BalancedDelimiterTracker T(*this, tok::l_paren);
2617 if (T.expectAndConsume())
2618 return StmtError();
2619
2620 // C++ 3.3.2p3:
2621 // The name in a catch exception-declaration is local to the handler and
2622 // shall not be redeclared in the outermost block of the handler.
2623 ParseScope CatchScope(
2626
2627 // exception-declaration is equivalent to '...' or a parameter-declaration
2628 // without default arguments.
2629 Decl *ExceptionDecl = nullptr;
2630 if (Tok.isNot(tok::ellipsis)) {
2631 ParsedAttributes Attributes(AttrFactory);
2632 MaybeParseCXX11Attributes(Attributes);
2633
2634 DeclSpec DS(AttrFactory);
2635
2636 if (ParseCXXTypeSpecifierSeq(DS))
2637 return StmtError();
2638
2639 Declarator ExDecl(DS, Attributes, DeclaratorContext::CXXCatch);
2640 ParseDeclarator(ExDecl);
2641 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2642 } else
2643 ConsumeToken();
2644
2645 T.consumeClose();
2646 if (T.getCloseLocation().isInvalid())
2647 return StmtError();
2648
2649 if (Tok.isNot(tok::l_brace))
2650 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2651
2652 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2653 StmtResult Block(ParseCompoundStatement());
2654 if (Block.isInvalid())
2655 return Block;
2656
2657 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2658}
2659
2660void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2661 IfExistsCondition Result;
2662 if (ParseMicrosoftIfExistsCondition(Result))
2663 return;
2664
2665 // Handle dependent statements by parsing the braces as a compound statement.
2666 // This is not the same behavior as Visual C++, which don't treat this as a
2667 // compound statement, but for Clang's type checking we can't have anything
2668 // inside these braces escaping to the surrounding code.
2669 if (Result.Behavior == IfExistsBehavior::Dependent) {
2670 if (!Tok.is(tok::l_brace)) {
2671 Diag(Tok, diag::err_expected) << tok::l_brace;
2672 return;
2673 }
2674
2675 StmtResult Compound = ParseCompoundStatement();
2676 if (Compound.isInvalid())
2677 return;
2678
2679 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2680 Result.IsIfExists,
2681 Result.SS,
2682 Result.Name,
2683 Compound.get());
2684 if (DepResult.isUsable())
2685 Stmts.push_back(DepResult.get());
2686 return;
2687 }
2688
2689 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2690 if (Braces.consumeOpen()) {
2691 Diag(Tok, diag::err_expected) << tok::l_brace;
2692 return;
2693 }
2694
2695 switch (Result.Behavior) {
2697 // Parse the statements below.
2698 break;
2699
2701 llvm_unreachable("Dependent case handled above");
2702
2704 Braces.skipToEnd();
2705 return;
2706 }
2707
2708 // Condition is true, parse the statements.
2709 while (Tok.isNot(tok::r_brace)) {
2710 StmtResult R =
2711 ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
2712 if (R.isUsable())
2713 Stmts.push_back(R.get());
2714 }
2715 Braces.consumeClose();
2716}
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Token Tok
The Token.
FormatToken * Next
The next token in the unwrapped line.
bool is(tok::TokenKind Kind) const
#define SM(sm)
static void DiagnoseLabelFollowedByDecl(Parser &P, const Stmt *SubStmt)
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
This file declares facilities that support code completion.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
Defines the clang::TokenKind enum and support functions.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
This represents one expression.
Definition Expr.h:112
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
IdentifierInfo * getIdentifierInfo() const
Represents the declaration of a label.
Definition Decl.h:524
@ FEM_Source
Use the declared type for fp arithmetic.
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
void takeAllPrependingFrom(ParsedAttributes &Other)
Definition ParsedAttr.h:946
void takeAllAppendingFrom(ParsedAttributes &Other)
Definition ParsedAttr.h:954
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:396
Parser - This implements a parser for the C family of languages.
Definition Parser.h:171
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:88
SourceLocation getEndOfPreviousToken() const
Definition Parser.cpp:1838
Preprocessor & getPreprocessor() const
Definition Parser.h:206
Sema::FullExprArg FullExprArg
Definition Parser.h:3627
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:262
Sema & getActions() const
Definition Parser.h:207
ExprResult ParseCaseExpression(SourceLocation CaseLoc)
SmallVector< Stmt *, 24 > StmtVector
A SmallVector of statements.
Definition Parser.h:7186
friend class ColonProtectionRAIIObject
Definition Parser.h:196
StmtResult ParseOpenACCDirectiveStmt()
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:270
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:219
Scope * getCurScope() const
Definition Parser.h:211
friend class InMessageExpressionRAIIObject
Definition Parser.h:5320
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition Parser.h:495
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
const Token & getCurToken() const
Definition Parser.h:210
SourceLocation MisleadingIndentationElseLoc
The location of the first statement inside an else that might have a missleading indentation.
Definition Parser.h:7191
const LangOptions & getLangOpts() const
Definition Parser.h:204
friend class ParenBraceBracketBalancer
Definition Parser.h:198
ExprResult ParseExpression(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
Simple precedence-based parser for binary/ternary operators.
Definition ParseExpr.cpp:47
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:476
@ StopAtCodeCompletion
Stop at code completion.
Definition Parser.h:477
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:474
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:324
friend class BalancedDelimiterTracker
Definition Parser.h:199
unsigned getNumDirectives() const
Retrieve the number of Directives that have been processed by the Preprocessor.
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
SourceManager & getSourceManager() const
void AddFlags(unsigned Flags)
Sets up the specified scope flags and adjusts the scope state variables accordingly.
Definition Scope.cpp:116
void setPrecedingLabel(LabelDecl *LD)
Definition Scope.h:277
void decrementMSManglingNumber()
Definition Scope.h:379
@ SEHTryScope
This scope corresponds to an SEH try.
Definition Scope.h:125
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition Scope.h:66
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition Scope.h:131
@ SwitchScope
This is a scope that corresponds to a switch statement.
Definition Scope.h:102
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition Scope.h:55
@ CatchScope
This is the scope of a C++ catch statement.
Definition Scope.h:141
@ CompoundStmtScope
This is a compound statement scope.
Definition Scope.h:134
@ FnTryCatchScope
This is the scope for a function-level C++ try or catch scope.
Definition Scope.h:108
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition Scope.h:128
@ TryScope
This is the scope of a C++ try statement.
Definition Scope.h:105
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
@ PCC_ForInit
Code completion occurs at the beginning of the initialization statement (or expression) in a for loop...
@ PCC_Expression
Code completion occurs within an expression.
@ PCC_Statement
Code completion occurs within a statement, which may also be an expression or a declaration.
void ActOnWhileStmt(SourceLocation WhileLoc)
void ActOnDoStmt(SourceLocation DoLoc)
void ActOnRangeForStmtBegin(SourceLocation ForLoc, const Stmt *OldRangeFor, const Stmt *RangeFor)
void ActOnForStmtEnd(SourceLocation ForLoc, StmtResult Body)
void ActOnForStmtBegin(SourceLocation ForLoc, const Stmt *First, const Stmt *Second, const Stmt *Third)
std::pair< VarDecl *, Expr * > get() const
Definition Sema.h:7844
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7864
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7866
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7865
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:924
SemaOpenACC & OpenACC()
Definition Sema.h:1498
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition Sema.h:6728
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6745
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6760
@ BFRK_Build
Initial building of a for-range statement.
Definition Sema.h:11077
static ConditionResult ConditionError()
Definition Sema.h:7850
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
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:195
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:140
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition Token.h:284
bool isOneOf(Ts... Ks) const
Definition Token.h:103
bool isNot(tok::TokenKind K) const
Definition Token.h:109
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition Token.h:129
void setAnnotationValue(void *val)
Definition Token.h:246
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Defines the clang::TargetInfo interface.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
IfStatementKind
In an if statement, this denotes whether the statement is a constexpr or consteval if statement.
Definition Specifiers.h:39
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition ParsedAttr.h:103
@ Error
Annotation has failed and emitted an error.
Definition Parser.h:57
std::pair< FileID, unsigned > FileIDAndOffset
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
@ Skip
Skip the block entirely; this code is never used.
Definition Parser.h:139
@ Parse
Parse the block; this code is always used.
Definition Parser.h:137
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
StmtResult StmtEmpty()
Definition Ownership.h:273
void takeAndConcatenateAttrs(ParsedAttributes &First, ParsedAttributes &&Second)
Consumes the attributes from Second and concatenates them at the end of First.
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1215
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2248
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
SourceRange Range
Definition LoopHint.h:22
IdentifierLoc * OptionLoc
Definition LoopHint.h:30
IdentifierLoc * StateLoc
Definition LoopHint.h:33
Expr * ValueExpr
Definition LoopHint.h:35
IdentifierLoc * PragmaNameLoc
Definition LoopHint.h:26