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