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