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