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