1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Statement and Block portions of the Parser
13 //===----------------------------------------------------------------------===//
15 #include "clang/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/Sema/DeclSpec.h"
18 #include "clang/Sema/PrettyDeclStackTrace.h"
19 #include "clang/Sema/Scope.h"
20 #include "clang/Sema/TypoCorrection.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/PrettyStackTrace.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "llvm/ADT/SmallString.h"
25 using namespace clang;
27 //===----------------------------------------------------------------------===//
28 // C99 6.8: Statements and Blocks.
29 //===----------------------------------------------------------------------===//
31 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
32 /// StatementOrDeclaration:
38 /// compound-statement
39 /// expression-statement
40 /// selection-statement
41 /// iteration-statement
43 /// [C++] declaration-statement
45 /// [MS] seh-try-block
46 /// [OBC] objc-throw-statement
47 /// [OBC] objc-try-catch-statement
48 /// [OBC] objc-synchronized-statement
49 /// [GNU] asm-statement
50 /// [OMP] openmp-construct [TODO]
52 /// labeled-statement:
53 /// identifier ':' statement
54 /// 'case' constant-expression ':' statement
55 /// 'default' ':' statement
57 /// selection-statement:
61 /// iteration-statement:
66 /// expression-statement:
67 /// expression[opt] ';'
70 /// 'goto' identifier ';'
73 /// 'return' expression[opt] ';'
74 /// [GNU] 'goto' '*' expression ';'
76 /// [OBC] objc-throw-statement:
77 /// [OBC] '@' 'throw' expression ';'
78 /// [OBC] '@' 'throw' ';'
81 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
82 SourceLocation *TrailingElseLoc) {
84 ParenBraceBracketBalancer BalancerRAIIObj(*this);
86 ParsedAttributesWithRange Attrs(AttrFactory);
87 MaybeParseCXX0XAttributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
89 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
90 OnlyStatement, TrailingElseLoc, Attrs);
92 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
93 "attributes on empty statement");
95 if (Attrs.empty() || Res.isInvalid())
98 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
102 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
103 bool OnlyStatement, SourceLocation *TrailingElseLoc,
104 ParsedAttributesWithRange &Attrs) {
105 const char *SemiError = 0;
108 // Cases in this switch statement should fall through if the parser expects
109 // the token to end in a semicolon (in which case SemiError should be set),
110 // or they directly 'return;' if not.
112 tok::TokenKind Kind = Tok.getKind();
113 SourceLocation AtLoc;
115 case tok::at: // May be a @try or @throw statement
117 ProhibitAttributes(Attrs); // TODO: is it correct?
118 AtLoc = ConsumeToken(); // consume @
119 return ParseObjCAtStatement(AtLoc);
122 case tok::code_completion:
123 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
127 case tok::identifier: {
128 Token Next = NextToken();
129 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
130 // identifier ':' statement
131 return ParseLabeledStatement(Attrs);
134 // Look up the identifier, and typo-correct it to a keyword if it's not
136 if (Next.isNot(tok::coloncolon)) {
137 // Try to limit which sets of keywords should be included in typo
138 // correction based on what the next token is.
139 // FIXME: Pass the next token into the CorrectionCandidateCallback and
140 // do this filtering in a more fine-grained manner.
141 CorrectionCandidateCallback DefaultValidator;
142 DefaultValidator.WantTypeSpecifiers =
143 Next.is(tok::l_paren) || Next.is(tok::less) ||
144 Next.is(tok::identifier) || Next.is(tok::star) ||
145 Next.is(tok::amp) || Next.is(tok::l_square);
146 DefaultValidator.WantExpressionKeywords =
147 Next.is(tok::l_paren) || Next.is(tok::identifier) ||
148 Next.is(tok::arrow) || Next.is(tok::period);
149 DefaultValidator.WantRemainingKeywords =
150 Next.is(tok::l_paren) || Next.is(tok::semi) ||
151 Next.is(tok::identifier) || Next.is(tok::l_brace);
152 DefaultValidator.WantCXXNamedCasts = false;
153 if (TryAnnotateName(/*IsAddressOfOperand*/false, &DefaultValidator)
155 // Handle errors here by skipping up to the next semicolon or '}', and
156 // eat the semicolon if that's what stopped us.
157 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
158 if (Tok.is(tok::semi))
163 // If the identifier was typo-corrected, try again.
164 if (Tok.isNot(tok::identifier))
172 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
173 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
174 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
176 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
179 if (Tok.is(tok::r_brace)) {
180 Diag(Tok, diag::err_expected_statement);
184 return ParseExprStatement();
187 case tok::kw_case: // C99 6.8.1: labeled-statement
188 return ParseCaseStatement();
189 case tok::kw_default: // C99 6.8.1: labeled-statement
190 return ParseDefaultStatement();
192 case tok::l_brace: // C99 6.8.2: compound-statement
193 return ParseCompoundStatement();
194 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
195 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
196 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
199 case tok::kw_if: // C99 6.8.4.1: if-statement
200 return ParseIfStatement(TrailingElseLoc);
201 case tok::kw_switch: // C99 6.8.4.2: switch-statement
202 return ParseSwitchStatement(TrailingElseLoc);
204 case tok::kw_while: // C99 6.8.5.1: while-statement
205 return ParseWhileStatement(TrailingElseLoc);
206 case tok::kw_do: // C99 6.8.5.2: do-statement
207 Res = ParseDoStatement();
208 SemiError = "do/while";
210 case tok::kw_for: // C99 6.8.5.3: for-statement
211 return ParseForStatement(TrailingElseLoc);
213 case tok::kw_goto: // C99 6.8.6.1: goto-statement
214 Res = ParseGotoStatement();
217 case tok::kw_continue: // C99 6.8.6.2: continue-statement
218 Res = ParseContinueStatement();
219 SemiError = "continue";
221 case tok::kw_break: // C99 6.8.6.3: break-statement
222 Res = ParseBreakStatement();
225 case tok::kw_return: // C99 6.8.6.4: return-statement
226 Res = ParseReturnStatement();
227 SemiError = "return";
231 ProhibitAttributes(Attrs);
233 Res = ParseAsmStatement(msAsm);
234 Res = Actions.ActOnFinishFullStmt(Res.get());
235 if (msAsm) return Res;
240 case tok::kw_try: // C++ 15: try-block
241 return ParseCXXTryBlock();
244 ProhibitAttributes(Attrs); // TODO: is it correct?
245 return ParseSEHTryBlock();
247 case tok::annot_pragma_vis:
248 ProhibitAttributes(Attrs);
249 HandlePragmaVisibility();
252 case tok::annot_pragma_pack:
253 ProhibitAttributes(Attrs);
257 case tok::annot_pragma_msstruct:
258 ProhibitAttributes(Attrs);
259 HandlePragmaMSStruct();
262 case tok::annot_pragma_align:
263 ProhibitAttributes(Attrs);
267 case tok::annot_pragma_weak:
268 ProhibitAttributes(Attrs);
272 case tok::annot_pragma_weakalias:
273 ProhibitAttributes(Attrs);
274 HandlePragmaWeakAlias();
277 case tok::annot_pragma_redefine_extname:
278 ProhibitAttributes(Attrs);
279 HandlePragmaRedefineExtname();
282 case tok::annot_pragma_fp_contract:
283 Diag(Tok, diag::err_pragma_fp_contract_scope);
287 case tok::annot_pragma_opencl_extension:
288 ProhibitAttributes(Attrs);
289 HandlePragmaOpenCLExtension();
293 // If we reached this code, the statement must end in a semicolon.
294 if (Tok.is(tok::semi)) {
296 } else if (!Res.isInvalid()) {
297 // If the result was valid, then we do want to diagnose this. Use
298 // ExpectAndConsume to emit the diagnostic, even though we know it won't
300 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
301 // Skip until we see a } or ;, but don't eat it.
302 SkipUntil(tok::r_brace, true, true);
308 /// \brief Parse an expression statement.
309 StmtResult Parser::ParseExprStatement() {
310 // If a case keyword is missing, this is where it should be inserted.
311 Token OldToken = Tok;
313 // expression[opt] ';'
314 ExprResult Expr(ParseExpression());
315 if (Expr.isInvalid()) {
316 // If the expression is invalid, skip ahead to the next semicolon or '}'.
317 // Not doing this opens us up to the possibility of infinite loops if
318 // ParseExpression does not consume any tokens.
319 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
320 if (Tok.is(tok::semi))
325 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
326 Actions.CheckCaseExpression(Expr.get())) {
327 // If a constant expression is followed by a colon inside a switch block,
328 // suggest a missing case keyword.
329 Diag(OldToken, diag::err_expected_case_before_expression)
330 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
332 // Recover parsing as a case statement.
333 return ParseCaseStatement(/*MissingCase=*/true, Expr);
336 // Otherwise, eat the semicolon.
337 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
338 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
341 StmtResult Parser::ParseSEHTryBlock() {
342 assert(Tok.is(tok::kw___try) && "Expected '__try'");
343 SourceLocation Loc = ConsumeToken();
344 return ParseSEHTryBlockCommon(Loc);
347 /// ParseSEHTryBlockCommon
350 /// '__try' compound-statement seh-handler
354 /// seh-finally-block
356 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
357 if(Tok.isNot(tok::l_brace))
358 return StmtError(Diag(Tok,diag::err_expected_lbrace));
360 StmtResult TryBlock(ParseCompoundStatement());
361 if(TryBlock.isInvalid())
365 if (Tok.is(tok::identifier) &&
366 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
367 SourceLocation Loc = ConsumeToken();
368 Handler = ParseSEHExceptBlock(Loc);
369 } else if (Tok.is(tok::kw___finally)) {
370 SourceLocation Loc = ConsumeToken();
371 Handler = ParseSEHFinallyBlock(Loc);
373 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
376 if(Handler.isInvalid())
379 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
385 /// ParseSEHExceptBlock - Handle __except
387 /// seh-except-block:
388 /// '__except' '(' seh-filter-expression ')' compound-statement
390 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
391 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
392 raii2(Ident___exception_code, false),
393 raii3(Ident_GetExceptionCode, false);
395 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
398 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
400 if (getLangOpts().Borland) {
401 Ident__exception_info->setIsPoisoned(false);
402 Ident___exception_info->setIsPoisoned(false);
403 Ident_GetExceptionInfo->setIsPoisoned(false);
405 ExprResult FilterExpr(ParseExpression());
407 if (getLangOpts().Borland) {
408 Ident__exception_info->setIsPoisoned(true);
409 Ident___exception_info->setIsPoisoned(true);
410 Ident_GetExceptionInfo->setIsPoisoned(true);
413 if(FilterExpr.isInvalid())
416 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
419 StmtResult Block(ParseCompoundStatement());
421 if(Block.isInvalid())
424 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
427 /// ParseSEHFinallyBlock - Handle __finally
429 /// seh-finally-block:
430 /// '__finally' compound-statement
432 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
433 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
434 raii2(Ident___abnormal_termination, false),
435 raii3(Ident_AbnormalTermination, false);
437 StmtResult Block(ParseCompoundStatement());
438 if(Block.isInvalid())
441 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
444 /// ParseLabeledStatement - We have an identifier and a ':' after it.
446 /// labeled-statement:
447 /// identifier ':' statement
448 /// [GNU] identifier ':' attributes[opt] statement
450 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
451 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
452 "Not an identifier!");
454 Token IdentTok = Tok; // Save the whole token.
455 ConsumeToken(); // eat the identifier.
457 assert(Tok.is(tok::colon) && "Not a label!");
459 // identifier ':' statement
460 SourceLocation ColonLoc = ConsumeToken();
462 // Read label attributes, if present. attrs will contain both C++11 and GNU
463 // attributes (if present) after this point.
464 MaybeParseGNUAttributes(attrs);
466 StmtResult SubStmt(ParseStatement());
468 // Broken substmt shouldn't prevent the label from being added to the AST.
469 if (SubStmt.isInvalid())
470 SubStmt = Actions.ActOnNullStmt(ColonLoc);
472 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
473 IdentTok.getLocation());
474 if (AttributeList *Attrs = attrs.getList()) {
475 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
479 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
483 /// ParseCaseStatement
484 /// labeled-statement:
485 /// 'case' constant-expression ':' statement
486 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
488 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
489 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
491 // It is very very common for code to contain many case statements recursively
492 // nested, as in (but usually without indentation):
499 // Parsing this naively works, but is both inefficient and can cause us to run
500 // out of stack space in our recursive descent parser. As a special case,
501 // flatten this recursion into an iterative loop. This is complex and gross,
502 // but all the grossness is constrained to ParseCaseStatement (and some
503 // wierdness in the actions), so this is just local grossness :).
505 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
507 StmtResult TopLevelCase(true);
509 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
510 // gets updated each time a new case is parsed, and whose body is unset so
511 // far. When parsing 'case 4', this is the 'case 3' node.
512 Stmt *DeepestParsedCaseStmt = 0;
514 // While we have case statements, eat and stack them.
515 SourceLocation ColonLoc;
517 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
518 ConsumeToken(); // eat the 'case'.
520 if (Tok.is(tok::code_completion)) {
521 Actions.CodeCompleteCase(getCurScope());
526 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
527 /// Disable this form of error recovery while we're parsing the case
529 ColonProtectionRAIIObject ColonProtection(*this);
531 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
533 if (LHS.isInvalid()) {
534 SkipUntil(tok::colon);
538 // GNU case range extension.
539 SourceLocation DotDotDotLoc;
541 if (Tok.is(tok::ellipsis)) {
542 Diag(Tok, diag::ext_gnu_case_range);
543 DotDotDotLoc = ConsumeToken();
545 RHS = ParseConstantExpression();
546 if (RHS.isInvalid()) {
547 SkipUntil(tok::colon);
552 ColonProtection.restore();
554 if (Tok.is(tok::colon)) {
555 ColonLoc = ConsumeToken();
557 // Treat "case blah;" as a typo for "case blah:".
558 } else if (Tok.is(tok::semi)) {
559 ColonLoc = ConsumeToken();
560 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
561 << FixItHint::CreateReplacement(ColonLoc, ":");
563 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
564 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
565 << FixItHint::CreateInsertion(ExpectedLoc, ":");
566 ColonLoc = ExpectedLoc;
570 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
571 RHS.get(), ColonLoc);
573 // If we had a sema error parsing this case, then just ignore it and
574 // continue parsing the sub-stmt.
575 if (Case.isInvalid()) {
576 if (TopLevelCase.isInvalid()) // No parsed case stmts.
577 return ParseStatement();
578 // Otherwise, just don't add it as a nested case.
580 // If this is the first case statement we parsed, it becomes TopLevelCase.
581 // Otherwise we link it into the current chain.
582 Stmt *NextDeepest = Case.get();
583 if (TopLevelCase.isInvalid())
586 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
587 DeepestParsedCaseStmt = NextDeepest;
590 // Handle all case statements.
591 } while (Tok.is(tok::kw_case));
593 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
595 // If we found a non-case statement, start by parsing it.
598 if (Tok.isNot(tok::r_brace)) {
599 SubStmt = ParseStatement();
601 // Nicely diagnose the common error "switch (X) { case 4: }", which is
603 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
604 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
605 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
609 // Broken sub-stmt shouldn't prevent forming the case statement properly.
610 if (SubStmt.isInvalid())
611 SubStmt = Actions.ActOnNullStmt(SourceLocation());
613 // Install the body into the most deeply-nested case.
614 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
616 // Return the top level parsed statement tree.
620 /// ParseDefaultStatement
621 /// labeled-statement:
622 /// 'default' ':' statement
623 /// Note that this does not parse the 'statement' at the end.
625 StmtResult Parser::ParseDefaultStatement() {
626 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
627 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
629 SourceLocation ColonLoc;
630 if (Tok.is(tok::colon)) {
631 ColonLoc = ConsumeToken();
633 // Treat "default;" as a typo for "default:".
634 } else if (Tok.is(tok::semi)) {
635 ColonLoc = ConsumeToken();
636 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
637 << FixItHint::CreateReplacement(ColonLoc, ":");
639 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
640 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
641 << FixItHint::CreateInsertion(ExpectedLoc, ":");
642 ColonLoc = ExpectedLoc;
647 if (Tok.isNot(tok::r_brace)) {
648 SubStmt = ParseStatement();
650 // Diagnose the common error "switch (X) {... default: }", which is
652 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
653 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
654 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
658 // Broken sub-stmt shouldn't prevent forming the case statement properly.
659 if (SubStmt.isInvalid())
660 SubStmt = Actions.ActOnNullStmt(ColonLoc);
662 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
663 SubStmt.get(), getCurScope());
666 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
667 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
670 /// ParseCompoundStatement - Parse a "{}" block.
672 /// compound-statement: [C99 6.8.2]
673 /// { block-item-list[opt] }
674 /// [GNU] { label-declarations block-item-list } [TODO]
678 /// block-item-list block-item
682 /// [GNU] '__extension__' declaration
684 /// [OMP] openmp-directive [TODO]
686 /// [GNU] label-declarations:
687 /// [GNU] label-declaration
688 /// [GNU] label-declarations label-declaration
690 /// [GNU] label-declaration:
691 /// [GNU] '__label__' identifier-list ';'
693 /// [OMP] openmp-directive: [TODO]
694 /// [OMP] barrier-directive
695 /// [OMP] flush-directive
697 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
698 unsigned ScopeFlags) {
699 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
701 // Enter a scope to hold everything within the compound stmt. Compound
702 // statements can always hold declarations.
703 ParseScope CompoundScope(this, ScopeFlags);
705 // Parse the statements in the body.
706 return ParseCompoundStatementBody(isStmtExpr);
709 /// Parse any pragmas at the start of the compound expression. We handle these
710 /// separately since some pragmas (FP_CONTRACT) must appear before any C
711 /// statement in the compound, but may be intermingled with other pragmas.
712 void Parser::ParseCompoundStatementLeadingPragmas() {
713 bool checkForPragmas = true;
714 while (checkForPragmas) {
715 switch (Tok.getKind()) {
716 case tok::annot_pragma_vis:
717 HandlePragmaVisibility();
719 case tok::annot_pragma_pack:
722 case tok::annot_pragma_msstruct:
723 HandlePragmaMSStruct();
725 case tok::annot_pragma_align:
728 case tok::annot_pragma_weak:
731 case tok::annot_pragma_weakalias:
732 HandlePragmaWeakAlias();
734 case tok::annot_pragma_redefine_extname:
735 HandlePragmaRedefineExtname();
737 case tok::annot_pragma_opencl_extension:
738 HandlePragmaOpenCLExtension();
740 case tok::annot_pragma_fp_contract:
741 HandlePragmaFPContract();
744 checkForPragmas = false;
751 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
752 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
753 /// consume the '}' at the end of the block. It does not manipulate the scope
755 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
756 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
758 "in compound statement ('{}')");
760 // Record the state of the FP_CONTRACT pragma, restore on leaving the
761 // compound statement.
762 Sema::FPContractStateRAII SaveFPContractState(Actions);
764 InMessageExpressionRAIIObject InMessage(*this, false);
765 BalancedDelimiterTracker T(*this, tok::l_brace);
769 Sema::CompoundScopeRAII CompoundScope(Actions);
771 // Parse any pragmas at the beginning of the compound statement.
772 ParseCompoundStatementLeadingPragmas();
776 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
777 // only allowed at the start of a compound stmt regardless of the language.
778 while (Tok.is(tok::kw___label__)) {
779 SourceLocation LabelLoc = ConsumeToken();
780 Diag(LabelLoc, diag::ext_gnu_local_label);
782 SmallVector<Decl *, 8> DeclsInGroup;
784 if (Tok.isNot(tok::identifier)) {
785 Diag(Tok, diag::err_expected_ident);
789 IdentifierInfo *II = Tok.getIdentifierInfo();
790 SourceLocation IdLoc = ConsumeToken();
791 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
793 if (!Tok.is(tok::comma))
798 DeclSpec DS(AttrFactory);
799 DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
800 DeclsInGroup.data(), DeclsInGroup.size());
801 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
803 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
805 Stmts.push_back(R.release());
808 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
809 if (Tok.is(tok::annot_pragma_unused)) {
810 HandlePragmaUnused();
814 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
815 Tok.is(tok::kw___if_not_exists))) {
816 ParseMicrosoftIfExistsStatement(Stmts);
821 if (Tok.isNot(tok::kw___extension__)) {
822 R = ParseStatementOrDeclaration(Stmts, false);
824 // __extension__ can start declarations and it can also be a unary
825 // operator for expressions. Consume multiple __extension__ markers here
826 // until we can determine which is which.
827 // FIXME: This loses extension expressions in the AST!
828 SourceLocation ExtLoc = ConsumeToken();
829 while (Tok.is(tok::kw___extension__))
832 ParsedAttributesWithRange attrs(AttrFactory);
833 MaybeParseCXX0XAttributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
835 // If this is the start of a declaration, parse it as such.
836 if (isDeclarationStatement()) {
837 // __extension__ silences extension warnings in the subdeclaration.
838 // FIXME: Save the __extension__ on the decl as a node somehow?
839 ExtensionRAIIObject O(Diags);
841 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
842 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
843 Declarator::BlockContext, DeclEnd,
845 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
847 // Otherwise this was a unary __extension__ marker.
848 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
850 if (Res.isInvalid()) {
851 SkipUntil(tok::semi);
855 // FIXME: Use attributes?
856 // Eat the semicolon at the end of stmt and convert the expr into a
858 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
859 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
864 Stmts.push_back(R.release());
867 SourceLocation CloseLoc = Tok.getLocation();
869 // We broke out of the while loop because we found a '}' or EOF.
870 if (Tok.isNot(tok::r_brace)) {
871 Diag(Tok, diag::err_expected_rbrace);
872 Diag(T.getOpenLocation(), diag::note_matching) << "{";
873 // Recover by creating a compound statement with what we parsed so far,
874 // instead of dropping everything and returning StmtError();
876 if (!T.consumeClose())
877 CloseLoc = T.getCloseLocation();
880 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
884 /// ParseParenExprOrCondition:
885 /// [C ] '(' expression ')'
886 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
888 /// This function parses and performs error recovery on the specified condition
889 /// or expression (depending on whether we're in C++ or C mode). This function
890 /// goes out of its way to recover well. It returns true if there was a parser
891 /// error (the right paren couldn't be found), which indicates that the caller
892 /// should try to recover harder. It returns false if the condition is
893 /// successfully parsed. Note that a successful parse can still have semantic
894 /// errors in the condition.
895 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
898 bool ConvertToBoolean) {
899 BalancedDelimiterTracker T(*this, tok::l_paren);
902 if (getLangOpts().CPlusPlus)
903 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
905 ExprResult = ParseExpression();
908 // If required, convert to a boolean value.
909 if (!ExprResult.isInvalid() && ConvertToBoolean)
911 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
914 // If the parser was confused by the condition and we don't have a ')', try to
915 // recover by skipping ahead to a semi and bailing out. If condexp is
916 // semantically invalid but we have well formed code, keep going.
917 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
918 SkipUntil(tok::semi);
919 // Skipping may have stopped if it found the containing ')'. If so, we can
920 // continue parsing the if statement.
921 if (Tok.isNot(tok::r_paren))
925 // Otherwise the condition is valid or the rparen is present.
928 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
929 // that all callers are looking for a statement after the condition, so ")"
931 while (Tok.is(tok::r_paren)) {
932 Diag(Tok, diag::err_extraneous_rparen_in_condition)
933 << FixItHint::CreateRemoval(Tok.getLocation());
942 /// if-statement: [C99 6.8.4.1]
943 /// 'if' '(' expression ')' statement
944 /// 'if' '(' expression ')' statement 'else' statement
945 /// [C++] 'if' '(' condition ')' statement
946 /// [C++] 'if' '(' condition ')' statement 'else' statement
948 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
949 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
950 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
952 if (Tok.isNot(tok::l_paren)) {
953 Diag(Tok, diag::err_expected_lparen_after) << "if";
954 SkipUntil(tok::semi);
958 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
960 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
964 // A name introduced by a declaration in a condition is in scope from its
965 // point of declaration until the end of the substatements controlled by the
968 // Names declared in the for-init-statement, and in the condition of if,
969 // while, for, and switch statements are local to the if, while, for, or
970 // switch statement (including the controlled statement).
972 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
974 // Parse the condition.
977 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
980 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
982 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
983 // there is no compound stmt. C90 does not have this clause. We only do this
984 // if the body isn't a compound statement to avoid push/pop in common cases.
987 // The substatement in a selection-statement (each substatement, in the else
988 // form of the if statement) implicitly defines a local scope.
990 // For C++ we create a scope for the condition and a new scope for
991 // substatements because:
992 // -When the 'then' scope exits, we want the condition declaration to still be
993 // active for the 'else' scope too.
994 // -Sema will detect name clashes by considering declarations of a
995 // 'ControlScope' as part of its direct subscope.
996 // -If we wanted the condition and substatement to be in the same scope, we
997 // would have to notify ParseStatement not to create a new scope. It's
998 // simpler to let it create a new scope.
1000 ParseScope InnerScope(this, Scope::DeclScope,
1001 C99orCXX && Tok.isNot(tok::l_brace));
1003 // Read the 'then' stmt.
1004 SourceLocation ThenStmtLoc = Tok.getLocation();
1006 SourceLocation InnerStatementTrailingElseLoc;
1007 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
1009 // Pop the 'if' scope if needed.
1012 // If it has an else, parse it.
1013 SourceLocation ElseLoc;
1014 SourceLocation ElseStmtLoc;
1015 StmtResult ElseStmt;
1017 if (Tok.is(tok::kw_else)) {
1018 if (TrailingElseLoc)
1019 *TrailingElseLoc = Tok.getLocation();
1021 ElseLoc = ConsumeToken();
1022 ElseStmtLoc = Tok.getLocation();
1024 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1025 // there is no compound stmt. C90 does not have this clause. We only do
1026 // this if the body isn't a compound statement to avoid push/pop in common
1030 // The substatement in a selection-statement (each substatement, in the else
1031 // form of the if statement) implicitly defines a local scope.
1033 ParseScope InnerScope(this, Scope::DeclScope,
1034 C99orCXX && Tok.isNot(tok::l_brace));
1036 ElseStmt = ParseStatement();
1038 // Pop the 'else' scope if needed.
1040 } else if (Tok.is(tok::code_completion)) {
1041 Actions.CodeCompleteAfterIf(getCurScope());
1044 } else if (InnerStatementTrailingElseLoc.isValid()) {
1045 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1050 // If the condition was invalid, discard the if statement. We could recover
1051 // better by replacing it with a valid expr, but don't do that yet.
1052 if (CondExp.isInvalid() && !CondVar)
1055 // If the then or else stmt is invalid and the other is valid (and present),
1056 // make turn the invalid one into a null stmt to avoid dropping the other
1057 // part. If both are invalid, return error.
1058 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1059 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1060 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
1061 // Both invalid, or one is invalid and other is non-present: return error.
1065 // Now if either are invalid, replace with a ';'.
1066 if (ThenStmt.isInvalid())
1067 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1068 if (ElseStmt.isInvalid())
1069 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1071 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
1072 ElseLoc, ElseStmt.get());
1075 /// ParseSwitchStatement
1076 /// switch-statement:
1077 /// 'switch' '(' expression ')' statement
1078 /// [C++] 'switch' '(' condition ')' statement
1079 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1080 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1081 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1083 if (Tok.isNot(tok::l_paren)) {
1084 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1085 SkipUntil(tok::semi);
1089 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1091 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1092 // not the case for C90. Start the switch scope.
1095 // A name introduced by a declaration in a condition is in scope from its
1096 // point of declaration until the end of the substatements controlled by the
1099 // Names declared in the for-init-statement, and in the condition of if,
1100 // while, for, and switch statements are local to the if, while, for, or
1101 // switch statement (including the controlled statement).
1103 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
1105 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1106 ParseScope SwitchScope(this, ScopeFlags);
1108 // Parse the condition.
1111 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1115 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1117 if (Switch.isInvalid()) {
1118 // Skip the switch body.
1119 // FIXME: This is not optimal recovery, but parsing the body is more
1120 // dangerous due to the presence of case and default statements, which
1121 // will have no place to connect back with the switch.
1122 if (Tok.is(tok::l_brace)) {
1124 SkipUntil(tok::r_brace, false, false);
1126 SkipUntil(tok::semi);
1130 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1131 // there is no compound stmt. C90 does not have this clause. We only do this
1132 // if the body isn't a compound statement to avoid push/pop in common cases.
1135 // The substatement in a selection-statement (each substatement, in the else
1136 // form of the if statement) implicitly defines a local scope.
1138 // See comments in ParseIfStatement for why we create a scope for the
1139 // condition and a new scope for substatement in C++.
1141 ParseScope InnerScope(this, Scope::DeclScope,
1142 C99orCXX && Tok.isNot(tok::l_brace));
1144 // Read the body statement.
1145 StmtResult Body(ParseStatement(TrailingElseLoc));
1151 if (Body.isInvalid()) {
1152 // FIXME: Remove the case statement list from the Switch statement.
1154 // Put the synthesized null statement on the same line as the end of switch
1156 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1157 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1160 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1163 /// ParseWhileStatement
1164 /// while-statement: [C99 6.8.5.1]
1165 /// 'while' '(' expression ')' statement
1166 /// [C++] 'while' '(' condition ')' statement
1167 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1168 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1169 SourceLocation WhileLoc = Tok.getLocation();
1170 ConsumeToken(); // eat the 'while'.
1172 if (Tok.isNot(tok::l_paren)) {
1173 Diag(Tok, diag::err_expected_lparen_after) << "while";
1174 SkipUntil(tok::semi);
1178 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1180 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1181 // the case for C90. Start the loop scope.
1184 // A name introduced by a declaration in a condition is in scope from its
1185 // point of declaration until the end of the substatements controlled by the
1188 // Names declared in the for-init-statement, and in the condition of if,
1189 // while, for, and switch statements are local to the if, while, for, or
1190 // switch statement (including the controlled statement).
1192 unsigned ScopeFlags;
1194 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1195 Scope::DeclScope | Scope::ControlScope;
1197 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1198 ParseScope WhileScope(this, ScopeFlags);
1200 // Parse the condition.
1203 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1206 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
1208 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1209 // there is no compound stmt. C90 does not have this clause. We only do this
1210 // if the body isn't a compound statement to avoid push/pop in common cases.
1213 // The substatement in an iteration-statement implicitly defines a local scope
1214 // which is entered and exited each time through the loop.
1216 // See comments in ParseIfStatement for why we create a scope for the
1217 // condition and a new scope for substatement in C++.
1219 ParseScope InnerScope(this, Scope::DeclScope,
1220 C99orCXX && Tok.isNot(tok::l_brace));
1222 // Read the body statement.
1223 StmtResult Body(ParseStatement(TrailingElseLoc));
1225 // Pop the body scope if needed.
1229 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1232 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1235 /// ParseDoStatement
1236 /// do-statement: [C99 6.8.5.2]
1237 /// 'do' statement 'while' '(' expression ')' ';'
1238 /// Note: this lets the caller parse the end ';'.
1239 StmtResult Parser::ParseDoStatement() {
1240 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1241 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1243 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1244 // the case for C90. Start the loop scope.
1245 unsigned ScopeFlags;
1246 if (getLangOpts().C99)
1247 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1249 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1251 ParseScope DoScope(this, ScopeFlags);
1253 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1254 // there is no compound stmt. C90 does not have this clause. We only do this
1255 // if the body isn't a compound statement to avoid push/pop in common cases.
1258 // The substatement in an iteration-statement implicitly defines a local scope
1259 // which is entered and exited each time through the loop.
1261 ParseScope InnerScope(this, Scope::DeclScope,
1262 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
1263 Tok.isNot(tok::l_brace));
1265 // Read the body statement.
1266 StmtResult Body(ParseStatement());
1268 // Pop the body scope if needed.
1271 if (Tok.isNot(tok::kw_while)) {
1272 if (!Body.isInvalid()) {
1273 Diag(Tok, diag::err_expected_while);
1274 Diag(DoLoc, diag::note_matching) << "do";
1275 SkipUntil(tok::semi, false, true);
1279 SourceLocation WhileLoc = ConsumeToken();
1281 if (Tok.isNot(tok::l_paren)) {
1282 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1283 SkipUntil(tok::semi, false, true);
1287 // Parse the parenthesized condition.
1288 BalancedDelimiterTracker T(*this, tok::l_paren);
1291 // FIXME: Do not just parse the attribute contents and throw them away
1292 ParsedAttributesWithRange attrs(AttrFactory);
1293 MaybeParseCXX0XAttributes(attrs);
1294 ProhibitAttributes(attrs);
1296 ExprResult Cond = ParseExpression();
1300 if (Cond.isInvalid() || Body.isInvalid())
1303 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1304 Cond.get(), T.getCloseLocation());
1307 /// ParseForStatement
1308 /// for-statement: [C99 6.8.5.3]
1309 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1310 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1311 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1313 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
1314 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1315 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1317 /// [C++] for-init-statement:
1318 /// [C++] expression-statement
1319 /// [C++] simple-declaration
1321 /// [C++0x] for-range-declaration:
1322 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1323 /// [C++0x] for-range-initializer:
1324 /// [C++0x] expression
1325 /// [C++0x] braced-init-list [TODO]
1326 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1327 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1328 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1330 if (Tok.isNot(tok::l_paren)) {
1331 Diag(Tok, diag::err_expected_lparen_after) << "for";
1332 SkipUntil(tok::semi);
1336 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1337 getLangOpts().ObjC1;
1339 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1340 // the case for C90. Start the loop scope.
1343 // A name introduced by a declaration in a condition is in scope from its
1344 // point of declaration until the end of the substatements controlled by the
1347 // Names declared in the for-init-statement, and in the condition of if,
1348 // while, for, and switch statements are local to the if, while, for, or
1349 // switch statement (including the controlled statement).
1351 // Names declared in the for-init-statement are in the same declarative-region
1352 // as those declared in the condition.
1354 unsigned ScopeFlags;
1356 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1357 Scope::DeclScope | Scope::ControlScope;
1359 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1361 ParseScope ForScope(this, ScopeFlags);
1363 BalancedDelimiterTracker T(*this, tok::l_paren);
1368 bool ForEach = false, ForRange = false;
1369 StmtResult FirstPart;
1370 bool SecondPartIsInvalid = false;
1371 FullExprArg SecondPart(Actions);
1372 ExprResult Collection;
1373 ForRangeInit ForRangeInit;
1374 FullExprArg ThirdPart(Actions);
1375 Decl *SecondVar = 0;
1377 if (Tok.is(tok::code_completion)) {
1378 Actions.CodeCompleteOrdinaryName(getCurScope(),
1379 C99orCXXorObjC? Sema::PCC_ForInit
1380 : Sema::PCC_Expression);
1385 ParsedAttributesWithRange attrs(AttrFactory);
1386 MaybeParseCXX0XAttributes(attrs);
1388 // Parse the first part of the for specifier.
1389 if (Tok.is(tok::semi)) { // for (;
1390 ProhibitAttributes(attrs);
1391 // no first part, eat the ';'.
1393 } else if (isForInitDeclaration()) { // for (int X = 4;
1394 // Parse declaration, which eats the ';'.
1395 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1396 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1398 ParsedAttributesWithRange attrs(AttrFactory);
1399 MaybeParseCXX0XAttributes(attrs);
1401 // In C++0x, "for (T NS:a" might not be a typo for ::
1402 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1403 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1405 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1407 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
1408 DeclEnd, attrs, false,
1409 MightBeForRangeStmt ?
1411 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1413 if (ForRangeInit.ParsedForRangeDecl()) {
1414 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus0x ?
1415 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1418 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1420 } else if ((ForEach = isTokIdentifier_in())) {
1421 Actions.ActOnForEachDeclStmt(DG);
1422 // ObjC: for (id x in expr)
1423 ConsumeToken(); // consume 'in'
1425 if (Tok.is(tok::code_completion)) {
1426 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1430 Collection = ParseExpression();
1432 Diag(Tok, diag::err_expected_semi_for);
1435 ProhibitAttributes(attrs);
1436 Value = ParseExpression();
1438 ForEach = isTokIdentifier_in();
1440 // Turn the expression into a stmt.
1441 if (!Value.isInvalid()) {
1443 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1445 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1448 if (Tok.is(tok::semi)) {
1450 } else if (ForEach) {
1451 ConsumeToken(); // consume 'in'
1453 if (Tok.is(tok::code_completion)) {
1454 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1458 Collection = ParseExpression();
1459 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::colon) && FirstPart.get()) {
1460 // User tried to write the reasonable, but ill-formed, for-range-statement
1461 // for (expr : expr) { ... }
1462 Diag(Tok, diag::err_for_range_expected_decl)
1463 << FirstPart.get()->getSourceRange();
1464 SkipUntil(tok::r_paren, false, true);
1465 SecondPartIsInvalid = true;
1467 if (!Value.isInvalid()) {
1468 Diag(Tok, diag::err_expected_semi_for);
1470 // Skip until semicolon or rparen, don't consume it.
1471 SkipUntil(tok::r_paren, true, true);
1472 if (Tok.is(tok::semi))
1477 if (!ForEach && !ForRange) {
1478 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1479 // Parse the second part of the for specifier.
1480 if (Tok.is(tok::semi)) { // for (...;;
1482 } else if (Tok.is(tok::r_paren)) {
1483 // missing both semicolons.
1486 if (getLangOpts().CPlusPlus)
1487 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1489 Second = ParseExpression();
1490 if (!Second.isInvalid())
1491 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1494 SecondPartIsInvalid = Second.isInvalid();
1495 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
1498 if (Tok.isNot(tok::semi)) {
1499 if (!SecondPartIsInvalid || SecondVar)
1500 Diag(Tok, diag::err_expected_semi_for);
1502 // Skip until semicolon or rparen, don't consume it.
1503 SkipUntil(tok::r_paren, true, true);
1506 if (Tok.is(tok::semi)) {
1510 // Parse the third part of the for specifier.
1511 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1512 ExprResult Third = ParseExpression();
1513 ThirdPart = Actions.MakeFullExpr(Third.take());
1519 // We need to perform most of the semantic analysis for a C++0x for-range
1520 // statememt before parsing the body, in order to be able to deduce the type
1521 // of an auto-typed loop variable.
1522 StmtResult ForRangeStmt;
1523 StmtResult ForEachStmt;
1526 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
1527 ForRangeInit.ColonLoc,
1528 ForRangeInit.RangeExpr.get(),
1529 T.getCloseLocation(),
1533 // Similarly, we need to do the semantic analysis for a for-range
1534 // statement immediately in order to close over temporaries correctly.
1535 } else if (ForEach) {
1536 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1539 T.getCloseLocation());
1542 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1543 // there is no compound stmt. C90 does not have this clause. We only do this
1544 // if the body isn't a compound statement to avoid push/pop in common cases.
1547 // The substatement in an iteration-statement implicitly defines a local scope
1548 // which is entered and exited each time through the loop.
1550 // See comments in ParseIfStatement for why we create a scope for
1551 // for-init-statement/condition and a new scope for substatement in C++.
1553 ParseScope InnerScope(this, Scope::DeclScope,
1554 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1556 // Read the body statement.
1557 StmtResult Body(ParseStatement(TrailingElseLoc));
1559 // Pop the body scope if needed.
1562 // Leave the for-scope.
1565 if (Body.isInvalid())
1569 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1573 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1575 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1576 SecondPart, SecondVar, ThirdPart,
1577 T.getCloseLocation(), Body.take());
1580 /// ParseGotoStatement
1582 /// 'goto' identifier ';'
1583 /// [GNU] 'goto' '*' expression ';'
1585 /// Note: this lets the caller parse the end ';'.
1587 StmtResult Parser::ParseGotoStatement() {
1588 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1589 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1592 if (Tok.is(tok::identifier)) {
1593 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1595 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1597 } else if (Tok.is(tok::star)) {
1598 // GNU indirect goto extension.
1599 Diag(Tok, diag::ext_gnu_indirect_goto);
1600 SourceLocation StarLoc = ConsumeToken();
1601 ExprResult R(ParseExpression());
1602 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1603 SkipUntil(tok::semi, false, true);
1606 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1608 Diag(Tok, diag::err_expected_ident);
1615 /// ParseContinueStatement
1619 /// Note: this lets the caller parse the end ';'.
1621 StmtResult Parser::ParseContinueStatement() {
1622 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1623 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1626 /// ParseBreakStatement
1630 /// Note: this lets the caller parse the end ';'.
1632 StmtResult Parser::ParseBreakStatement() {
1633 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1634 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1637 /// ParseReturnStatement
1639 /// 'return' expression[opt] ';'
1640 StmtResult Parser::ParseReturnStatement() {
1641 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1642 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1645 if (Tok.isNot(tok::semi)) {
1646 if (Tok.is(tok::code_completion)) {
1647 Actions.CodeCompleteReturn(getCurScope());
1652 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1653 R = ParseInitializer();
1655 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus0x ?
1656 diag::warn_cxx98_compat_generalized_initializer_lists :
1657 diag::ext_generalized_initializer_lists)
1658 << R.get()->getSourceRange();
1660 R = ParseExpression();
1661 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1662 SkipUntil(tok::semi, false, true);
1666 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1669 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
1670 /// this routine is called to collect the tokens for an MS asm statement.
1672 /// [MS] ms-asm-statement:
1674 /// ms-asm-block ms-asm-statement
1676 /// [MS] ms-asm-block:
1677 /// '__asm' ms-asm-line '\n'
1678 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1680 /// [MS] ms-asm-instruction-block
1682 /// ms-asm-line '\n' ms-asm-instruction-block
1684 StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1685 // MS-style inline assembly is not fully supported, so emit a warning.
1686 Diag(AsmLoc, diag::warn_unsupported_msasm);
1688 SourceManager &SrcMgr = PP.getSourceManager();
1689 SourceLocation EndLoc = AsmLoc;
1690 SmallVector<Token, 4> AsmToks;
1692 bool InBraces = false;
1693 unsigned short savedBraceCount = 0;
1694 bool InAsmComment = false;
1696 unsigned LineNo = 0;
1697 unsigned NumTokensRead = 0;
1698 SourceLocation LBraceLoc;
1700 if (Tok.is(tok::l_brace)) {
1701 // Braced inline asm: consume the opening brace.
1703 savedBraceCount = BraceCount;
1704 EndLoc = LBraceLoc = ConsumeBrace();
1707 // Single-line inline asm; compute which line it is on.
1708 std::pair<FileID, unsigned> ExpAsmLoc =
1709 SrcMgr.getDecomposedExpansionLoc(EndLoc);
1710 FID = ExpAsmLoc.first;
1711 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
1714 SourceLocation TokLoc = Tok.getLocation();
1716 // If we hit EOF, we're done, period.
1717 if (Tok.is(tok::eof))
1720 if (!InAsmComment && Tok.is(tok::semi)) {
1721 // A semicolon in an asm is the start of a comment.
1722 InAsmComment = true;
1724 // Compute which line the comment is on.
1725 std::pair<FileID, unsigned> ExpSemiLoc =
1726 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1727 FID = ExpSemiLoc.first;
1728 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
1730 } else if (!InBraces || InAsmComment) {
1731 // If end-of-line is significant, check whether this token is on a
1733 std::pair<FileID, unsigned> ExpLoc =
1734 SrcMgr.getDecomposedExpansionLoc(TokLoc);
1735 if (ExpLoc.first != FID ||
1736 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
1737 // If this is a single-line __asm, we're done.
1740 // We're no longer in a comment.
1741 InAsmComment = false;
1742 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
1743 // Single-line asm always ends when a closing brace is seen.
1744 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
1745 // does MSVC do here?
1749 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
1750 BraceCount == (savedBraceCount + 1)) {
1751 // Consume the closing brace, and finish
1752 EndLoc = ConsumeBrace();
1756 // Consume the next token; make sure we don't modify the brace count etc.
1757 // if we are in a comment.
1762 AsmToks.push_back(Tok);
1765 TokLoc = Tok.getLocation();
1769 if (InBraces && BraceCount != savedBraceCount) {
1770 // __asm without closing brace (this can happen at EOF).
1771 Diag(Tok, diag::err_expected_rbrace);
1772 Diag(LBraceLoc, diag::note_matching) << "{";
1774 } else if (NumTokensRead == 0) {
1776 Diag(Tok, diag::err_expected_lbrace);
1780 // If MS-style inline assembly is disabled, then build an empty asm.
1781 if (!getLangOpts().EmitMicrosoftInlineAsm) {
1783 t.setKind(tok::string_literal);
1784 t.setLiteralData("\"/*FIXME: not done*/\"");
1785 t.clearFlag(Token::NeedsCleaning);
1787 ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1788 ExprVector Constraints;
1790 ExprVector Clobbers;
1791 return Actions.ActOnGCCAsmStmt(AsmLoc, true, true, 0, 0, 0, Constraints,
1792 Exprs, AsmString.take(), Clobbers, EndLoc);
1795 // FIXME: We should be passing source locations for better diagnostics.
1796 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc,
1797 llvm::makeArrayRef(AsmToks), EndLoc);
1800 /// ParseAsmStatement - Parse a GNU extended asm statement.
1802 /// gnu-asm-statement
1803 /// ms-asm-statement
1805 /// [GNU] gnu-asm-statement:
1806 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1808 /// [GNU] asm-argument:
1809 /// asm-string-literal
1810 /// asm-string-literal ':' asm-operands[opt]
1811 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1812 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1813 /// ':' asm-clobbers
1815 /// [GNU] asm-clobbers:
1816 /// asm-string-literal
1817 /// asm-clobbers ',' asm-string-literal
1819 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
1820 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1821 SourceLocation AsmLoc = ConsumeToken();
1823 if (getLangOpts().MicrosoftExt && Tok.isNot(tok::l_paren) &&
1824 !isTypeQualifier()) {
1826 return ParseMicrosoftAsmStatement(AsmLoc);
1828 DeclSpec DS(AttrFactory);
1829 SourceLocation Loc = Tok.getLocation();
1830 ParseTypeQualifierListOpt(DS, true, false);
1832 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1833 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1834 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1835 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1836 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1838 // Remember if this was a volatile asm.
1839 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1840 if (Tok.isNot(tok::l_paren)) {
1841 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1842 SkipUntil(tok::r_paren);
1845 BalancedDelimiterTracker T(*this, tok::l_paren);
1848 ExprResult AsmString(ParseAsmStringLiteral());
1849 if (AsmString.isInvalid()) {
1850 // Consume up to and including the closing paren.
1855 SmallVector<IdentifierInfo *, 4> Names;
1856 ExprVector Constraints;
1858 ExprVector Clobbers;
1860 if (Tok.is(tok::r_paren)) {
1861 // We have a simple asm expression like 'asm("foo")'.
1863 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1864 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1865 Constraints, Exprs, AsmString.take(),
1866 Clobbers, T.getCloseLocation());
1869 // Parse Outputs, if present.
1870 bool AteExtraColon = false;
1871 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1872 // In C++ mode, parse "::" like ": :".
1873 AteExtraColon = Tok.is(tok::coloncolon);
1876 if (!AteExtraColon &&
1877 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1881 unsigned NumOutputs = Names.size();
1883 // Parse Inputs, if present.
1884 if (AteExtraColon ||
1885 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1886 // In C++ mode, parse "::" like ": :".
1888 AteExtraColon = false;
1890 AteExtraColon = Tok.is(tok::coloncolon);
1894 if (!AteExtraColon &&
1895 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1899 assert(Names.size() == Constraints.size() &&
1900 Constraints.size() == Exprs.size() &&
1901 "Input operand size mismatch!");
1903 unsigned NumInputs = Names.size() - NumOutputs;
1905 // Parse the clobbers, if present.
1906 if (AteExtraColon || Tok.is(tok::colon)) {
1910 // Parse the asm-string list for clobbers if present.
1911 if (Tok.isNot(tok::r_paren)) {
1913 ExprResult Clobber(ParseAsmStringLiteral());
1915 if (Clobber.isInvalid())
1918 Clobbers.push_back(Clobber.release());
1920 if (Tok.isNot(tok::comma)) break;
1927 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
1928 NumInputs, Names.data(), Constraints, Exprs,
1929 AsmString.take(), Clobbers,
1930 T.getCloseLocation());
1933 /// ParseAsmOperands - Parse the asm-operands production as used by
1934 /// asm-statement, assuming the leading ':' token was eaten.
1936 /// [GNU] asm-operands:
1938 /// asm-operands ',' asm-operand
1940 /// [GNU] asm-operand:
1941 /// asm-string-literal '(' expression ')'
1942 /// '[' identifier ']' asm-string-literal '(' expression ')'
1945 // FIXME: Avoid unnecessary std::string trashing.
1946 bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1947 SmallVectorImpl<Expr *> &Constraints,
1948 SmallVectorImpl<Expr *> &Exprs) {
1949 // 'asm-operands' isn't present?
1950 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1954 // Read the [id] if present.
1955 if (Tok.is(tok::l_square)) {
1956 BalancedDelimiterTracker T(*this, tok::l_square);
1959 if (Tok.isNot(tok::identifier)) {
1960 Diag(Tok, diag::err_expected_ident);
1961 SkipUntil(tok::r_paren);
1965 IdentifierInfo *II = Tok.getIdentifierInfo();
1968 Names.push_back(II);
1973 ExprResult Constraint(ParseAsmStringLiteral());
1974 if (Constraint.isInvalid()) {
1975 SkipUntil(tok::r_paren);
1978 Constraints.push_back(Constraint.release());
1980 if (Tok.isNot(tok::l_paren)) {
1981 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1982 SkipUntil(tok::r_paren);
1986 // Read the parenthesized expression.
1987 BalancedDelimiterTracker T(*this, tok::l_paren);
1989 ExprResult Res(ParseExpression());
1991 if (Res.isInvalid()) {
1992 SkipUntil(tok::r_paren);
1995 Exprs.push_back(Res.release());
1996 // Eat the comma and continue parsing if it exists.
1997 if (Tok.isNot(tok::comma)) return false;
2002 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2003 assert(Tok.is(tok::l_brace));
2004 SourceLocation LBraceLoc = Tok.getLocation();
2006 if (SkipFunctionBodies && trySkippingFunctionBody()) {
2008 return Actions.ActOnFinishFunctionBody(Decl, 0);
2011 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2012 "parsing function body");
2014 // Do not enter a scope for the brace, as the arguments are in the same scope
2015 // (the function body) as the body itself. Instead, just read the statement
2016 // list and put it into a CompoundStmt for safe keeping.
2017 StmtResult FnBody(ParseCompoundStatementBody());
2019 // If the function body could not be parsed, make a bogus compoundstmt.
2020 if (FnBody.isInvalid()) {
2021 Sema::CompoundScopeRAII CompoundScope(Actions);
2022 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
2023 MultiStmtArg(), false);
2027 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
2030 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
2032 /// function-try-block:
2033 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2035 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2036 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2037 SourceLocation TryLoc = ConsumeToken();
2039 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2040 "parsing function try block");
2042 // Constructor initializer list?
2043 if (Tok.is(tok::colon))
2044 ParseConstructorInitializer(Decl);
2046 Actions.ActOnDefaultCtorInitializers(Decl);
2048 if (SkipFunctionBodies && trySkippingFunctionBody()) {
2050 return Actions.ActOnFinishFunctionBody(Decl, 0);
2053 SourceLocation LBraceLoc = Tok.getLocation();
2054 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2055 // If we failed to parse the try-catch, we just give the function an empty
2056 // compound statement as the body.
2057 if (FnBody.isInvalid()) {
2058 Sema::CompoundScopeRAII CompoundScope(Actions);
2059 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
2060 MultiStmtArg(), false);
2064 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
2067 bool Parser::trySkippingFunctionBody() {
2068 assert(Tok.is(tok::l_brace));
2069 assert(SkipFunctionBodies &&
2070 "Should only be called when SkipFunctionBodies is enabled");
2072 if (!PP.isCodeCompletionEnabled()) {
2074 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false);
2078 // We're in code-completion mode. Skip parsing for all function bodies unless
2079 // the body contains the code-completion point.
2080 TentativeParsingAction PA(*this);
2082 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
2083 /*StopAtCodeCompletion=*/true)) {
2092 /// ParseCXXTryBlock - Parse a C++ try-block.
2095 /// 'try' compound-statement handler-seq
2097 StmtResult Parser::ParseCXXTryBlock() {
2098 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2100 SourceLocation TryLoc = ConsumeToken();
2101 return ParseCXXTryBlockCommon(TryLoc);
2104 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2105 /// function-try-block.
2108 /// 'try' compound-statement handler-seq
2110 /// function-try-block:
2111 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2114 /// handler handler-seq[opt]
2116 /// [Borland] try-block:
2117 /// 'try' compound-statement seh-except-block
2118 /// 'try' compound-statment seh-finally-block
2120 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2121 if (Tok.isNot(tok::l_brace))
2122 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2123 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2125 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2127 (FnTry ? Scope::FnTryScope : Scope::TryScope)));
2128 if (TryBlock.isInvalid())
2131 // Borland allows SEH-handlers with 'try'
2133 if ((Tok.is(tok::identifier) &&
2134 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2135 Tok.is(tok::kw___finally)) {
2136 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2138 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2139 SourceLocation Loc = ConsumeToken();
2140 Handler = ParseSEHExceptBlock(Loc);
2143 SourceLocation Loc = ConsumeToken();
2144 Handler = ParseSEHFinallyBlock(Loc);
2146 if(Handler.isInvalid())
2149 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2155 StmtVector Handlers;
2156 ParsedAttributesWithRange attrs(AttrFactory);
2157 MaybeParseCXX0XAttributes(attrs);
2158 ProhibitAttributes(attrs);
2160 if (Tok.isNot(tok::kw_catch))
2161 return StmtError(Diag(Tok, diag::err_expected_catch));
2162 while (Tok.is(tok::kw_catch)) {
2163 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2164 if (!Handler.isInvalid())
2165 Handlers.push_back(Handler.release());
2167 // Don't bother creating the full statement if we don't have any usable
2169 if (Handlers.empty())
2172 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(),Handlers);
2176 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2179 /// 'catch' '(' exception-declaration ')' compound-statement
2181 /// exception-declaration:
2182 /// type-specifier-seq declarator
2183 /// type-specifier-seq abstract-declarator
2184 /// type-specifier-seq
2187 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2188 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2190 SourceLocation CatchLoc = ConsumeToken();
2192 BalancedDelimiterTracker T(*this, tok::l_paren);
2193 if (T.expectAndConsume(diag::err_expected_lparen))
2197 // The name in a catch exception-declaration is local to the handler and
2198 // shall not be redeclared in the outermost block of the handler.
2199 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2200 (FnCatch ? Scope::FnCatchScope : Scope::CatchScope));
2202 // exception-declaration is equivalent to '...' or a parameter-declaration
2203 // without default arguments.
2204 Decl *ExceptionDecl = 0;
2205 if (Tok.isNot(tok::ellipsis)) {
2206 DeclSpec DS(AttrFactory);
2207 if (ParseCXXTypeSpecifierSeq(DS))
2209 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2210 ParseDeclarator(ExDecl);
2211 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2216 if (T.getCloseLocation().isInvalid())
2219 if (Tok.isNot(tok::l_brace))
2220 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2222 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2223 StmtResult Block(ParseCompoundStatement());
2224 if (Block.isInvalid())
2227 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
2230 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2231 IfExistsCondition Result;
2232 if (ParseMicrosoftIfExistsCondition(Result))
2235 // Handle dependent statements by parsing the braces as a compound statement.
2236 // This is not the same behavior as Visual C++, which don't treat this as a
2237 // compound statement, but for Clang's type checking we can't have anything
2238 // inside these braces escaping to the surrounding code.
2239 if (Result.Behavior == IEB_Dependent) {
2240 if (!Tok.is(tok::l_brace)) {
2241 Diag(Tok, diag::err_expected_lbrace);
2245 StmtResult Compound = ParseCompoundStatement();
2246 if (Compound.isInvalid())
2249 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2254 if (DepResult.isUsable())
2255 Stmts.push_back(DepResult.get());
2259 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2260 if (Braces.consumeOpen()) {
2261 Diag(Tok, diag::err_expected_lbrace);
2265 switch (Result.Behavior) {
2267 // Parse the statements below.
2271 llvm_unreachable("Dependent case handled above");
2278 // Condition is true, parse the statements.
2279 while (Tok.isNot(tok::r_brace)) {
2280 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2282 Stmts.push_back(R.release());
2284 Braces.consumeClose();