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