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