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