clang API Documentation
00001 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the Statement and Block portions of the Parser 00011 // interface. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "clang/Parse/Parser.h" 00016 #include "RAIIObjectsForParser.h" 00017 #include "clang/AST/ASTContext.h" 00018 #include "clang/Basic/Attributes.h" 00019 #include "clang/Basic/Diagnostic.h" 00020 #include "clang/Basic/PrettyStackTrace.h" 00021 #include "clang/Sema/DeclSpec.h" 00022 #include "clang/Sema/LoopHint.h" 00023 #include "clang/Sema/PrettyDeclStackTrace.h" 00024 #include "clang/Sema/Scope.h" 00025 #include "clang/Sema/TypoCorrection.h" 00026 #include "llvm/ADT/SmallString.h" 00027 using namespace clang; 00028 00029 //===----------------------------------------------------------------------===// 00030 // C99 6.8: Statements and Blocks. 00031 //===----------------------------------------------------------------------===// 00032 00033 /// \brief Parse a standalone statement (for instance, as the body of an 'if', 00034 /// 'while', or 'for'). 00035 StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) { 00036 StmtResult Res; 00037 00038 // We may get back a null statement if we found a #pragma. Keep going until 00039 // we get an actual statement. 00040 do { 00041 StmtVector Stmts; 00042 Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc); 00043 } while (!Res.isInvalid() && !Res.get()); 00044 00045 return Res; 00046 } 00047 00048 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'. 00049 /// StatementOrDeclaration: 00050 /// statement 00051 /// declaration 00052 /// 00053 /// statement: 00054 /// labeled-statement 00055 /// compound-statement 00056 /// expression-statement 00057 /// selection-statement 00058 /// iteration-statement 00059 /// jump-statement 00060 /// [C++] declaration-statement 00061 /// [C++] try-block 00062 /// [MS] seh-try-block 00063 /// [OBC] objc-throw-statement 00064 /// [OBC] objc-try-catch-statement 00065 /// [OBC] objc-synchronized-statement 00066 /// [GNU] asm-statement 00067 /// [OMP] openmp-construct [TODO] 00068 /// 00069 /// labeled-statement: 00070 /// identifier ':' statement 00071 /// 'case' constant-expression ':' statement 00072 /// 'default' ':' statement 00073 /// 00074 /// selection-statement: 00075 /// if-statement 00076 /// switch-statement 00077 /// 00078 /// iteration-statement: 00079 /// while-statement 00080 /// do-statement 00081 /// for-statement 00082 /// 00083 /// expression-statement: 00084 /// expression[opt] ';' 00085 /// 00086 /// jump-statement: 00087 /// 'goto' identifier ';' 00088 /// 'continue' ';' 00089 /// 'break' ';' 00090 /// 'return' expression[opt] ';' 00091 /// [GNU] 'goto' '*' expression ';' 00092 /// 00093 /// [OBC] objc-throw-statement: 00094 /// [OBC] '@' 'throw' expression ';' 00095 /// [OBC] '@' 'throw' ';' 00096 /// 00097 StmtResult 00098 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement, 00099 SourceLocation *TrailingElseLoc) { 00100 00101 ParenBraceBracketBalancer BalancerRAIIObj(*this); 00102 00103 ParsedAttributesWithRange Attrs(AttrFactory); 00104 MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true); 00105 00106 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts, 00107 OnlyStatement, TrailingElseLoc, Attrs); 00108 00109 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) && 00110 "attributes on empty statement"); 00111 00112 if (Attrs.empty() || Res.isInvalid()) 00113 return Res; 00114 00115 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range); 00116 } 00117 00118 namespace { 00119 class StatementFilterCCC : public CorrectionCandidateCallback { 00120 public: 00121 StatementFilterCCC(Token nextTok) : NextToken(nextTok) { 00122 WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) || 00123 nextTok.is(tok::identifier) || nextTok.is(tok::star) || 00124 nextTok.is(tok::amp) || nextTok.is(tok::l_square); 00125 WantExpressionKeywords = nextTok.is(tok::l_paren) || 00126 nextTok.is(tok::identifier) || 00127 nextTok.is(tok::arrow) || nextTok.is(tok::period); 00128 WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) || 00129 nextTok.is(tok::identifier) || 00130 nextTok.is(tok::l_brace); 00131 WantCXXNamedCasts = false; 00132 } 00133 00134 bool ValidateCandidate(const TypoCorrection &candidate) override { 00135 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>()) 00136 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD); 00137 if (NextToken.is(tok::equal)) 00138 return candidate.getCorrectionDeclAs<VarDecl>(); 00139 if (NextToken.is(tok::period) && 00140 candidate.getCorrectionDeclAs<NamespaceDecl>()) 00141 return false; 00142 return CorrectionCandidateCallback::ValidateCandidate(candidate); 00143 } 00144 00145 private: 00146 Token NextToken; 00147 }; 00148 } 00149 00150 StmtResult 00151 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts, 00152 bool OnlyStatement, SourceLocation *TrailingElseLoc, 00153 ParsedAttributesWithRange &Attrs) { 00154 const char *SemiError = nullptr; 00155 StmtResult Res; 00156 00157 // Cases in this switch statement should fall through if the parser expects 00158 // the token to end in a semicolon (in which case SemiError should be set), 00159 // or they directly 'return;' if not. 00160 Retry: 00161 tok::TokenKind Kind = Tok.getKind(); 00162 SourceLocation AtLoc; 00163 switch (Kind) { 00164 case tok::at: // May be a @try or @throw statement 00165 { 00166 ProhibitAttributes(Attrs); // TODO: is it correct? 00167 AtLoc = ConsumeToken(); // consume @ 00168 return ParseObjCAtStatement(AtLoc); 00169 } 00170 00171 case tok::code_completion: 00172 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement); 00173 cutOffParsing(); 00174 return StmtError(); 00175 00176 case tok::identifier: { 00177 Token Next = NextToken(); 00178 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement 00179 // identifier ':' statement 00180 return ParseLabeledStatement(Attrs); 00181 } 00182 00183 // Look up the identifier, and typo-correct it to a keyword if it's not 00184 // found. 00185 if (Next.isNot(tok::coloncolon)) { 00186 // Try to limit which sets of keywords should be included in typo 00187 // correction based on what the next token is. 00188 if (TryAnnotateName(/*IsAddressOfOperand*/ false, 00189 llvm::make_unique<StatementFilterCCC>(Next)) == 00190 ANK_Error) { 00191 // Handle errors here by skipping up to the next semicolon or '}', and 00192 // eat the semicolon if that's what stopped us. 00193 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 00194 if (Tok.is(tok::semi)) 00195 ConsumeToken(); 00196 return StmtError(); 00197 } 00198 00199 // If the identifier was typo-corrected, try again. 00200 if (Tok.isNot(tok::identifier)) 00201 goto Retry; 00202 } 00203 00204 // Fall through 00205 } 00206 00207 default: { 00208 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) { 00209 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 00210 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext, 00211 DeclEnd, Attrs); 00212 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd); 00213 } 00214 00215 if (Tok.is(tok::r_brace)) { 00216 Diag(Tok, diag::err_expected_statement); 00217 return StmtError(); 00218 } 00219 00220 return ParseExprStatement(); 00221 } 00222 00223 case tok::kw_case: // C99 6.8.1: labeled-statement 00224 return ParseCaseStatement(); 00225 case tok::kw_default: // C99 6.8.1: labeled-statement 00226 return ParseDefaultStatement(); 00227 00228 case tok::l_brace: // C99 6.8.2: compound-statement 00229 return ParseCompoundStatement(); 00230 case tok::semi: { // C99 6.8.3p3: expression[opt] ';' 00231 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro(); 00232 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro); 00233 } 00234 00235 case tok::kw_if: // C99 6.8.4.1: if-statement 00236 return ParseIfStatement(TrailingElseLoc); 00237 case tok::kw_switch: // C99 6.8.4.2: switch-statement 00238 return ParseSwitchStatement(TrailingElseLoc); 00239 00240 case tok::kw_while: // C99 6.8.5.1: while-statement 00241 return ParseWhileStatement(TrailingElseLoc); 00242 case tok::kw_do: // C99 6.8.5.2: do-statement 00243 Res = ParseDoStatement(); 00244 SemiError = "do/while"; 00245 break; 00246 case tok::kw_for: // C99 6.8.5.3: for-statement 00247 return ParseForStatement(TrailingElseLoc); 00248 00249 case tok::kw_goto: // C99 6.8.6.1: goto-statement 00250 Res = ParseGotoStatement(); 00251 SemiError = "goto"; 00252 break; 00253 case tok::kw_continue: // C99 6.8.6.2: continue-statement 00254 Res = ParseContinueStatement(); 00255 SemiError = "continue"; 00256 break; 00257 case tok::kw_break: // C99 6.8.6.3: break-statement 00258 Res = ParseBreakStatement(); 00259 SemiError = "break"; 00260 break; 00261 case tok::kw_return: // C99 6.8.6.4: return-statement 00262 Res = ParseReturnStatement(); 00263 SemiError = "return"; 00264 break; 00265 00266 case tok::kw_asm: { 00267 ProhibitAttributes(Attrs); 00268 bool msAsm = false; 00269 Res = ParseAsmStatement(msAsm); 00270 Res = Actions.ActOnFinishFullStmt(Res.get()); 00271 if (msAsm) return Res; 00272 SemiError = "asm"; 00273 break; 00274 } 00275 00276 case tok::kw___if_exists: 00277 case tok::kw___if_not_exists: 00278 ProhibitAttributes(Attrs); 00279 ParseMicrosoftIfExistsStatement(Stmts); 00280 // An __if_exists block is like a compound statement, but it doesn't create 00281 // a new scope. 00282 return StmtEmpty(); 00283 00284 case tok::kw_try: // C++ 15: try-block 00285 return ParseCXXTryBlock(); 00286 00287 case tok::kw___try: 00288 ProhibitAttributes(Attrs); // TODO: is it correct? 00289 return ParseSEHTryBlock(); 00290 00291 case tok::kw___leave: 00292 Res = ParseSEHLeaveStatement(); 00293 SemiError = "__leave"; 00294 break; 00295 00296 case tok::annot_pragma_vis: 00297 ProhibitAttributes(Attrs); 00298 HandlePragmaVisibility(); 00299 return StmtEmpty(); 00300 00301 case tok::annot_pragma_pack: 00302 ProhibitAttributes(Attrs); 00303 HandlePragmaPack(); 00304 return StmtEmpty(); 00305 00306 case tok::annot_pragma_msstruct: 00307 ProhibitAttributes(Attrs); 00308 HandlePragmaMSStruct(); 00309 return StmtEmpty(); 00310 00311 case tok::annot_pragma_align: 00312 ProhibitAttributes(Attrs); 00313 HandlePragmaAlign(); 00314 return StmtEmpty(); 00315 00316 case tok::annot_pragma_weak: 00317 ProhibitAttributes(Attrs); 00318 HandlePragmaWeak(); 00319 return StmtEmpty(); 00320 00321 case tok::annot_pragma_weakalias: 00322 ProhibitAttributes(Attrs); 00323 HandlePragmaWeakAlias(); 00324 return StmtEmpty(); 00325 00326 case tok::annot_pragma_redefine_extname: 00327 ProhibitAttributes(Attrs); 00328 HandlePragmaRedefineExtname(); 00329 return StmtEmpty(); 00330 00331 case tok::annot_pragma_fp_contract: 00332 ProhibitAttributes(Attrs); 00333 Diag(Tok, diag::err_pragma_fp_contract_scope); 00334 ConsumeToken(); 00335 return StmtError(); 00336 00337 case tok::annot_pragma_opencl_extension: 00338 ProhibitAttributes(Attrs); 00339 HandlePragmaOpenCLExtension(); 00340 return StmtEmpty(); 00341 00342 case tok::annot_pragma_captured: 00343 ProhibitAttributes(Attrs); 00344 return HandlePragmaCaptured(); 00345 00346 case tok::annot_pragma_openmp: 00347 ProhibitAttributes(Attrs); 00348 return ParseOpenMPDeclarativeOrExecutableDirective(!OnlyStatement); 00349 00350 case tok::annot_pragma_ms_pointers_to_members: 00351 ProhibitAttributes(Attrs); 00352 HandlePragmaMSPointersToMembers(); 00353 return StmtEmpty(); 00354 00355 case tok::annot_pragma_ms_pragma: 00356 ProhibitAttributes(Attrs); 00357 HandlePragmaMSPragma(); 00358 return StmtEmpty(); 00359 00360 case tok::annot_pragma_loop_hint: 00361 ProhibitAttributes(Attrs); 00362 return ParsePragmaLoopHint(Stmts, OnlyStatement, TrailingElseLoc, Attrs); 00363 } 00364 00365 // If we reached this code, the statement must end in a semicolon. 00366 if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) { 00367 // If the result was valid, then we do want to diagnose this. Use 00368 // ExpectAndConsume to emit the diagnostic, even though we know it won't 00369 // succeed. 00370 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError); 00371 // Skip until we see a } or ;, but don't eat it. 00372 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 00373 } 00374 00375 return Res; 00376 } 00377 00378 /// \brief Parse an expression statement. 00379 StmtResult Parser::ParseExprStatement() { 00380 // If a case keyword is missing, this is where it should be inserted. 00381 Token OldToken = Tok; 00382 00383 // expression[opt] ';' 00384 ExprResult Expr(ParseExpression()); 00385 if (Expr.isInvalid()) { 00386 // If the expression is invalid, skip ahead to the next semicolon or '}'. 00387 // Not doing this opens us up to the possibility of infinite loops if 00388 // ParseExpression does not consume any tokens. 00389 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 00390 if (Tok.is(tok::semi)) 00391 ConsumeToken(); 00392 return Actions.ActOnExprStmtError(); 00393 } 00394 00395 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() && 00396 Actions.CheckCaseExpression(Expr.get())) { 00397 // If a constant expression is followed by a colon inside a switch block, 00398 // suggest a missing case keyword. 00399 Diag(OldToken, diag::err_expected_case_before_expression) 00400 << FixItHint::CreateInsertion(OldToken.getLocation(), "case "); 00401 00402 // Recover parsing as a case statement. 00403 return ParseCaseStatement(/*MissingCase=*/true, Expr); 00404 } 00405 00406 // Otherwise, eat the semicolon. 00407 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 00408 return Actions.ActOnExprStmt(Expr); 00409 } 00410 00411 StmtResult Parser::ParseSEHTryBlock() { 00412 assert(Tok.is(tok::kw___try) && "Expected '__try'"); 00413 SourceLocation Loc = ConsumeToken(); 00414 return ParseSEHTryBlockCommon(Loc); 00415 } 00416 00417 /// ParseSEHTryBlockCommon 00418 /// 00419 /// seh-try-block: 00420 /// '__try' compound-statement seh-handler 00421 /// 00422 /// seh-handler: 00423 /// seh-except-block 00424 /// seh-finally-block 00425 /// 00426 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) { 00427 if(Tok.isNot(tok::l_brace)) 00428 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); 00429 00430 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false, 00431 Scope::DeclScope | Scope::SEHTryScope)); 00432 if(TryBlock.isInvalid()) 00433 return TryBlock; 00434 00435 StmtResult Handler; 00436 if (Tok.is(tok::identifier) && 00437 Tok.getIdentifierInfo() == getSEHExceptKeyword()) { 00438 SourceLocation Loc = ConsumeToken(); 00439 Handler = ParseSEHExceptBlock(Loc); 00440 } else if (Tok.is(tok::kw___finally)) { 00441 SourceLocation Loc = ConsumeToken(); 00442 Handler = ParseSEHFinallyBlock(Loc); 00443 } else { 00444 return StmtError(Diag(Tok,diag::err_seh_expected_handler)); 00445 } 00446 00447 if(Handler.isInvalid()) 00448 return Handler; 00449 00450 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */, 00451 TryLoc, 00452 TryBlock.get(), 00453 Handler.get()); 00454 } 00455 00456 /// ParseSEHExceptBlock - Handle __except 00457 /// 00458 /// seh-except-block: 00459 /// '__except' '(' seh-filter-expression ')' compound-statement 00460 /// 00461 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) { 00462 PoisonIdentifierRAIIObject raii(Ident__exception_code, false), 00463 raii2(Ident___exception_code, false), 00464 raii3(Ident_GetExceptionCode, false); 00465 00466 if (ExpectAndConsume(tok::l_paren)) 00467 return StmtError(); 00468 00469 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope); 00470 00471 if (getLangOpts().Borland) { 00472 Ident__exception_info->setIsPoisoned(false); 00473 Ident___exception_info->setIsPoisoned(false); 00474 Ident_GetExceptionInfo->setIsPoisoned(false); 00475 } 00476 ExprResult FilterExpr(ParseExpression()); 00477 00478 if (getLangOpts().Borland) { 00479 Ident__exception_info->setIsPoisoned(true); 00480 Ident___exception_info->setIsPoisoned(true); 00481 Ident_GetExceptionInfo->setIsPoisoned(true); 00482 } 00483 00484 if(FilterExpr.isInvalid()) 00485 return StmtError(); 00486 00487 if (ExpectAndConsume(tok::r_paren)) 00488 return StmtError(); 00489 00490 StmtResult Block(ParseCompoundStatement()); 00491 00492 if(Block.isInvalid()) 00493 return Block; 00494 00495 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get()); 00496 } 00497 00498 /// ParseSEHFinallyBlock - Handle __finally 00499 /// 00500 /// seh-finally-block: 00501 /// '__finally' compound-statement 00502 /// 00503 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) { 00504 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false), 00505 raii2(Ident___abnormal_termination, false), 00506 raii3(Ident_AbnormalTermination, false); 00507 00508 StmtResult Block(ParseCompoundStatement()); 00509 if(Block.isInvalid()) 00510 return Block; 00511 00512 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.get()); 00513 } 00514 00515 /// Handle __leave 00516 /// 00517 /// seh-leave-statement: 00518 /// '__leave' ';' 00519 /// 00520 StmtResult Parser::ParseSEHLeaveStatement() { 00521 SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'. 00522 return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope()); 00523 } 00524 00525 /// ParseLabeledStatement - We have an identifier and a ':' after it. 00526 /// 00527 /// labeled-statement: 00528 /// identifier ':' statement 00529 /// [GNU] identifier ':' attributes[opt] statement 00530 /// 00531 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) { 00532 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() && 00533 "Not an identifier!"); 00534 00535 Token IdentTok = Tok; // Save the whole token. 00536 ConsumeToken(); // eat the identifier. 00537 00538 assert(Tok.is(tok::colon) && "Not a label!"); 00539 00540 // identifier ':' statement 00541 SourceLocation ColonLoc = ConsumeToken(); 00542 00543 // Read label attributes, if present. 00544 StmtResult SubStmt; 00545 if (Tok.is(tok::kw___attribute)) { 00546 ParsedAttributesWithRange TempAttrs(AttrFactory); 00547 ParseGNUAttributes(TempAttrs); 00548 00549 // In C++, GNU attributes only apply to the label if they are followed by a 00550 // semicolon, to disambiguate label attributes from attributes on a labeled 00551 // declaration. 00552 // 00553 // This doesn't quite match what GCC does; if the attribute list is empty 00554 // and followed by a semicolon, GCC will reject (it appears to parse the 00555 // attributes as part of a statement in that case). That looks like a bug. 00556 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi)) 00557 attrs.takeAllFrom(TempAttrs); 00558 else if (isDeclarationStatement()) { 00559 StmtVector Stmts; 00560 // FIXME: We should do this whether or not we have a declaration 00561 // statement, but that doesn't work correctly (because ProhibitAttributes 00562 // can't handle GNU attributes), so only call it in the one case where 00563 // GNU attributes are allowed. 00564 SubStmt = ParseStatementOrDeclarationAfterAttributes( 00565 Stmts, /*OnlyStmts*/ true, nullptr, TempAttrs); 00566 if (!TempAttrs.empty() && !SubStmt.isInvalid()) 00567 SubStmt = Actions.ProcessStmtAttributes( 00568 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range); 00569 } else { 00570 Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi; 00571 } 00572 } 00573 00574 // If we've not parsed a statement yet, parse one now. 00575 if (!SubStmt.isInvalid() && !SubStmt.isUsable()) 00576 SubStmt = ParseStatement(); 00577 00578 // Broken substmt shouldn't prevent the label from being added to the AST. 00579 if (SubStmt.isInvalid()) 00580 SubStmt = Actions.ActOnNullStmt(ColonLoc); 00581 00582 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(), 00583 IdentTok.getLocation()); 00584 if (AttributeList *Attrs = attrs.getList()) { 00585 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs); 00586 attrs.clear(); 00587 } 00588 00589 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc, 00590 SubStmt.get()); 00591 } 00592 00593 /// ParseCaseStatement 00594 /// labeled-statement: 00595 /// 'case' constant-expression ':' statement 00596 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement 00597 /// 00598 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) { 00599 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!"); 00600 00601 // It is very very common for code to contain many case statements recursively 00602 // nested, as in (but usually without indentation): 00603 // case 1: 00604 // case 2: 00605 // case 3: 00606 // case 4: 00607 // case 5: etc. 00608 // 00609 // Parsing this naively works, but is both inefficient and can cause us to run 00610 // out of stack space in our recursive descent parser. As a special case, 00611 // flatten this recursion into an iterative loop. This is complex and gross, 00612 // but all the grossness is constrained to ParseCaseStatement (and some 00613 // weirdness in the actions), so this is just local grossness :). 00614 00615 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the 00616 // example above. 00617 StmtResult TopLevelCase(true); 00618 00619 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which 00620 // gets updated each time a new case is parsed, and whose body is unset so 00621 // far. When parsing 'case 4', this is the 'case 3' node. 00622 Stmt *DeepestParsedCaseStmt = nullptr; 00623 00624 // While we have case statements, eat and stack them. 00625 SourceLocation ColonLoc; 00626 do { 00627 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() : 00628 ConsumeToken(); // eat the 'case'. 00629 ColonLoc = SourceLocation(); 00630 00631 if (Tok.is(tok::code_completion)) { 00632 Actions.CodeCompleteCase(getCurScope()); 00633 cutOffParsing(); 00634 return StmtError(); 00635 } 00636 00637 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'. 00638 /// Disable this form of error recovery while we're parsing the case 00639 /// expression. 00640 ColonProtectionRAIIObject ColonProtection(*this); 00641 00642 ExprResult LHS; 00643 if (!MissingCase) { 00644 LHS = ParseConstantExpression(); 00645 if (LHS.isInvalid()) { 00646 // If constant-expression is parsed unsuccessfully, recover by skipping 00647 // current case statement (moving to the colon that ends it). 00648 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) { 00649 TryConsumeToken(tok::colon, ColonLoc); 00650 continue; 00651 } 00652 return StmtError(); 00653 } 00654 } else { 00655 LHS = Expr; 00656 MissingCase = false; 00657 } 00658 00659 // GNU case range extension. 00660 SourceLocation DotDotDotLoc; 00661 ExprResult RHS; 00662 if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) { 00663 Diag(DotDotDotLoc, diag::ext_gnu_case_range); 00664 RHS = ParseConstantExpression(); 00665 if (RHS.isInvalid()) { 00666 if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) { 00667 TryConsumeToken(tok::colon, ColonLoc); 00668 continue; 00669 } 00670 return StmtError(); 00671 } 00672 } 00673 00674 ColonProtection.restore(); 00675 00676 if (TryConsumeToken(tok::colon, ColonLoc)) { 00677 } else if (TryConsumeToken(tok::semi, ColonLoc) || 00678 TryConsumeToken(tok::coloncolon, ColonLoc)) { 00679 // Treat "case blah;" or "case blah::" as a typo for "case blah:". 00680 Diag(ColonLoc, diag::err_expected_after) 00681 << "'case'" << tok::colon 00682 << FixItHint::CreateReplacement(ColonLoc, ":"); 00683 } else { 00684 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation); 00685 Diag(ExpectedLoc, diag::err_expected_after) 00686 << "'case'" << tok::colon 00687 << FixItHint::CreateInsertion(ExpectedLoc, ":"); 00688 ColonLoc = ExpectedLoc; 00689 } 00690 00691 StmtResult Case = 00692 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc, 00693 RHS.get(), ColonLoc); 00694 00695 // If we had a sema error parsing this case, then just ignore it and 00696 // continue parsing the sub-stmt. 00697 if (Case.isInvalid()) { 00698 if (TopLevelCase.isInvalid()) // No parsed case stmts. 00699 return ParseStatement(); 00700 // Otherwise, just don't add it as a nested case. 00701 } else { 00702 // If this is the first case statement we parsed, it becomes TopLevelCase. 00703 // Otherwise we link it into the current chain. 00704 Stmt *NextDeepest = Case.get(); 00705 if (TopLevelCase.isInvalid()) 00706 TopLevelCase = Case; 00707 else 00708 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get()); 00709 DeepestParsedCaseStmt = NextDeepest; 00710 } 00711 00712 // Handle all case statements. 00713 } while (Tok.is(tok::kw_case)); 00714 00715 // If we found a non-case statement, start by parsing it. 00716 StmtResult SubStmt; 00717 00718 if (Tok.isNot(tok::r_brace)) { 00719 SubStmt = ParseStatement(); 00720 } else { 00721 // Nicely diagnose the common error "switch (X) { case 4: }", which is 00722 // not valid. If ColonLoc doesn't point to a valid text location, there was 00723 // another parsing error, so avoid producing extra diagnostics. 00724 if (ColonLoc.isValid()) { 00725 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc); 00726 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement) 00727 << FixItHint::CreateInsertion(AfterColonLoc, " ;"); 00728 } 00729 SubStmt = StmtError(); 00730 } 00731 00732 // Install the body into the most deeply-nested case. 00733 if (DeepestParsedCaseStmt) { 00734 // Broken sub-stmt shouldn't prevent forming the case statement properly. 00735 if (SubStmt.isInvalid()) 00736 SubStmt = Actions.ActOnNullStmt(SourceLocation()); 00737 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get()); 00738 } 00739 00740 // Return the top level parsed statement tree. 00741 return TopLevelCase; 00742 } 00743 00744 /// ParseDefaultStatement 00745 /// labeled-statement: 00746 /// 'default' ':' statement 00747 /// Note that this does not parse the 'statement' at the end. 00748 /// 00749 StmtResult Parser::ParseDefaultStatement() { 00750 assert(Tok.is(tok::kw_default) && "Not a default stmt!"); 00751 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'. 00752 00753 SourceLocation ColonLoc; 00754 if (TryConsumeToken(tok::colon, ColonLoc)) { 00755 } else if (TryConsumeToken(tok::semi, ColonLoc)) { 00756 // Treat "default;" as a typo for "default:". 00757 Diag(ColonLoc, diag::err_expected_after) 00758 << "'default'" << tok::colon 00759 << FixItHint::CreateReplacement(ColonLoc, ":"); 00760 } else { 00761 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation); 00762 Diag(ExpectedLoc, diag::err_expected_after) 00763 << "'default'" << tok::colon 00764 << FixItHint::CreateInsertion(ExpectedLoc, ":"); 00765 ColonLoc = ExpectedLoc; 00766 } 00767 00768 StmtResult SubStmt; 00769 00770 if (Tok.isNot(tok::r_brace)) { 00771 SubStmt = ParseStatement(); 00772 } else { 00773 // Diagnose the common error "switch (X) {... default: }", which is 00774 // not valid. 00775 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc); 00776 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement) 00777 << FixItHint::CreateInsertion(AfterColonLoc, " ;"); 00778 SubStmt = true; 00779 } 00780 00781 // Broken sub-stmt shouldn't prevent forming the case statement properly. 00782 if (SubStmt.isInvalid()) 00783 SubStmt = Actions.ActOnNullStmt(ColonLoc); 00784 00785 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc, 00786 SubStmt.get(), getCurScope()); 00787 } 00788 00789 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) { 00790 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope); 00791 } 00792 00793 /// ParseCompoundStatement - Parse a "{}" block. 00794 /// 00795 /// compound-statement: [C99 6.8.2] 00796 /// { block-item-list[opt] } 00797 /// [GNU] { label-declarations block-item-list } [TODO] 00798 /// 00799 /// block-item-list: 00800 /// block-item 00801 /// block-item-list block-item 00802 /// 00803 /// block-item: 00804 /// declaration 00805 /// [GNU] '__extension__' declaration 00806 /// statement 00807 /// 00808 /// [GNU] label-declarations: 00809 /// [GNU] label-declaration 00810 /// [GNU] label-declarations label-declaration 00811 /// 00812 /// [GNU] label-declaration: 00813 /// [GNU] '__label__' identifier-list ';' 00814 /// 00815 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr, 00816 unsigned ScopeFlags) { 00817 assert(Tok.is(tok::l_brace) && "Not a compount stmt!"); 00818 00819 // Enter a scope to hold everything within the compound stmt. Compound 00820 // statements can always hold declarations. 00821 ParseScope CompoundScope(this, ScopeFlags); 00822 00823 // Parse the statements in the body. 00824 return ParseCompoundStatementBody(isStmtExpr); 00825 } 00826 00827 /// Parse any pragmas at the start of the compound expression. We handle these 00828 /// separately since some pragmas (FP_CONTRACT) must appear before any C 00829 /// statement in the compound, but may be intermingled with other pragmas. 00830 void Parser::ParseCompoundStatementLeadingPragmas() { 00831 bool checkForPragmas = true; 00832 while (checkForPragmas) { 00833 switch (Tok.getKind()) { 00834 case tok::annot_pragma_vis: 00835 HandlePragmaVisibility(); 00836 break; 00837 case tok::annot_pragma_pack: 00838 HandlePragmaPack(); 00839 break; 00840 case tok::annot_pragma_msstruct: 00841 HandlePragmaMSStruct(); 00842 break; 00843 case tok::annot_pragma_align: 00844 HandlePragmaAlign(); 00845 break; 00846 case tok::annot_pragma_weak: 00847 HandlePragmaWeak(); 00848 break; 00849 case tok::annot_pragma_weakalias: 00850 HandlePragmaWeakAlias(); 00851 break; 00852 case tok::annot_pragma_redefine_extname: 00853 HandlePragmaRedefineExtname(); 00854 break; 00855 case tok::annot_pragma_opencl_extension: 00856 HandlePragmaOpenCLExtension(); 00857 break; 00858 case tok::annot_pragma_fp_contract: 00859 HandlePragmaFPContract(); 00860 break; 00861 case tok::annot_pragma_ms_pointers_to_members: 00862 HandlePragmaMSPointersToMembers(); 00863 break; 00864 case tok::annot_pragma_ms_pragma: 00865 HandlePragmaMSPragma(); 00866 break; 00867 default: 00868 checkForPragmas = false; 00869 break; 00870 } 00871 } 00872 00873 } 00874 00875 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the 00876 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and 00877 /// consume the '}' at the end of the block. It does not manipulate the scope 00878 /// stack. 00879 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) { 00880 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), 00881 Tok.getLocation(), 00882 "in compound statement ('{}')"); 00883 00884 // Record the state of the FP_CONTRACT pragma, restore on leaving the 00885 // compound statement. 00886 Sema::FPContractStateRAII SaveFPContractState(Actions); 00887 00888 InMessageExpressionRAIIObject InMessage(*this, false); 00889 BalancedDelimiterTracker T(*this, tok::l_brace); 00890 if (T.consumeOpen()) 00891 return StmtError(); 00892 00893 Sema::CompoundScopeRAII CompoundScope(Actions); 00894 00895 // Parse any pragmas at the beginning of the compound statement. 00896 ParseCompoundStatementLeadingPragmas(); 00897 00898 StmtVector Stmts; 00899 00900 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are 00901 // only allowed at the start of a compound stmt regardless of the language. 00902 while (Tok.is(tok::kw___label__)) { 00903 SourceLocation LabelLoc = ConsumeToken(); 00904 00905 SmallVector<Decl *, 8> DeclsInGroup; 00906 while (1) { 00907 if (Tok.isNot(tok::identifier)) { 00908 Diag(Tok, diag::err_expected) << tok::identifier; 00909 break; 00910 } 00911 00912 IdentifierInfo *II = Tok.getIdentifierInfo(); 00913 SourceLocation IdLoc = ConsumeToken(); 00914 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc)); 00915 00916 if (!TryConsumeToken(tok::comma)) 00917 break; 00918 } 00919 00920 DeclSpec DS(AttrFactory); 00921 DeclGroupPtrTy Res = 00922 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); 00923 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation()); 00924 00925 ExpectAndConsumeSemi(diag::err_expected_semi_declaration); 00926 if (R.isUsable()) 00927 Stmts.push_back(R.get()); 00928 } 00929 00930 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 00931 if (Tok.is(tok::annot_pragma_unused)) { 00932 HandlePragmaUnused(); 00933 continue; 00934 } 00935 00936 StmtResult R; 00937 if (Tok.isNot(tok::kw___extension__)) { 00938 R = ParseStatementOrDeclaration(Stmts, false); 00939 } else { 00940 // __extension__ can start declarations and it can also be a unary 00941 // operator for expressions. Consume multiple __extension__ markers here 00942 // until we can determine which is which. 00943 // FIXME: This loses extension expressions in the AST! 00944 SourceLocation ExtLoc = ConsumeToken(); 00945 while (Tok.is(tok::kw___extension__)) 00946 ConsumeToken(); 00947 00948 ParsedAttributesWithRange attrs(AttrFactory); 00949 MaybeParseCXX11Attributes(attrs, nullptr, 00950 /*MightBeObjCMessageSend*/ true); 00951 00952 // If this is the start of a declaration, parse it as such. 00953 if (isDeclarationStatement()) { 00954 // __extension__ silences extension warnings in the subdeclaration. 00955 // FIXME: Save the __extension__ on the decl as a node somehow? 00956 ExtensionRAIIObject O(Diags); 00957 00958 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 00959 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd, 00960 attrs); 00961 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd); 00962 } else { 00963 // Otherwise this was a unary __extension__ marker. 00964 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc)); 00965 00966 if (Res.isInvalid()) { 00967 SkipUntil(tok::semi); 00968 continue; 00969 } 00970 00971 // FIXME: Use attributes? 00972 // Eat the semicolon at the end of stmt and convert the expr into a 00973 // statement. 00974 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 00975 R = Actions.ActOnExprStmt(Res); 00976 } 00977 } 00978 00979 if (R.isUsable()) 00980 Stmts.push_back(R.get()); 00981 } 00982 00983 SourceLocation CloseLoc = Tok.getLocation(); 00984 00985 // We broke out of the while loop because we found a '}' or EOF. 00986 if (!T.consumeClose()) 00987 // Recover by creating a compound statement with what we parsed so far, 00988 // instead of dropping everything and returning StmtError(); 00989 CloseLoc = T.getCloseLocation(); 00990 00991 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc, 00992 Stmts, isStmtExpr); 00993 } 00994 00995 /// ParseParenExprOrCondition: 00996 /// [C ] '(' expression ')' 00997 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true] 00998 /// 00999 /// This function parses and performs error recovery on the specified condition 01000 /// or expression (depending on whether we're in C++ or C mode). This function 01001 /// goes out of its way to recover well. It returns true if there was a parser 01002 /// error (the right paren couldn't be found), which indicates that the caller 01003 /// should try to recover harder. It returns false if the condition is 01004 /// successfully parsed. Note that a successful parse can still have semantic 01005 /// errors in the condition. 01006 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult, 01007 Decl *&DeclResult, 01008 SourceLocation Loc, 01009 bool ConvertToBoolean) { 01010 BalancedDelimiterTracker T(*this, tok::l_paren); 01011 T.consumeOpen(); 01012 01013 if (getLangOpts().CPlusPlus) 01014 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean); 01015 else { 01016 ExprResult = ParseExpression(); 01017 DeclResult = nullptr; 01018 01019 // If required, convert to a boolean value. 01020 if (!ExprResult.isInvalid() && ConvertToBoolean) 01021 ExprResult 01022 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get()); 01023 } 01024 01025 // If the parser was confused by the condition and we don't have a ')', try to 01026 // recover by skipping ahead to a semi and bailing out. If condexp is 01027 // semantically invalid but we have well formed code, keep going. 01028 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) { 01029 SkipUntil(tok::semi); 01030 // Skipping may have stopped if it found the containing ')'. If so, we can 01031 // continue parsing the if statement. 01032 if (Tok.isNot(tok::r_paren)) 01033 return true; 01034 } 01035 01036 // Otherwise the condition is valid or the rparen is present. 01037 T.consumeClose(); 01038 01039 // Check for extraneous ')'s to catch things like "if (foo())) {". We know 01040 // that all callers are looking for a statement after the condition, so ")" 01041 // isn't valid. 01042 while (Tok.is(tok::r_paren)) { 01043 Diag(Tok, diag::err_extraneous_rparen_in_condition) 01044 << FixItHint::CreateRemoval(Tok.getLocation()); 01045 ConsumeParen(); 01046 } 01047 01048 return false; 01049 } 01050 01051 01052 /// ParseIfStatement 01053 /// if-statement: [C99 6.8.4.1] 01054 /// 'if' '(' expression ')' statement 01055 /// 'if' '(' expression ')' statement 'else' statement 01056 /// [C++] 'if' '(' condition ')' statement 01057 /// [C++] 'if' '(' condition ')' statement 'else' statement 01058 /// 01059 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) { 01060 assert(Tok.is(tok::kw_if) && "Not an if stmt!"); 01061 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'. 01062 01063 if (Tok.isNot(tok::l_paren)) { 01064 Diag(Tok, diag::err_expected_lparen_after) << "if"; 01065 SkipUntil(tok::semi); 01066 return StmtError(); 01067 } 01068 01069 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 01070 01071 // C99 6.8.4p3 - In C99, the if statement is a block. This is not 01072 // the case for C90. 01073 // 01074 // C++ 6.4p3: 01075 // A name introduced by a declaration in a condition is in scope from its 01076 // point of declaration until the end of the substatements controlled by the 01077 // condition. 01078 // C++ 3.3.2p4: 01079 // Names declared in the for-init-statement, and in the condition of if, 01080 // while, for, and switch statements are local to the if, while, for, or 01081 // switch statement (including the controlled statement). 01082 // 01083 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX); 01084 01085 // Parse the condition. 01086 ExprResult CondExp; 01087 Decl *CondVar = nullptr; 01088 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true)) 01089 return StmtError(); 01090 01091 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc)); 01092 01093 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if 01094 // there is no compound stmt. C90 does not have this clause. We only do this 01095 // if the body isn't a compound statement to avoid push/pop in common cases. 01096 // 01097 // C++ 6.4p1: 01098 // The substatement in a selection-statement (each substatement, in the else 01099 // form of the if statement) implicitly defines a local scope. 01100 // 01101 // For C++ we create a scope for the condition and a new scope for 01102 // substatements because: 01103 // -When the 'then' scope exits, we want the condition declaration to still be 01104 // active for the 'else' scope too. 01105 // -Sema will detect name clashes by considering declarations of a 01106 // 'ControlScope' as part of its direct subscope. 01107 // -If we wanted the condition and substatement to be in the same scope, we 01108 // would have to notify ParseStatement not to create a new scope. It's 01109 // simpler to let it create a new scope. 01110 // 01111 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); 01112 01113 // Read the 'then' stmt. 01114 SourceLocation ThenStmtLoc = Tok.getLocation(); 01115 01116 SourceLocation InnerStatementTrailingElseLoc; 01117 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc)); 01118 01119 // Pop the 'if' scope if needed. 01120 InnerScope.Exit(); 01121 01122 // If it has an else, parse it. 01123 SourceLocation ElseLoc; 01124 SourceLocation ElseStmtLoc; 01125 StmtResult ElseStmt; 01126 01127 if (Tok.is(tok::kw_else)) { 01128 if (TrailingElseLoc) 01129 *TrailingElseLoc = Tok.getLocation(); 01130 01131 ElseLoc = ConsumeToken(); 01132 ElseStmtLoc = Tok.getLocation(); 01133 01134 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if 01135 // there is no compound stmt. C90 does not have this clause. We only do 01136 // this if the body isn't a compound statement to avoid push/pop in common 01137 // cases. 01138 // 01139 // C++ 6.4p1: 01140 // The substatement in a selection-statement (each substatement, in the else 01141 // form of the if statement) implicitly defines a local scope. 01142 // 01143 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); 01144 01145 ElseStmt = ParseStatement(); 01146 01147 // Pop the 'else' scope if needed. 01148 InnerScope.Exit(); 01149 } else if (Tok.is(tok::code_completion)) { 01150 Actions.CodeCompleteAfterIf(getCurScope()); 01151 cutOffParsing(); 01152 return StmtError(); 01153 } else if (InnerStatementTrailingElseLoc.isValid()) { 01154 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else); 01155 } 01156 01157 IfScope.Exit(); 01158 01159 // If the then or else stmt is invalid and the other is valid (and present), 01160 // make turn the invalid one into a null stmt to avoid dropping the other 01161 // part. If both are invalid, return error. 01162 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) || 01163 (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) || 01164 (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) { 01165 // Both invalid, or one is invalid and other is non-present: return error. 01166 return StmtError(); 01167 } 01168 01169 // Now if either are invalid, replace with a ';'. 01170 if (ThenStmt.isInvalid()) 01171 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc); 01172 if (ElseStmt.isInvalid()) 01173 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc); 01174 01175 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(), 01176 ElseLoc, ElseStmt.get()); 01177 } 01178 01179 /// ParseSwitchStatement 01180 /// switch-statement: 01181 /// 'switch' '(' expression ')' statement 01182 /// [C++] 'switch' '(' condition ')' statement 01183 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) { 01184 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!"); 01185 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'. 01186 01187 if (Tok.isNot(tok::l_paren)) { 01188 Diag(Tok, diag::err_expected_lparen_after) << "switch"; 01189 SkipUntil(tok::semi); 01190 return StmtError(); 01191 } 01192 01193 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 01194 01195 // C99 6.8.4p3 - In C99, the switch statement is a block. This is 01196 // not the case for C90. Start the switch scope. 01197 // 01198 // C++ 6.4p3: 01199 // A name introduced by a declaration in a condition is in scope from its 01200 // point of declaration until the end of the substatements controlled by the 01201 // condition. 01202 // C++ 3.3.2p4: 01203 // Names declared in the for-init-statement, and in the condition of if, 01204 // while, for, and switch statements are local to the if, while, for, or 01205 // switch statement (including the controlled statement). 01206 // 01207 unsigned ScopeFlags = Scope::SwitchScope; 01208 if (C99orCXX) 01209 ScopeFlags |= Scope::DeclScope | Scope::ControlScope; 01210 ParseScope SwitchScope(this, ScopeFlags); 01211 01212 // Parse the condition. 01213 ExprResult Cond; 01214 Decl *CondVar = nullptr; 01215 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false)) 01216 return StmtError(); 01217 01218 StmtResult Switch 01219 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar); 01220 01221 if (Switch.isInvalid()) { 01222 // Skip the switch body. 01223 // FIXME: This is not optimal recovery, but parsing the body is more 01224 // dangerous due to the presence of case and default statements, which 01225 // will have no place to connect back with the switch. 01226 if (Tok.is(tok::l_brace)) { 01227 ConsumeBrace(); 01228 SkipUntil(tok::r_brace); 01229 } else 01230 SkipUntil(tok::semi); 01231 return Switch; 01232 } 01233 01234 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if 01235 // there is no compound stmt. C90 does not have this clause. We only do this 01236 // if the body isn't a compound statement to avoid push/pop in common cases. 01237 // 01238 // C++ 6.4p1: 01239 // The substatement in a selection-statement (each substatement, in the else 01240 // form of the if statement) implicitly defines a local scope. 01241 // 01242 // See comments in ParseIfStatement for why we create a scope for the 01243 // condition and a new scope for substatement in C++. 01244 // 01245 getCurScope()->AddFlags(Scope::BreakScope); 01246 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); 01247 01248 // We have incremented the mangling number for the SwitchScope and the 01249 // InnerScope, which is one too many. 01250 if (C99orCXX) 01251 getCurScope()->decrementMSLocalManglingNumber(); 01252 01253 // Read the body statement. 01254 StmtResult Body(ParseStatement(TrailingElseLoc)); 01255 01256 // Pop the scopes. 01257 InnerScope.Exit(); 01258 SwitchScope.Exit(); 01259 01260 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get()); 01261 } 01262 01263 /// ParseWhileStatement 01264 /// while-statement: [C99 6.8.5.1] 01265 /// 'while' '(' expression ')' statement 01266 /// [C++] 'while' '(' condition ')' statement 01267 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) { 01268 assert(Tok.is(tok::kw_while) && "Not a while stmt!"); 01269 SourceLocation WhileLoc = Tok.getLocation(); 01270 ConsumeToken(); // eat the 'while'. 01271 01272 if (Tok.isNot(tok::l_paren)) { 01273 Diag(Tok, diag::err_expected_lparen_after) << "while"; 01274 SkipUntil(tok::semi); 01275 return StmtError(); 01276 } 01277 01278 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 01279 01280 // C99 6.8.5p5 - In C99, the while statement is a block. This is not 01281 // the case for C90. Start the loop scope. 01282 // 01283 // C++ 6.4p3: 01284 // A name introduced by a declaration in a condition is in scope from its 01285 // point of declaration until the end of the substatements controlled by the 01286 // condition. 01287 // C++ 3.3.2p4: 01288 // Names declared in the for-init-statement, and in the condition of if, 01289 // while, for, and switch statements are local to the if, while, for, or 01290 // switch statement (including the controlled statement). 01291 // 01292 unsigned ScopeFlags; 01293 if (C99orCXX) 01294 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | 01295 Scope::DeclScope | Scope::ControlScope; 01296 else 01297 ScopeFlags = Scope::BreakScope | Scope::ContinueScope; 01298 ParseScope WhileScope(this, ScopeFlags); 01299 01300 // Parse the condition. 01301 ExprResult Cond; 01302 Decl *CondVar = nullptr; 01303 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true)) 01304 return StmtError(); 01305 01306 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc)); 01307 01308 // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if 01309 // there is no compound stmt. C90 does not have this clause. We only do this 01310 // if the body isn't a compound statement to avoid push/pop in common cases. 01311 // 01312 // C++ 6.5p2: 01313 // The substatement in an iteration-statement implicitly defines a local scope 01314 // which is entered and exited each time through the loop. 01315 // 01316 // See comments in ParseIfStatement for why we create a scope for the 01317 // condition and a new scope for substatement in C++. 01318 // 01319 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); 01320 01321 // Read the body statement. 01322 StmtResult Body(ParseStatement(TrailingElseLoc)); 01323 01324 // Pop the body scope if needed. 01325 InnerScope.Exit(); 01326 WhileScope.Exit(); 01327 01328 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid()) 01329 return StmtError(); 01330 01331 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get()); 01332 } 01333 01334 /// ParseDoStatement 01335 /// do-statement: [C99 6.8.5.2] 01336 /// 'do' statement 'while' '(' expression ')' ';' 01337 /// Note: this lets the caller parse the end ';'. 01338 StmtResult Parser::ParseDoStatement() { 01339 assert(Tok.is(tok::kw_do) && "Not a do stmt!"); 01340 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'. 01341 01342 // C99 6.8.5p5 - In C99, the do statement is a block. This is not 01343 // the case for C90. Start the loop scope. 01344 unsigned ScopeFlags; 01345 if (getLangOpts().C99) 01346 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope; 01347 else 01348 ScopeFlags = Scope::BreakScope | Scope::ContinueScope; 01349 01350 ParseScope DoScope(this, ScopeFlags); 01351 01352 // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if 01353 // there is no compound stmt. C90 does not have this clause. We only do this 01354 // if the body isn't a compound statement to avoid push/pop in common cases. 01355 // 01356 // C++ 6.5p2: 01357 // The substatement in an iteration-statement implicitly defines a local scope 01358 // which is entered and exited each time through the loop. 01359 // 01360 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 01361 ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); 01362 01363 // Read the body statement. 01364 StmtResult Body(ParseStatement()); 01365 01366 // Pop the body scope if needed. 01367 InnerScope.Exit(); 01368 01369 if (Tok.isNot(tok::kw_while)) { 01370 if (!Body.isInvalid()) { 01371 Diag(Tok, diag::err_expected_while); 01372 Diag(DoLoc, diag::note_matching) << "'do'"; 01373 SkipUntil(tok::semi, StopBeforeMatch); 01374 } 01375 return StmtError(); 01376 } 01377 SourceLocation WhileLoc = ConsumeToken(); 01378 01379 if (Tok.isNot(tok::l_paren)) { 01380 Diag(Tok, diag::err_expected_lparen_after) << "do/while"; 01381 SkipUntil(tok::semi, StopBeforeMatch); 01382 return StmtError(); 01383 } 01384 01385 // Parse the parenthesized expression. 01386 BalancedDelimiterTracker T(*this, tok::l_paren); 01387 T.consumeOpen(); 01388 01389 // A do-while expression is not a condition, so can't have attributes. 01390 DiagnoseAndSkipCXX11Attributes(); 01391 01392 ExprResult Cond = ParseExpression(); 01393 T.consumeClose(); 01394 DoScope.Exit(); 01395 01396 if (Cond.isInvalid() || Body.isInvalid()) 01397 return StmtError(); 01398 01399 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(), 01400 Cond.get(), T.getCloseLocation()); 01401 } 01402 01403 bool Parser::isForRangeIdentifier() { 01404 assert(Tok.is(tok::identifier)); 01405 01406 const Token &Next = NextToken(); 01407 if (Next.is(tok::colon)) 01408 return true; 01409 01410 if (Next.is(tok::l_square) || Next.is(tok::kw_alignas)) { 01411 TentativeParsingAction PA(*this); 01412 ConsumeToken(); 01413 SkipCXX11Attributes(); 01414 bool Result = Tok.is(tok::colon); 01415 PA.Revert(); 01416 return Result; 01417 } 01418 01419 return false; 01420 } 01421 01422 /// ParseForStatement 01423 /// for-statement: [C99 6.8.5.3] 01424 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement 01425 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement 01426 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')' 01427 /// [C++] statement 01428 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement 01429 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement 01430 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement 01431 /// 01432 /// [C++] for-init-statement: 01433 /// [C++] expression-statement 01434 /// [C++] simple-declaration 01435 /// 01436 /// [C++0x] for-range-declaration: 01437 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator 01438 /// [C++0x] for-range-initializer: 01439 /// [C++0x] expression 01440 /// [C++0x] braced-init-list [TODO] 01441 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) { 01442 assert(Tok.is(tok::kw_for) && "Not a for stmt!"); 01443 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'. 01444 01445 if (Tok.isNot(tok::l_paren)) { 01446 Diag(Tok, diag::err_expected_lparen_after) << "for"; 01447 SkipUntil(tok::semi); 01448 return StmtError(); 01449 } 01450 01451 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus || 01452 getLangOpts().ObjC1; 01453 01454 // C99 6.8.5p5 - In C99, the for statement is a block. This is not 01455 // the case for C90. Start the loop scope. 01456 // 01457 // C++ 6.4p3: 01458 // A name introduced by a declaration in a condition is in scope from its 01459 // point of declaration until the end of the substatements controlled by the 01460 // condition. 01461 // C++ 3.3.2p4: 01462 // Names declared in the for-init-statement, and in the condition of if, 01463 // while, for, and switch statements are local to the if, while, for, or 01464 // switch statement (including the controlled statement). 01465 // C++ 6.5.3p1: 01466 // Names declared in the for-init-statement are in the same declarative-region 01467 // as those declared in the condition. 01468 // 01469 unsigned ScopeFlags = 0; 01470 if (C99orCXXorObjC) 01471 ScopeFlags = Scope::DeclScope | Scope::ControlScope; 01472 01473 ParseScope ForScope(this, ScopeFlags); 01474 01475 BalancedDelimiterTracker T(*this, tok::l_paren); 01476 T.consumeOpen(); 01477 01478 ExprResult Value; 01479 01480 bool ForEach = false, ForRange = false; 01481 StmtResult FirstPart; 01482 bool SecondPartIsInvalid = false; 01483 FullExprArg SecondPart(Actions); 01484 ExprResult Collection; 01485 ForRangeInit ForRangeInit; 01486 FullExprArg ThirdPart(Actions); 01487 Decl *SecondVar = nullptr; 01488 01489 if (Tok.is(tok::code_completion)) { 01490 Actions.CodeCompleteOrdinaryName(getCurScope(), 01491 C99orCXXorObjC? Sema::PCC_ForInit 01492 : Sema::PCC_Expression); 01493 cutOffParsing(); 01494 return StmtError(); 01495 } 01496 01497 ParsedAttributesWithRange attrs(AttrFactory); 01498 MaybeParseCXX11Attributes(attrs); 01499 01500 // Parse the first part of the for specifier. 01501 if (Tok.is(tok::semi)) { // for (; 01502 ProhibitAttributes(attrs); 01503 // no first part, eat the ';'. 01504 ConsumeToken(); 01505 } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) && 01506 isForRangeIdentifier()) { 01507 ProhibitAttributes(attrs); 01508 IdentifierInfo *Name = Tok.getIdentifierInfo(); 01509 SourceLocation Loc = ConsumeToken(); 01510 MaybeParseCXX11Attributes(attrs); 01511 01512 ForRangeInit.ColonLoc = ConsumeToken(); 01513 if (Tok.is(tok::l_brace)) 01514 ForRangeInit.RangeExpr = ParseBraceInitializer(); 01515 else 01516 ForRangeInit.RangeExpr = ParseExpression(); 01517 01518 Diag(Loc, getLangOpts().CPlusPlus1z 01519 ? diag::warn_cxx14_compat_for_range_identifier 01520 : diag::ext_for_range_identifier) 01521 << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z) 01522 ? FixItHint::CreateInsertion(Loc, "auto &&") 01523 : FixItHint()); 01524 01525 FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name, 01526 attrs, attrs.Range.getEnd()); 01527 ForRange = true; 01528 } else if (isForInitDeclaration()) { // for (int X = 4; 01529 // Parse declaration, which eats the ';'. 01530 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode? 01531 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop); 01532 01533 // In C++0x, "for (T NS:a" might not be a typo for :: 01534 bool MightBeForRangeStmt = getLangOpts().CPlusPlus; 01535 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt); 01536 01537 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 01538 DeclGroupPtrTy DG = ParseSimpleDeclaration( 01539 Declarator::ForContext, DeclEnd, attrs, false, 01540 MightBeForRangeStmt ? &ForRangeInit : nullptr); 01541 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation()); 01542 if (ForRangeInit.ParsedForRangeDecl()) { 01543 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ? 01544 diag::warn_cxx98_compat_for_range : diag::ext_for_range); 01545 01546 ForRange = true; 01547 } else if (Tok.is(tok::semi)) { // for (int x = 4; 01548 ConsumeToken(); 01549 } else if ((ForEach = isTokIdentifier_in())) { 01550 Actions.ActOnForEachDeclStmt(DG); 01551 // ObjC: for (id x in expr) 01552 ConsumeToken(); // consume 'in' 01553 01554 if (Tok.is(tok::code_completion)) { 01555 Actions.CodeCompleteObjCForCollection(getCurScope(), DG); 01556 cutOffParsing(); 01557 return StmtError(); 01558 } 01559 Collection = ParseExpression(); 01560 } else { 01561 Diag(Tok, diag::err_expected_semi_for); 01562 } 01563 } else { 01564 ProhibitAttributes(attrs); 01565 Value = ParseExpression(); 01566 01567 ForEach = isTokIdentifier_in(); 01568 01569 // Turn the expression into a stmt. 01570 if (!Value.isInvalid()) { 01571 if (ForEach) 01572 FirstPart = Actions.ActOnForEachLValueExpr(Value.get()); 01573 else 01574 FirstPart = Actions.ActOnExprStmt(Value); 01575 } 01576 01577 if (Tok.is(tok::semi)) { 01578 ConsumeToken(); 01579 } else if (ForEach) { 01580 ConsumeToken(); // consume 'in' 01581 01582 if (Tok.is(tok::code_completion)) { 01583 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy()); 01584 cutOffParsing(); 01585 return StmtError(); 01586 } 01587 Collection = ParseExpression(); 01588 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) { 01589 // User tried to write the reasonable, but ill-formed, for-range-statement 01590 // for (expr : expr) { ... } 01591 Diag(Tok, diag::err_for_range_expected_decl) 01592 << FirstPart.get()->getSourceRange(); 01593 SkipUntil(tok::r_paren, StopBeforeMatch); 01594 SecondPartIsInvalid = true; 01595 } else { 01596 if (!Value.isInvalid()) { 01597 Diag(Tok, diag::err_expected_semi_for); 01598 } else { 01599 // Skip until semicolon or rparen, don't consume it. 01600 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 01601 if (Tok.is(tok::semi)) 01602 ConsumeToken(); 01603 } 01604 } 01605 } 01606 01607 // Parse the second part of the for specifier. 01608 getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope); 01609 if (!ForEach && !ForRange) { 01610 assert(!SecondPart.get() && "Shouldn't have a second expression yet."); 01611 // Parse the second part of the for specifier. 01612 if (Tok.is(tok::semi)) { // for (...;; 01613 // no second part. 01614 } else if (Tok.is(tok::r_paren)) { 01615 // missing both semicolons. 01616 } else { 01617 ExprResult Second; 01618 if (getLangOpts().CPlusPlus) 01619 ParseCXXCondition(Second, SecondVar, ForLoc, true); 01620 else { 01621 Second = ParseExpression(); 01622 if (!Second.isInvalid()) 01623 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc, 01624 Second.get()); 01625 } 01626 SecondPartIsInvalid = Second.isInvalid(); 01627 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc); 01628 } 01629 01630 if (Tok.isNot(tok::semi)) { 01631 if (!SecondPartIsInvalid || SecondVar) 01632 Diag(Tok, diag::err_expected_semi_for); 01633 else 01634 // Skip until semicolon or rparen, don't consume it. 01635 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); 01636 } 01637 01638 if (Tok.is(tok::semi)) { 01639 ConsumeToken(); 01640 } 01641 01642 // Parse the third part of the for specifier. 01643 if (Tok.isNot(tok::r_paren)) { // for (...;...;) 01644 ExprResult Third = ParseExpression(); 01645 // FIXME: The C++11 standard doesn't actually say that this is a 01646 // discarded-value expression, but it clearly should be. 01647 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get()); 01648 } 01649 } 01650 // Match the ')'. 01651 T.consumeClose(); 01652 01653 // We need to perform most of the semantic analysis for a C++0x for-range 01654 // statememt before parsing the body, in order to be able to deduce the type 01655 // of an auto-typed loop variable. 01656 StmtResult ForRangeStmt; 01657 StmtResult ForEachStmt; 01658 01659 if (ForRange) { 01660 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.get(), 01661 ForRangeInit.ColonLoc, 01662 ForRangeInit.RangeExpr.get(), 01663 T.getCloseLocation(), 01664 Sema::BFRK_Build); 01665 01666 01667 // Similarly, we need to do the semantic analysis for a for-range 01668 // statement immediately in order to close over temporaries correctly. 01669 } else if (ForEach) { 01670 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc, 01671 FirstPart.get(), 01672 Collection.get(), 01673 T.getCloseLocation()); 01674 } 01675 01676 // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if 01677 // there is no compound stmt. C90 does not have this clause. We only do this 01678 // if the body isn't a compound statement to avoid push/pop in common cases. 01679 // 01680 // C++ 6.5p2: 01681 // The substatement in an iteration-statement implicitly defines a local scope 01682 // which is entered and exited each time through the loop. 01683 // 01684 // See comments in ParseIfStatement for why we create a scope for 01685 // for-init-statement/condition and a new scope for substatement in C++. 01686 // 01687 ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC, 01688 Tok.is(tok::l_brace)); 01689 01690 // The body of the for loop has the same local mangling number as the 01691 // for-init-statement. 01692 // It will only be incremented if the body contains other things that would 01693 // normally increment the mangling number (like a compound statement). 01694 if (C99orCXXorObjC) 01695 getCurScope()->decrementMSLocalManglingNumber(); 01696 01697 // Read the body statement. 01698 StmtResult Body(ParseStatement(TrailingElseLoc)); 01699 01700 // Pop the body scope if needed. 01701 InnerScope.Exit(); 01702 01703 // Leave the for-scope. 01704 ForScope.Exit(); 01705 01706 if (Body.isInvalid()) 01707 return StmtError(); 01708 01709 if (ForEach) 01710 return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(), 01711 Body.get()); 01712 01713 if (ForRange) 01714 return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get()); 01715 01716 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(), 01717 SecondPart, SecondVar, ThirdPart, 01718 T.getCloseLocation(), Body.get()); 01719 } 01720 01721 /// ParseGotoStatement 01722 /// jump-statement: 01723 /// 'goto' identifier ';' 01724 /// [GNU] 'goto' '*' expression ';' 01725 /// 01726 /// Note: this lets the caller parse the end ';'. 01727 /// 01728 StmtResult Parser::ParseGotoStatement() { 01729 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!"); 01730 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'. 01731 01732 StmtResult Res; 01733 if (Tok.is(tok::identifier)) { 01734 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), 01735 Tok.getLocation()); 01736 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD); 01737 ConsumeToken(); 01738 } else if (Tok.is(tok::star)) { 01739 // GNU indirect goto extension. 01740 Diag(Tok, diag::ext_gnu_indirect_goto); 01741 SourceLocation StarLoc = ConsumeToken(); 01742 ExprResult R(ParseExpression()); 01743 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it. 01744 SkipUntil(tok::semi, StopBeforeMatch); 01745 return StmtError(); 01746 } 01747 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get()); 01748 } else { 01749 Diag(Tok, diag::err_expected) << tok::identifier; 01750 return StmtError(); 01751 } 01752 01753 return Res; 01754 } 01755 01756 /// ParseContinueStatement 01757 /// jump-statement: 01758 /// 'continue' ';' 01759 /// 01760 /// Note: this lets the caller parse the end ';'. 01761 /// 01762 StmtResult Parser::ParseContinueStatement() { 01763 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'. 01764 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope()); 01765 } 01766 01767 /// ParseBreakStatement 01768 /// jump-statement: 01769 /// 'break' ';' 01770 /// 01771 /// Note: this lets the caller parse the end ';'. 01772 /// 01773 StmtResult Parser::ParseBreakStatement() { 01774 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'. 01775 return Actions.ActOnBreakStmt(BreakLoc, getCurScope()); 01776 } 01777 01778 /// ParseReturnStatement 01779 /// jump-statement: 01780 /// 'return' expression[opt] ';' 01781 StmtResult Parser::ParseReturnStatement() { 01782 assert(Tok.is(tok::kw_return) && "Not a return stmt!"); 01783 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'. 01784 01785 ExprResult R; 01786 if (Tok.isNot(tok::semi)) { 01787 if (Tok.is(tok::code_completion)) { 01788 Actions.CodeCompleteReturn(getCurScope()); 01789 cutOffParsing(); 01790 return StmtError(); 01791 } 01792 01793 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) { 01794 R = ParseInitializer(); 01795 if (R.isUsable()) 01796 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ? 01797 diag::warn_cxx98_compat_generalized_initializer_lists : 01798 diag::ext_generalized_initializer_lists) 01799 << R.get()->getSourceRange(); 01800 } else 01801 R = ParseExpression(); 01802 if (R.isInvalid()) { 01803 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 01804 return StmtError(); 01805 } 01806 } 01807 return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope()); 01808 } 01809 01810 StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts, bool OnlyStatement, 01811 SourceLocation *TrailingElseLoc, 01812 ParsedAttributesWithRange &Attrs) { 01813 // Create temporary attribute list. 01814 ParsedAttributesWithRange TempAttrs(AttrFactory); 01815 01816 // Get loop hints and consume annotated token. 01817 while (Tok.is(tok::annot_pragma_loop_hint)) { 01818 LoopHint Hint; 01819 if (!HandlePragmaLoopHint(Hint)) 01820 continue; 01821 01822 ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc, 01823 ArgsUnion(Hint.ValueExpr)}; 01824 TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr, 01825 Hint.PragmaNameLoc->Loc, ArgHints, 4, 01826 AttributeList::AS_Pragma); 01827 } 01828 01829 // Get the next statement. 01830 MaybeParseCXX11Attributes(Attrs); 01831 01832 StmtResult S = ParseStatementOrDeclarationAfterAttributes( 01833 Stmts, OnlyStatement, TrailingElseLoc, Attrs); 01834 01835 Attrs.takeAllFrom(TempAttrs); 01836 return S; 01837 } 01838 01839 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) { 01840 assert(Tok.is(tok::l_brace)); 01841 SourceLocation LBraceLoc = Tok.getLocation(); 01842 01843 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) && 01844 trySkippingFunctionBody()) { 01845 BodyScope.Exit(); 01846 return Actions.ActOnSkippedFunctionBody(Decl); 01847 } 01848 01849 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc, 01850 "parsing function body"); 01851 01852 // Do not enter a scope for the brace, as the arguments are in the same scope 01853 // (the function body) as the body itself. Instead, just read the statement 01854 // list and put it into a CompoundStmt for safe keeping. 01855 StmtResult FnBody(ParseCompoundStatementBody()); 01856 01857 // If the function body could not be parsed, make a bogus compoundstmt. 01858 if (FnBody.isInvalid()) { 01859 Sema::CompoundScopeRAII CompoundScope(Actions); 01860 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false); 01861 } 01862 01863 BodyScope.Exit(); 01864 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get()); 01865 } 01866 01867 /// ParseFunctionTryBlock - Parse a C++ function-try-block. 01868 /// 01869 /// function-try-block: 01870 /// 'try' ctor-initializer[opt] compound-statement handler-seq 01871 /// 01872 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) { 01873 assert(Tok.is(tok::kw_try) && "Expected 'try'"); 01874 SourceLocation TryLoc = ConsumeToken(); 01875 01876 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc, 01877 "parsing function try block"); 01878 01879 // Constructor initializer list? 01880 if (Tok.is(tok::colon)) 01881 ParseConstructorInitializer(Decl); 01882 else 01883 Actions.ActOnDefaultCtorInitializers(Decl); 01884 01885 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) && 01886 trySkippingFunctionBody()) { 01887 BodyScope.Exit(); 01888 return Actions.ActOnSkippedFunctionBody(Decl); 01889 } 01890 01891 SourceLocation LBraceLoc = Tok.getLocation(); 01892 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true)); 01893 // If we failed to parse the try-catch, we just give the function an empty 01894 // compound statement as the body. 01895 if (FnBody.isInvalid()) { 01896 Sema::CompoundScopeRAII CompoundScope(Actions); 01897 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false); 01898 } 01899 01900 BodyScope.Exit(); 01901 return Actions.ActOnFinishFunctionBody(Decl, FnBody.get()); 01902 } 01903 01904 bool Parser::trySkippingFunctionBody() { 01905 assert(Tok.is(tok::l_brace)); 01906 assert(SkipFunctionBodies && 01907 "Should only be called when SkipFunctionBodies is enabled"); 01908 01909 if (!PP.isCodeCompletionEnabled()) { 01910 ConsumeBrace(); 01911 SkipUntil(tok::r_brace); 01912 return true; 01913 } 01914 01915 // We're in code-completion mode. Skip parsing for all function bodies unless 01916 // the body contains the code-completion point. 01917 TentativeParsingAction PA(*this); 01918 ConsumeBrace(); 01919 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) { 01920 PA.Commit(); 01921 return true; 01922 } 01923 01924 PA.Revert(); 01925 return false; 01926 } 01927 01928 /// ParseCXXTryBlock - Parse a C++ try-block. 01929 /// 01930 /// try-block: 01931 /// 'try' compound-statement handler-seq 01932 /// 01933 StmtResult Parser::ParseCXXTryBlock() { 01934 assert(Tok.is(tok::kw_try) && "Expected 'try'"); 01935 01936 SourceLocation TryLoc = ConsumeToken(); 01937 return ParseCXXTryBlockCommon(TryLoc); 01938 } 01939 01940 /// ParseCXXTryBlockCommon - Parse the common part of try-block and 01941 /// function-try-block. 01942 /// 01943 /// try-block: 01944 /// 'try' compound-statement handler-seq 01945 /// 01946 /// function-try-block: 01947 /// 'try' ctor-initializer[opt] compound-statement handler-seq 01948 /// 01949 /// handler-seq: 01950 /// handler handler-seq[opt] 01951 /// 01952 /// [Borland] try-block: 01953 /// 'try' compound-statement seh-except-block 01954 /// 'try' compound-statement seh-finally-block 01955 /// 01956 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) { 01957 if (Tok.isNot(tok::l_brace)) 01958 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); 01959 // FIXME: Possible draft standard bug: attribute-specifier should be allowed? 01960 01961 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false, 01962 Scope::DeclScope | Scope::TryScope | 01963 (FnTry ? Scope::FnTryCatchScope : 0))); 01964 if (TryBlock.isInvalid()) 01965 return TryBlock; 01966 01967 // Borland allows SEH-handlers with 'try' 01968 01969 if ((Tok.is(tok::identifier) && 01970 Tok.getIdentifierInfo() == getSEHExceptKeyword()) || 01971 Tok.is(tok::kw___finally)) { 01972 // TODO: Factor into common return ParseSEHHandlerCommon(...) 01973 StmtResult Handler; 01974 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) { 01975 SourceLocation Loc = ConsumeToken(); 01976 Handler = ParseSEHExceptBlock(Loc); 01977 } 01978 else { 01979 SourceLocation Loc = ConsumeToken(); 01980 Handler = ParseSEHFinallyBlock(Loc); 01981 } 01982 if(Handler.isInvalid()) 01983 return Handler; 01984 01985 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */, 01986 TryLoc, 01987 TryBlock.get(), 01988 Handler.get()); 01989 } 01990 else { 01991 StmtVector Handlers; 01992 01993 // C++11 attributes can't appear here, despite this context seeming 01994 // statement-like. 01995 DiagnoseAndSkipCXX11Attributes(); 01996 01997 if (Tok.isNot(tok::kw_catch)) 01998 return StmtError(Diag(Tok, diag::err_expected_catch)); 01999 while (Tok.is(tok::kw_catch)) { 02000 StmtResult Handler(ParseCXXCatchBlock(FnTry)); 02001 if (!Handler.isInvalid()) 02002 Handlers.push_back(Handler.get()); 02003 } 02004 // Don't bother creating the full statement if we don't have any usable 02005 // handlers. 02006 if (Handlers.empty()) 02007 return StmtError(); 02008 02009 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers); 02010 } 02011 } 02012 02013 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard 02014 /// 02015 /// handler: 02016 /// 'catch' '(' exception-declaration ')' compound-statement 02017 /// 02018 /// exception-declaration: 02019 /// attribute-specifier-seq[opt] type-specifier-seq declarator 02020 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt] 02021 /// '...' 02022 /// 02023 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) { 02024 assert(Tok.is(tok::kw_catch) && "Expected 'catch'"); 02025 02026 SourceLocation CatchLoc = ConsumeToken(); 02027 02028 BalancedDelimiterTracker T(*this, tok::l_paren); 02029 if (T.expectAndConsume()) 02030 return StmtError(); 02031 02032 // C++ 3.3.2p3: 02033 // The name in a catch exception-declaration is local to the handler and 02034 // shall not be redeclared in the outermost block of the handler. 02035 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope | 02036 (FnCatch ? Scope::FnTryCatchScope : 0)); 02037 02038 // exception-declaration is equivalent to '...' or a parameter-declaration 02039 // without default arguments. 02040 Decl *ExceptionDecl = nullptr; 02041 if (Tok.isNot(tok::ellipsis)) { 02042 ParsedAttributesWithRange Attributes(AttrFactory); 02043 MaybeParseCXX11Attributes(Attributes); 02044 02045 DeclSpec DS(AttrFactory); 02046 DS.takeAttributesFrom(Attributes); 02047 02048 if (ParseCXXTypeSpecifierSeq(DS)) 02049 return StmtError(); 02050 02051 Declarator ExDecl(DS, Declarator::CXXCatchContext); 02052 ParseDeclarator(ExDecl); 02053 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl); 02054 } else 02055 ConsumeToken(); 02056 02057 T.consumeClose(); 02058 if (T.getCloseLocation().isInvalid()) 02059 return StmtError(); 02060 02061 if (Tok.isNot(tok::l_brace)) 02062 return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); 02063 02064 // FIXME: Possible draft standard bug: attribute-specifier should be allowed? 02065 StmtResult Block(ParseCompoundStatement()); 02066 if (Block.isInvalid()) 02067 return Block; 02068 02069 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get()); 02070 } 02071 02072 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) { 02073 IfExistsCondition Result; 02074 if (ParseMicrosoftIfExistsCondition(Result)) 02075 return; 02076 02077 // Handle dependent statements by parsing the braces as a compound statement. 02078 // This is not the same behavior as Visual C++, which don't treat this as a 02079 // compound statement, but for Clang's type checking we can't have anything 02080 // inside these braces escaping to the surrounding code. 02081 if (Result.Behavior == IEB_Dependent) { 02082 if (!Tok.is(tok::l_brace)) { 02083 Diag(Tok, diag::err_expected) << tok::l_brace; 02084 return; 02085 } 02086 02087 StmtResult Compound = ParseCompoundStatement(); 02088 if (Compound.isInvalid()) 02089 return; 02090 02091 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc, 02092 Result.IsIfExists, 02093 Result.SS, 02094 Result.Name, 02095 Compound.get()); 02096 if (DepResult.isUsable()) 02097 Stmts.push_back(DepResult.get()); 02098 return; 02099 } 02100 02101 BalancedDelimiterTracker Braces(*this, tok::l_brace); 02102 if (Braces.consumeOpen()) { 02103 Diag(Tok, diag::err_expected) << tok::l_brace; 02104 return; 02105 } 02106 02107 switch (Result.Behavior) { 02108 case IEB_Parse: 02109 // Parse the statements below. 02110 break; 02111 02112 case IEB_Dependent: 02113 llvm_unreachable("Dependent case handled above"); 02114 02115 case IEB_Skip: 02116 Braces.skipToEnd(); 02117 return; 02118 } 02119 02120 // Condition is true, parse the statements. 02121 while (Tok.isNot(tok::r_brace)) { 02122 StmtResult R = ParseStatementOrDeclaration(Stmts, false); 02123 if (R.isUsable()) 02124 Stmts.push_back(R.get()); 02125 } 02126 Braces.consumeClose(); 02127 }