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