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