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