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/Basic/Diagnostic.h"
21 #include "clang/Basic/PrettyStackTrace.h"
22 #include "clang/Basic/SourceManager.h"
23 using namespace clang;
25 //===----------------------------------------------------------------------===//
26 // C99 6.8: Statements and Blocks.
27 //===----------------------------------------------------------------------===//
29 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
30 /// StatementOrDeclaration:
36 /// compound-statement
37 /// expression-statement
38 /// selection-statement
39 /// iteration-statement
41 /// [C++] declaration-statement
43 /// [MS] seh-try-block
44 /// [OBC] objc-throw-statement
45 /// [OBC] objc-try-catch-statement
46 /// [OBC] objc-synchronized-statement
47 /// [GNU] asm-statement
48 /// [OMP] openmp-construct [TODO]
50 /// labeled-statement:
51 /// identifier ':' statement
52 /// 'case' constant-expression ':' statement
53 /// 'default' ':' statement
55 /// selection-statement:
59 /// iteration-statement:
64 /// expression-statement:
65 /// expression[opt] ';'
68 /// 'goto' identifier ';'
71 /// 'return' expression[opt] ';'
72 /// [GNU] 'goto' '*' expression ';'
74 /// [OBC] objc-throw-statement:
75 /// [OBC] '@' 'throw' expression ';'
76 /// [OBC] '@' 'throw' ';'
79 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement) {
80 const char *SemiError = 0;
83 ParenBraceBracketBalancer BalancerRAIIObj(*this);
85 ParsedAttributesWithRange attrs(AttrFactory);
86 MaybeParseCXX0XAttributes(attrs);
88 // Cases in this switch statement should fall through if the parser expects
89 // the token to end in a semicolon (in which case SemiError should be set),
90 // or they directly 'return;' if not.
92 tok::TokenKind Kind = Tok.getKind();
95 case tok::at: // May be a @try or @throw statement
97 AtLoc = ConsumeToken(); // consume @
98 return ParseObjCAtStatement(AtLoc);
101 case tok::code_completion:
102 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
103 ConsumeCodeCompletionToken();
104 return ParseStatementOrDeclaration(Stmts, OnlyStatement);
106 case tok::identifier: {
107 Token Next = NextToken();
108 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
109 // identifier ':' statement
110 return ParseLabeledStatement(attrs);
113 if (Next.isNot(tok::coloncolon)) {
115 IdentifierInfo *Name = Tok.getIdentifierInfo();
116 SourceLocation NameLoc = Tok.getLocation();
117 Sema::NameClassification Classification
118 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next);
119 switch (Classification.getKind()) {
120 case Sema::NC_Keyword:
121 // The identifier was corrected to a keyword. Update the token
122 // to this keyword, and try again.
123 if (Name->getTokenID() != tok::identifier) {
124 Tok.setIdentifierInfo(Name);
125 Tok.setKind(Name->getTokenID());
129 // Fall through via the normal error path.
130 // FIXME: This seems like it could only happen for context-sensitive
134 // Handle errors here by skipping up to the next semicolon or '}', and
135 // eat the semicolon if that's what stopped us.
136 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
137 if (Tok.is(tok::semi))
141 case Sema::NC_Unknown:
142 // Either we don't know anything about this identifier, or we know that
143 // we're in a syntactic context we haven't handled yet.
147 Tok.setKind(tok::annot_typename);
148 setTypeAnnotation(Tok, Classification.getType());
149 Tok.setAnnotationEndLoc(NameLoc);
150 PP.AnnotateCachedTokens(Tok);
153 case Sema::NC_Expression:
154 Tok.setKind(tok::annot_primary_expr);
155 setExprAnnotation(Tok, Classification.getExpression());
156 Tok.setAnnotationEndLoc(NameLoc);
157 PP.AnnotateCachedTokens(Tok);
160 case Sema::NC_TypeTemplate:
161 case Sema::NC_FunctionTemplate: {
162 ConsumeToken(); // the identifier
164 Id.setIdentifier(Name, NameLoc);
165 if (AnnotateTemplateIdToken(
166 TemplateTy::make(Classification.getTemplateName()),
167 Classification.getTemplateNameKind(),
168 SS, Id, SourceLocation(),
169 /*AllowTypeAnnotation=*/false)) {
170 // Handle errors here by skipping up to the next semicolon or '}', and
171 // eat the semicolon if that's what stopped us.
172 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
173 if (Tok.is(tok::semi))
178 // If the next token is '::', jump right into parsing a
179 // nested-name-specifier. We don't want to leave the template-id
181 if (NextToken().is(tok::coloncolon) && TryAnnotateCXXScopeToken(false)){
182 // Handle errors here by skipping up to the next semicolon or '}', and
183 // eat the semicolon if that's what stopped us.
184 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
185 if (Tok.is(tok::semi))
190 // We've annotated a template-id, so try again now.
194 case Sema::NC_NestedNameSpecifier:
195 // FIXME: Implement this!
204 if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
205 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
206 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
208 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
211 if (Tok.is(tok::r_brace)) {
212 Diag(Tok, diag::err_expected_statement);
216 return ParseExprStatement(attrs);
219 case tok::kw_case: // C99 6.8.1: labeled-statement
220 return ParseCaseStatement(attrs);
221 case tok::kw_default: // C99 6.8.1: labeled-statement
222 return ParseDefaultStatement(attrs);
224 case tok::l_brace: // C99 6.8.2: compound-statement
225 return ParseCompoundStatement(attrs);
226 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
227 SourceLocation LeadingEmptyMacroLoc;
228 if (Tok.hasLeadingEmptyMacro())
229 LeadingEmptyMacroLoc = PP.getLastEmptyMacroExpansionLoc();
230 return Actions.ActOnNullStmt(ConsumeToken(), LeadingEmptyMacroLoc);
233 case tok::kw_if: // C99 6.8.4.1: if-statement
234 return ParseIfStatement(attrs);
235 case tok::kw_switch: // C99 6.8.4.2: switch-statement
236 return ParseSwitchStatement(attrs);
238 case tok::kw_while: // C99 6.8.5.1: while-statement
239 return ParseWhileStatement(attrs);
240 case tok::kw_do: // C99 6.8.5.2: do-statement
241 Res = ParseDoStatement(attrs);
242 SemiError = "do/while";
244 case tok::kw_for: // C99 6.8.5.3: for-statement
245 return ParseForStatement(attrs);
247 case tok::kw_goto: // C99 6.8.6.1: goto-statement
248 Res = ParseGotoStatement(attrs);
251 case tok::kw_continue: // C99 6.8.6.2: continue-statement
252 Res = ParseContinueStatement(attrs);
253 SemiError = "continue";
255 case tok::kw_break: // C99 6.8.6.3: break-statement
256 Res = ParseBreakStatement(attrs);
259 case tok::kw_return: // C99 6.8.6.4: return-statement
260 Res = ParseReturnStatement(attrs);
261 SemiError = "return";
265 ProhibitAttributes(attrs);
267 Res = ParseAsmStatement(msAsm);
268 Res = Actions.ActOnFinishFullStmt(Res.get());
269 if (msAsm) return move(Res);
274 case tok::kw_try: // C++ 15: try-block
275 return ParseCXXTryBlock(attrs);
278 return ParseSEHTryBlock(attrs);
281 // If we reached this code, the statement must end in a semicolon.
282 if (Tok.is(tok::semi)) {
284 } else if (!Res.isInvalid()) {
285 // If the result was valid, then we do want to diagnose this. Use
286 // ExpectAndConsume to emit the diagnostic, even though we know it won't
288 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
289 // Skip until we see a } or ;, but don't eat it.
290 SkipUntil(tok::r_brace, true, true);
296 /// \brief Parse an expression statement.
297 StmtResult Parser::ParseExprStatement(ParsedAttributes &Attrs) {
298 // If a case keyword is missing, this is where it should be inserted.
299 Token OldToken = Tok;
301 // FIXME: Use the attributes
302 // expression[opt] ';'
303 ExprResult Expr(ParseExpression());
304 if (Expr.isInvalid()) {
305 // If the expression is invalid, skip ahead to the next semicolon or '}'.
306 // Not doing this opens us up to the possibility of infinite loops if
307 // ParseExpression does not consume any tokens.
308 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
309 if (Tok.is(tok::semi))
314 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
315 Actions.CheckCaseExpression(Expr.get())) {
316 // If a constant expression is followed by a colon inside a switch block,
317 // suggest a missing case keyword.
318 Diag(OldToken, diag::err_expected_case_before_expression)
319 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
321 // Recover parsing as a case statement.
322 return ParseCaseStatement(Attrs, /*MissingCase=*/true, Expr);
325 // Otherwise, eat the semicolon.
326 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
327 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
330 StmtResult Parser::ParseSEHTryBlock(ParsedAttributes & Attrs) {
331 assert(Tok.is(tok::kw___try) && "Expected '__try'");
332 SourceLocation Loc = ConsumeToken();
333 return ParseSEHTryBlockCommon(Loc);
336 /// ParseSEHTryBlockCommon
339 /// '__try' compound-statement seh-handler
343 /// seh-finally-block
345 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
346 if(Tok.isNot(tok::l_brace))
347 return StmtError(Diag(Tok,diag::err_expected_lbrace));
349 ParsedAttributesWithRange attrs(AttrFactory);
350 StmtResult TryBlock(ParseCompoundStatement(attrs));
351 if(TryBlock.isInvalid())
352 return move(TryBlock);
355 if(Tok.is(tok::kw___except)) {
356 SourceLocation Loc = ConsumeToken();
357 Handler = ParseSEHExceptBlock(Loc);
358 } else if (Tok.is(tok::kw___finally)) {
359 SourceLocation Loc = ConsumeToken();
360 Handler = ParseSEHFinallyBlock(Loc);
362 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
365 if(Handler.isInvalid())
366 return move(Handler);
368 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
374 /// ParseSEHExceptBlock - Handle __except
376 /// seh-except-block:
377 /// '__except' '(' seh-filter-expression ')' compound-statement
379 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
380 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
381 raii2(Ident___exception_code, false),
382 raii3(Ident_GetExceptionCode, false);
384 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
387 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
389 if (getLang().Borland) {
390 Ident__exception_info->setIsPoisoned(false);
391 Ident___exception_info->setIsPoisoned(false);
392 Ident_GetExceptionInfo->setIsPoisoned(false);
394 ExprResult FilterExpr(ParseExpression());
396 if (getLang().Borland) {
397 Ident__exception_info->setIsPoisoned(true);
398 Ident___exception_info->setIsPoisoned(true);
399 Ident_GetExceptionInfo->setIsPoisoned(true);
402 if(FilterExpr.isInvalid())
405 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
408 ParsedAttributesWithRange attrs(AttrFactory);
409 StmtResult Block(ParseCompoundStatement(attrs));
411 if(Block.isInvalid())
414 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
417 /// ParseSEHFinallyBlock - Handle __finally
419 /// seh-finally-block:
420 /// '__finally' compound-statement
422 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
423 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
424 raii2(Ident___abnormal_termination, false),
425 raii3(Ident_AbnormalTermination, false);
427 ParsedAttributesWithRange attrs(AttrFactory);
428 StmtResult Block(ParseCompoundStatement(attrs));
429 if(Block.isInvalid())
432 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
435 /// ParseLabeledStatement - We have an identifier and a ':' after it.
437 /// labeled-statement:
438 /// identifier ':' statement
439 /// [GNU] identifier ':' attributes[opt] statement
441 StmtResult Parser::ParseLabeledStatement(ParsedAttributes &attrs) {
442 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
443 "Not an identifier!");
445 Token IdentTok = Tok; // Save the whole token.
446 ConsumeToken(); // eat the identifier.
448 assert(Tok.is(tok::colon) && "Not a label!");
450 // identifier ':' statement
451 SourceLocation ColonLoc = ConsumeToken();
453 // Read label attributes, if present.
454 MaybeParseGNUAttributes(attrs);
456 StmtResult SubStmt(ParseStatement());
458 // Broken substmt shouldn't prevent the label from being added to the AST.
459 if (SubStmt.isInvalid())
460 SubStmt = Actions.ActOnNullStmt(ColonLoc);
462 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
463 IdentTok.getLocation());
464 if (AttributeList *Attrs = attrs.getList())
465 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
467 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
471 /// ParseCaseStatement
472 /// labeled-statement:
473 /// 'case' constant-expression ':' statement
474 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
476 StmtResult Parser::ParseCaseStatement(ParsedAttributes &attrs, bool MissingCase,
478 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
479 // FIXME: Use attributes?
481 // It is very very common for code to contain many case statements recursively
482 // nested, as in (but usually without indentation):
489 // Parsing this naively works, but is both inefficient and can cause us to run
490 // out of stack space in our recursive descent parser. As a special case,
491 // flatten this recursion into an iterative loop. This is complex and gross,
492 // but all the grossness is constrained to ParseCaseStatement (and some
493 // wierdness in the actions), so this is just local grossness :).
495 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
497 StmtResult TopLevelCase(true);
499 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
500 // gets updated each time a new case is parsed, and whose body is unset so
501 // far. When parsing 'case 4', this is the 'case 3' node.
502 StmtTy *DeepestParsedCaseStmt = 0;
504 // While we have case statements, eat and stack them.
505 SourceLocation ColonLoc;
507 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
508 ConsumeToken(); // eat the 'case'.
510 if (Tok.is(tok::code_completion)) {
511 Actions.CodeCompleteCase(getCurScope());
512 ConsumeCodeCompletionToken();
515 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
516 /// Disable this form of error recovery while we're parsing the case
518 ColonProtectionRAIIObject ColonProtection(*this);
520 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
522 if (LHS.isInvalid()) {
523 SkipUntil(tok::colon);
527 // GNU case range extension.
528 SourceLocation DotDotDotLoc;
530 if (Tok.is(tok::ellipsis)) {
531 Diag(Tok, diag::ext_gnu_case_range);
532 DotDotDotLoc = ConsumeToken();
534 RHS = ParseConstantExpression();
535 if (RHS.isInvalid()) {
536 SkipUntil(tok::colon);
541 ColonProtection.restore();
543 if (Tok.is(tok::colon)) {
544 ColonLoc = ConsumeToken();
546 // Treat "case blah;" as a typo for "case blah:".
547 } else if (Tok.is(tok::semi)) {
548 ColonLoc = ConsumeToken();
549 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
550 << FixItHint::CreateReplacement(ColonLoc, ":");
552 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
553 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
554 << FixItHint::CreateInsertion(ExpectedLoc, ":");
555 ColonLoc = ExpectedLoc;
559 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
560 RHS.get(), ColonLoc);
562 // If we had a sema error parsing this case, then just ignore it and
563 // continue parsing the sub-stmt.
564 if (Case.isInvalid()) {
565 if (TopLevelCase.isInvalid()) // No parsed case stmts.
566 return ParseStatement();
567 // Otherwise, just don't add it as a nested case.
569 // If this is the first case statement we parsed, it becomes TopLevelCase.
570 // Otherwise we link it into the current chain.
571 Stmt *NextDeepest = Case.get();
572 if (TopLevelCase.isInvalid())
573 TopLevelCase = move(Case);
575 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
576 DeepestParsedCaseStmt = NextDeepest;
579 // Handle all case statements.
580 } while (Tok.is(tok::kw_case));
582 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
584 // If we found a non-case statement, start by parsing it.
587 if (Tok.isNot(tok::r_brace)) {
588 SubStmt = ParseStatement();
590 // Nicely diagnose the common error "switch (X) { case 4: }", which is
592 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
593 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement);
597 // Broken sub-stmt shouldn't prevent forming the case statement properly.
598 if (SubStmt.isInvalid())
599 SubStmt = Actions.ActOnNullStmt(SourceLocation());
601 // Install the body into the most deeply-nested case.
602 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
604 // Return the top level parsed statement tree.
605 return move(TopLevelCase);
608 /// ParseDefaultStatement
609 /// labeled-statement:
610 /// 'default' ':' statement
611 /// Note that this does not parse the 'statement' at the end.
613 StmtResult Parser::ParseDefaultStatement(ParsedAttributes &attrs) {
614 //FIXME: Use attributes?
616 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
617 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
619 SourceLocation ColonLoc;
620 if (Tok.is(tok::colon)) {
621 ColonLoc = ConsumeToken();
623 // Treat "default;" as a typo for "default:".
624 } else if (Tok.is(tok::semi)) {
625 ColonLoc = ConsumeToken();
626 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
627 << FixItHint::CreateReplacement(ColonLoc, ":");
629 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
630 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
631 << FixItHint::CreateInsertion(ExpectedLoc, ":");
632 ColonLoc = ExpectedLoc;
635 // Diagnose the common error "switch (X) {... default: }", which is not valid.
636 if (Tok.is(tok::r_brace)) {
637 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
638 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement);
642 StmtResult SubStmt(ParseStatement());
643 if (SubStmt.isInvalid())
646 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
647 SubStmt.get(), getCurScope());
650 StmtResult Parser::ParseCompoundStatement(ParsedAttributes &Attr,
652 return ParseCompoundStatement(Attr, isStmtExpr, Scope::DeclScope);
655 /// ParseCompoundStatement - Parse a "{}" block.
657 /// compound-statement: [C99 6.8.2]
658 /// { block-item-list[opt] }
659 /// [GNU] { label-declarations block-item-list } [TODO]
663 /// block-item-list block-item
667 /// [GNU] '__extension__' declaration
669 /// [OMP] openmp-directive [TODO]
671 /// [GNU] label-declarations:
672 /// [GNU] label-declaration
673 /// [GNU] label-declarations label-declaration
675 /// [GNU] label-declaration:
676 /// [GNU] '__label__' identifier-list ';'
678 /// [OMP] openmp-directive: [TODO]
679 /// [OMP] barrier-directive
680 /// [OMP] flush-directive
682 StmtResult Parser::ParseCompoundStatement(ParsedAttributes &attrs,
684 unsigned ScopeFlags) {
685 //FIXME: Use attributes?
687 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
689 // Enter a scope to hold everything within the compound stmt. Compound
690 // statements can always hold declarations.
691 ParseScope CompoundScope(this, ScopeFlags);
693 // Parse the statements in the body.
694 return ParseCompoundStatementBody(isStmtExpr);
698 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
699 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
700 /// consume the '}' at the end of the block. It does not manipulate the scope
702 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
703 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
705 "in compound statement ('{}')");
706 InMessageExpressionRAIIObject InMessage(*this, false);
708 SourceLocation LBraceLoc = ConsumeBrace(); // eat the '{'.
710 StmtVector Stmts(Actions);
712 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
713 // only allowed at the start of a compound stmt regardless of the language.
714 while (Tok.is(tok::kw___label__)) {
715 SourceLocation LabelLoc = ConsumeToken();
716 Diag(LabelLoc, diag::ext_gnu_local_label);
718 llvm::SmallVector<Decl *, 8> DeclsInGroup;
720 if (Tok.isNot(tok::identifier)) {
721 Diag(Tok, diag::err_expected_ident);
725 IdentifierInfo *II = Tok.getIdentifierInfo();
726 SourceLocation IdLoc = ConsumeToken();
727 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
729 if (!Tok.is(tok::comma))
734 DeclSpec DS(AttrFactory);
735 DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
736 DeclsInGroup.data(), DeclsInGroup.size());
737 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
739 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
741 Stmts.push_back(R.release());
744 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
745 if (Tok.is(tok::annot_pragma_unused)) {
746 HandlePragmaUnused();
750 if (getLang().Microsoft && (Tok.is(tok::kw___if_exists) ||
751 Tok.is(tok::kw___if_not_exists))) {
752 ParseMicrosoftIfExistsStatement(Stmts);
757 if (Tok.isNot(tok::kw___extension__)) {
758 R = ParseStatementOrDeclaration(Stmts, false);
760 // __extension__ can start declarations and it can also be a unary
761 // operator for expressions. Consume multiple __extension__ markers here
762 // until we can determine which is which.
763 // FIXME: This loses extension expressions in the AST!
764 SourceLocation ExtLoc = ConsumeToken();
765 while (Tok.is(tok::kw___extension__))
768 ParsedAttributesWithRange attrs(AttrFactory);
769 MaybeParseCXX0XAttributes(attrs);
771 // If this is the start of a declaration, parse it as such.
772 if (isDeclarationStatement()) {
773 // __extension__ silences extension warnings in the subdeclaration.
774 // FIXME: Save the __extension__ on the decl as a node somehow?
775 ExtensionRAIIObject O(Diags);
777 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
778 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
779 Declarator::BlockContext, DeclEnd,
781 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
783 // Otherwise this was a unary __extension__ marker.
784 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
786 if (Res.isInvalid()) {
787 SkipUntil(tok::semi);
791 // FIXME: Use attributes?
792 // Eat the semicolon at the end of stmt and convert the expr into a
794 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
795 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
800 Stmts.push_back(R.release());
803 // We broke out of the while loop because we found a '}' or EOF.
804 if (Tok.isNot(tok::r_brace)) {
805 Diag(Tok, diag::err_expected_rbrace);
806 Diag(LBraceLoc, diag::note_matching) << "{";
810 SourceLocation RBraceLoc = ConsumeBrace();
811 return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
815 /// ParseParenExprOrCondition:
816 /// [C ] '(' expression ')'
817 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
819 /// This function parses and performs error recovery on the specified condition
820 /// or expression (depending on whether we're in C++ or C mode). This function
821 /// goes out of its way to recover well. It returns true if there was a parser
822 /// error (the right paren couldn't be found), which indicates that the caller
823 /// should try to recover harder. It returns false if the condition is
824 /// successfully parsed. Note that a successful parse can still have semantic
825 /// errors in the condition.
826 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
829 bool ConvertToBoolean) {
830 SourceLocation LParenLoc = ConsumeParen();
831 if (getLang().CPlusPlus)
832 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
834 ExprResult = ParseExpression();
837 // If required, convert to a boolean value.
838 if (!ExprResult.isInvalid() && ConvertToBoolean)
840 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
843 // If the parser was confused by the condition and we don't have a ')', try to
844 // recover by skipping ahead to a semi and bailing out. If condexp is
845 // semantically invalid but we have well formed code, keep going.
846 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
847 SkipUntil(tok::semi);
848 // Skipping may have stopped if it found the containing ')'. If so, we can
849 // continue parsing the if statement.
850 if (Tok.isNot(tok::r_paren))
854 // Otherwise the condition is valid or the rparen is present.
855 MatchRHSPunctuation(tok::r_paren, LParenLoc);
861 /// if-statement: [C99 6.8.4.1]
862 /// 'if' '(' expression ')' statement
863 /// 'if' '(' expression ')' statement 'else' statement
864 /// [C++] 'if' '(' condition ')' statement
865 /// [C++] 'if' '(' condition ')' statement 'else' statement
867 StmtResult Parser::ParseIfStatement(ParsedAttributes &attrs) {
868 // FIXME: Use attributes?
870 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
871 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
873 if (Tok.isNot(tok::l_paren)) {
874 Diag(Tok, diag::err_expected_lparen_after) << "if";
875 SkipUntil(tok::semi);
879 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
881 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
885 // A name introduced by a declaration in a condition is in scope from its
886 // point of declaration until the end of the substatements controlled by the
889 // Names declared in the for-init-statement, and in the condition of if,
890 // while, for, and switch statements are local to the if, while, for, or
891 // switch statement (including the controlled statement).
893 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
895 // Parse the condition.
898 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
901 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
903 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
904 // there is no compound stmt. C90 does not have this clause. We only do this
905 // if the body isn't a compound statement to avoid push/pop in common cases.
908 // The substatement in a selection-statement (each substatement, in the else
909 // form of the if statement) implicitly defines a local scope.
911 // For C++ we create a scope for the condition and a new scope for
912 // substatements because:
913 // -When the 'then' scope exits, we want the condition declaration to still be
914 // active for the 'else' scope too.
915 // -Sema will detect name clashes by considering declarations of a
916 // 'ControlScope' as part of its direct subscope.
917 // -If we wanted the condition and substatement to be in the same scope, we
918 // would have to notify ParseStatement not to create a new scope. It's
919 // simpler to let it create a new scope.
921 ParseScope InnerScope(this, Scope::DeclScope,
922 C99orCXX && Tok.isNot(tok::l_brace));
924 // Read the 'then' stmt.
925 SourceLocation ThenStmtLoc = Tok.getLocation();
926 StmtResult ThenStmt(ParseStatement());
928 // Pop the 'if' scope if needed.
931 // If it has an else, parse it.
932 SourceLocation ElseLoc;
933 SourceLocation ElseStmtLoc;
936 if (Tok.is(tok::kw_else)) {
937 ElseLoc = ConsumeToken();
938 ElseStmtLoc = Tok.getLocation();
940 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
941 // there is no compound stmt. C90 does not have this clause. We only do
942 // this if the body isn't a compound statement to avoid push/pop in common
946 // The substatement in a selection-statement (each substatement, in the else
947 // form of the if statement) implicitly defines a local scope.
949 ParseScope InnerScope(this, Scope::DeclScope,
950 C99orCXX && Tok.isNot(tok::l_brace));
952 ElseStmt = ParseStatement();
954 // Pop the 'else' scope if needed.
960 // If the condition was invalid, discard the if statement. We could recover
961 // better by replacing it with a valid expr, but don't do that yet.
962 if (CondExp.isInvalid() && !CondVar)
965 // If the then or else stmt is invalid and the other is valid (and present),
966 // make turn the invalid one into a null stmt to avoid dropping the other
967 // part. If both are invalid, return error.
968 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
969 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
970 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
971 // Both invalid, or one is invalid and other is non-present: return error.
975 // Now if either are invalid, replace with a ';'.
976 if (ThenStmt.isInvalid())
977 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
978 if (ElseStmt.isInvalid())
979 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
981 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
982 ElseLoc, ElseStmt.get());
985 /// ParseSwitchStatement
986 /// switch-statement:
987 /// 'switch' '(' expression ')' statement
988 /// [C++] 'switch' '(' condition ')' statement
989 StmtResult Parser::ParseSwitchStatement(ParsedAttributes &attrs) {
990 // FIXME: Use attributes?
992 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
993 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
995 if (Tok.isNot(tok::l_paren)) {
996 Diag(Tok, diag::err_expected_lparen_after) << "switch";
997 SkipUntil(tok::semi);
1001 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
1003 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1004 // not the case for C90. Start the switch scope.
1007 // A name introduced by a declaration in a condition is in scope from its
1008 // point of declaration until the end of the substatements controlled by the
1011 // Names declared in the for-init-statement, and in the condition of if,
1012 // while, for, and switch statements are local to the if, while, for, or
1013 // switch statement (including the controlled statement).
1015 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
1017 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1018 ParseScope SwitchScope(this, ScopeFlags);
1020 // Parse the condition.
1023 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1027 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1029 if (Switch.isInvalid()) {
1030 // Skip the switch body.
1031 // FIXME: This is not optimal recovery, but parsing the body is more
1032 // dangerous due to the presence of case and default statements, which
1033 // will have no place to connect back with the switch.
1034 if (Tok.is(tok::l_brace)) {
1036 SkipUntil(tok::r_brace, false, false);
1038 SkipUntil(tok::semi);
1039 return move(Switch);
1042 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1043 // there is no compound stmt. C90 does not have this clause. We only do this
1044 // if the body isn't a compound statement to avoid push/pop in common cases.
1047 // The substatement in a selection-statement (each substatement, in the else
1048 // form of the if statement) implicitly defines a local scope.
1050 // See comments in ParseIfStatement for why we create a scope for the
1051 // condition and a new scope for substatement in C++.
1053 ParseScope InnerScope(this, Scope::DeclScope,
1054 C99orCXX && Tok.isNot(tok::l_brace));
1056 // Read the body statement.
1057 StmtResult Body(ParseStatement());
1063 if (Body.isInvalid())
1064 // FIXME: Remove the case statement list from the Switch statement.
1065 Body = Actions.ActOnNullStmt(Tok.getLocation());
1067 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1070 /// ParseWhileStatement
1071 /// while-statement: [C99 6.8.5.1]
1072 /// 'while' '(' expression ')' statement
1073 /// [C++] 'while' '(' condition ')' statement
1074 StmtResult Parser::ParseWhileStatement(ParsedAttributes &attrs) {
1075 // FIXME: Use attributes?
1077 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1078 SourceLocation WhileLoc = Tok.getLocation();
1079 ConsumeToken(); // eat the 'while'.
1081 if (Tok.isNot(tok::l_paren)) {
1082 Diag(Tok, diag::err_expected_lparen_after) << "while";
1083 SkipUntil(tok::semi);
1087 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
1089 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1090 // the case for C90. Start the loop scope.
1093 // A name introduced by a declaration in a condition is in scope from its
1094 // point of declaration until the end of the substatements controlled by the
1097 // Names declared in the for-init-statement, and in the condition of if,
1098 // while, for, and switch statements are local to the if, while, for, or
1099 // switch statement (including the controlled statement).
1101 unsigned ScopeFlags;
1103 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1104 Scope::DeclScope | Scope::ControlScope;
1106 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1107 ParseScope WhileScope(this, ScopeFlags);
1109 // Parse the condition.
1112 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1115 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
1117 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1118 // there is no compound stmt. C90 does not have this clause. We only do this
1119 // if the body isn't a compound statement to avoid push/pop in common cases.
1122 // The substatement in an iteration-statement implicitly defines a local scope
1123 // which is entered and exited each time through the loop.
1125 // See comments in ParseIfStatement for why we create a scope for the
1126 // condition and a new scope for substatement in C++.
1128 ParseScope InnerScope(this, Scope::DeclScope,
1129 C99orCXX && Tok.isNot(tok::l_brace));
1131 // Read the body statement.
1132 StmtResult Body(ParseStatement());
1134 // Pop the body scope if needed.
1138 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1141 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1144 /// ParseDoStatement
1145 /// do-statement: [C99 6.8.5.2]
1146 /// 'do' statement 'while' '(' expression ')' ';'
1147 /// Note: this lets the caller parse the end ';'.
1148 StmtResult Parser::ParseDoStatement(ParsedAttributes &attrs) {
1149 // FIXME: Use attributes?
1151 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1152 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1154 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1155 // the case for C90. Start the loop scope.
1156 unsigned ScopeFlags;
1158 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1160 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1162 ParseScope DoScope(this, ScopeFlags);
1164 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1165 // there is no compound stmt. C90 does not have this clause. We only do this
1166 // if the body isn't a compound statement to avoid push/pop in common cases.
1169 // The substatement in an iteration-statement implicitly defines a local scope
1170 // which is entered and exited each time through the loop.
1172 ParseScope InnerScope(this, Scope::DeclScope,
1173 (getLang().C99 || getLang().CPlusPlus) &&
1174 Tok.isNot(tok::l_brace));
1176 // Read the body statement.
1177 StmtResult Body(ParseStatement());
1179 // Pop the body scope if needed.
1182 if (Tok.isNot(tok::kw_while)) {
1183 if (!Body.isInvalid()) {
1184 Diag(Tok, diag::err_expected_while);
1185 Diag(DoLoc, diag::note_matching) << "do";
1186 SkipUntil(tok::semi, false, true);
1190 SourceLocation WhileLoc = ConsumeToken();
1192 if (Tok.isNot(tok::l_paren)) {
1193 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1194 SkipUntil(tok::semi, false, true);
1198 // Parse the parenthesized condition.
1199 SourceLocation LPLoc = ConsumeParen();
1200 ExprResult Cond = ParseExpression();
1201 SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
1204 if (Cond.isInvalid() || Body.isInvalid())
1207 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, LPLoc,
1211 /// ParseForStatement
1212 /// for-statement: [C99 6.8.5.3]
1213 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1214 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1215 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1217 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
1218 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1219 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1221 /// [C++] for-init-statement:
1222 /// [C++] expression-statement
1223 /// [C++] simple-declaration
1225 /// [C++0x] for-range-declaration:
1226 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1227 /// [C++0x] for-range-initializer:
1228 /// [C++0x] expression
1229 /// [C++0x] braced-init-list [TODO]
1230 StmtResult Parser::ParseForStatement(ParsedAttributes &attrs) {
1231 // FIXME: Use attributes?
1233 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1234 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1236 if (Tok.isNot(tok::l_paren)) {
1237 Diag(Tok, diag::err_expected_lparen_after) << "for";
1238 SkipUntil(tok::semi);
1242 bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
1244 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1245 // the case for C90. Start the loop scope.
1248 // A name introduced by a declaration in a condition is in scope from its
1249 // point of declaration until the end of the substatements controlled by the
1252 // Names declared in the for-init-statement, and in the condition of if,
1253 // while, for, and switch statements are local to the if, while, for, or
1254 // switch statement (including the controlled statement).
1256 // Names declared in the for-init-statement are in the same declarative-region
1257 // as those declared in the condition.
1259 unsigned ScopeFlags;
1261 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1262 Scope::DeclScope | Scope::ControlScope;
1264 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1266 ParseScope ForScope(this, ScopeFlags);
1268 SourceLocation LParenLoc = ConsumeParen();
1271 bool ForEach = false, ForRange = false;
1272 StmtResult FirstPart;
1273 bool SecondPartIsInvalid = false;
1274 FullExprArg SecondPart(Actions);
1275 ExprResult Collection;
1276 ForRangeInit ForRangeInit;
1277 FullExprArg ThirdPart(Actions);
1278 Decl *SecondVar = 0;
1280 if (Tok.is(tok::code_completion)) {
1281 Actions.CodeCompleteOrdinaryName(getCurScope(),
1282 C99orCXXorObjC? Sema::PCC_ForInit
1283 : Sema::PCC_Expression);
1284 ConsumeCodeCompletionToken();
1287 // Parse the first part of the for specifier.
1288 if (Tok.is(tok::semi)) { // for (;
1289 // no first part, eat the ';'.
1291 } else if (isSimpleDeclaration()) { // for (int X = 4;
1292 // Parse declaration, which eats the ';'.
1293 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1294 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1296 ParsedAttributesWithRange attrs(AttrFactory);
1297 MaybeParseCXX0XAttributes(attrs);
1299 // In C++0x, "for (T NS:a" might not be a typo for ::
1300 bool MightBeForRangeStmt = getLang().CPlusPlus;
1301 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1303 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1304 StmtVector Stmts(Actions);
1305 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
1306 DeclEnd, attrs, false,
1307 MightBeForRangeStmt ?
1309 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1311 if (ForRangeInit.ParsedForRangeDecl()) {
1313 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1315 } else if ((ForEach = isTokIdentifier_in())) {
1316 Actions.ActOnForEachDeclStmt(DG);
1317 // ObjC: for (id x in expr)
1318 ConsumeToken(); // consume 'in'
1320 if (Tok.is(tok::code_completion)) {
1321 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1322 ConsumeCodeCompletionToken();
1324 Collection = ParseExpression();
1326 Diag(Tok, diag::err_expected_semi_for);
1329 Value = ParseExpression();
1331 ForEach = isTokIdentifier_in();
1333 // Turn the expression into a stmt.
1334 if (!Value.isInvalid()) {
1336 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1338 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1341 if (Tok.is(tok::semi)) {
1343 } else if (ForEach) {
1344 ConsumeToken(); // consume 'in'
1346 if (Tok.is(tok::code_completion)) {
1347 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1348 ConsumeCodeCompletionToken();
1350 Collection = ParseExpression();
1352 if (!Value.isInvalid()) {
1353 Diag(Tok, diag::err_expected_semi_for);
1355 // Skip until semicolon or rparen, don't consume it.
1356 SkipUntil(tok::r_paren, true, true);
1357 if (Tok.is(tok::semi))
1362 if (!ForEach && !ForRange) {
1363 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1364 // Parse the second part of the for specifier.
1365 if (Tok.is(tok::semi)) { // for (...;;
1367 } else if (Tok.is(tok::r_paren)) {
1368 // missing both semicolons.
1371 if (getLang().CPlusPlus)
1372 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1374 Second = ParseExpression();
1375 if (!Second.isInvalid())
1376 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1379 SecondPartIsInvalid = Second.isInvalid();
1380 SecondPart = Actions.MakeFullExpr(Second.get());
1383 if (Tok.isNot(tok::semi)) {
1384 if (!SecondPartIsInvalid || SecondVar)
1385 Diag(Tok, diag::err_expected_semi_for);
1387 // Skip until semicolon or rparen, don't consume it.
1388 SkipUntil(tok::r_paren, true, true);
1391 if (Tok.is(tok::semi)) {
1395 // Parse the third part of the for specifier.
1396 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1397 ExprResult Third = ParseExpression();
1398 ThirdPart = Actions.MakeFullExpr(Third.take());
1402 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1404 // We need to perform most of the semantic analysis for a C++0x for-range
1405 // statememt before parsing the body, in order to be able to deduce the type
1406 // of an auto-typed loop variable.
1407 StmtResult ForRangeStmt;
1409 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, LParenLoc,
1411 ForRangeInit.ColonLoc,
1412 ForRangeInit.RangeExpr.get(),
1415 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1416 // there is no compound stmt. C90 does not have this clause. We only do this
1417 // if the body isn't a compound statement to avoid push/pop in common cases.
1420 // The substatement in an iteration-statement implicitly defines a local scope
1421 // which is entered and exited each time through the loop.
1423 // See comments in ParseIfStatement for why we create a scope for
1424 // for-init-statement/condition and a new scope for substatement in C++.
1426 ParseScope InnerScope(this, Scope::DeclScope,
1427 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1429 // Read the body statement.
1430 StmtResult Body(ParseStatement());
1432 // Pop the body scope if needed.
1435 // Leave the for-scope.
1438 if (Body.isInvalid())
1442 // FIXME: It isn't clear how to communicate the late destruction of
1443 // C++ temporaries used to create the collection.
1444 return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc,
1446 Collection.take(), RParenLoc,
1450 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1452 return Actions.ActOnForStmt(ForLoc, LParenLoc, FirstPart.take(), SecondPart,
1453 SecondVar, ThirdPart, RParenLoc, Body.take());
1456 /// ParseGotoStatement
1458 /// 'goto' identifier ';'
1459 /// [GNU] 'goto' '*' expression ';'
1461 /// Note: this lets the caller parse the end ';'.
1463 StmtResult Parser::ParseGotoStatement(ParsedAttributes &attrs) {
1464 // FIXME: Use attributes?
1466 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1467 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1470 if (Tok.is(tok::identifier)) {
1471 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1473 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1475 } else if (Tok.is(tok::star)) {
1476 // GNU indirect goto extension.
1477 Diag(Tok, diag::ext_gnu_indirect_goto);
1478 SourceLocation StarLoc = ConsumeToken();
1479 ExprResult R(ParseExpression());
1480 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1481 SkipUntil(tok::semi, false, true);
1484 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1486 Diag(Tok, diag::err_expected_ident);
1493 /// ParseContinueStatement
1497 /// Note: this lets the caller parse the end ';'.
1499 StmtResult Parser::ParseContinueStatement(ParsedAttributes &attrs) {
1500 // FIXME: Use attributes?
1502 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1503 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1506 /// ParseBreakStatement
1510 /// Note: this lets the caller parse the end ';'.
1512 StmtResult Parser::ParseBreakStatement(ParsedAttributes &attrs) {
1513 // FIXME: Use attributes?
1515 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1516 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1519 /// ParseReturnStatement
1521 /// 'return' expression[opt] ';'
1522 StmtResult Parser::ParseReturnStatement(ParsedAttributes &attrs) {
1523 // FIXME: Use attributes?
1525 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1526 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1529 if (Tok.isNot(tok::semi)) {
1530 if (Tok.is(tok::code_completion)) {
1531 Actions.CodeCompleteReturn(getCurScope());
1532 ConsumeCodeCompletionToken();
1533 SkipUntil(tok::semi, false, true);
1537 // FIXME: This is a hack to allow something like C++0x's generalized
1538 // initializer lists, but only enough of this feature to allow Clang to
1539 // parse libstdc++ 4.5's headers.
1540 if (Tok.is(tok::l_brace) && getLang().CPlusPlus) {
1541 R = ParseInitializer();
1542 if (R.isUsable() && !getLang().CPlusPlus0x)
1543 Diag(R.get()->getLocStart(), diag::ext_generalized_initializer_lists)
1544 << R.get()->getSourceRange();
1546 R = ParseExpression();
1547 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1548 SkipUntil(tok::semi, false, true);
1552 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1555 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1556 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1557 StmtResult Parser::FuzzyParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1558 SourceLocation EndLoc;
1559 if (Tok.is(tok::l_brace)) {
1560 unsigned short savedBraceCount = BraceCount;
1562 EndLoc = Tok.getLocation();
1564 } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1566 // From the MS website: If used without braces, the __asm keyword means
1567 // that the rest of the line is an assembly-language statement.
1568 SourceManager &SrcMgr = PP.getSourceManager();
1569 SourceLocation TokLoc = Tok.getLocation();
1570 unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1574 TokLoc = Tok.getLocation();
1575 } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1576 Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1577 Tok.isNot(tok::eof));
1580 t.setKind(tok::string_literal);
1581 t.setLiteralData("\"/*FIXME: not done*/\"");
1582 t.clearFlag(Token::NeedsCleaning);
1584 ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1585 ExprVector Constraints(Actions);
1586 ExprVector Exprs(Actions);
1587 ExprVector Clobbers(Actions);
1588 return Actions.ActOnAsmStmt(AsmLoc, true, true, 0, 0, 0,
1589 move_arg(Constraints), move_arg(Exprs),
1590 AsmString.take(), move_arg(Clobbers),
1594 /// ParseAsmStatement - Parse a GNU extended asm statement.
1596 /// gnu-asm-statement
1597 /// ms-asm-statement
1599 /// [GNU] gnu-asm-statement:
1600 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1602 /// [GNU] asm-argument:
1603 /// asm-string-literal
1604 /// asm-string-literal ':' asm-operands[opt]
1605 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1606 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1607 /// ':' asm-clobbers
1609 /// [GNU] asm-clobbers:
1610 /// asm-string-literal
1611 /// asm-clobbers ',' asm-string-literal
1613 /// [MS] ms-asm-statement:
1614 /// '__asm' assembly-instruction ';'[opt]
1615 /// '__asm' '{' assembly-instruction-list '}' ';'[opt]
1617 /// [MS] assembly-instruction-list:
1618 /// assembly-instruction ';'[opt]
1619 /// assembly-instruction-list ';' assembly-instruction ';'[opt]
1621 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
1622 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1623 SourceLocation AsmLoc = ConsumeToken();
1625 if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1627 return FuzzyParseMicrosoftAsmStatement(AsmLoc);
1629 DeclSpec DS(AttrFactory);
1630 SourceLocation Loc = Tok.getLocation();
1631 ParseTypeQualifierListOpt(DS, true, false);
1633 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1634 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1635 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1636 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1637 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1639 // Remember if this was a volatile asm.
1640 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1641 if (Tok.isNot(tok::l_paren)) {
1642 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1643 SkipUntil(tok::r_paren);
1646 Loc = ConsumeParen();
1648 ExprResult AsmString(ParseAsmStringLiteral());
1649 if (AsmString.isInvalid())
1652 llvm::SmallVector<IdentifierInfo *, 4> Names;
1653 ExprVector Constraints(Actions);
1654 ExprVector Exprs(Actions);
1655 ExprVector Clobbers(Actions);
1657 if (Tok.is(tok::r_paren)) {
1658 // We have a simple asm expression like 'asm("foo")'.
1659 SourceLocation RParenLoc = ConsumeParen();
1660 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1661 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1662 move_arg(Constraints), move_arg(Exprs),
1663 AsmString.take(), move_arg(Clobbers),
1667 // Parse Outputs, if present.
1668 bool AteExtraColon = false;
1669 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1670 // In C++ mode, parse "::" like ": :".
1671 AteExtraColon = Tok.is(tok::coloncolon);
1674 if (!AteExtraColon &&
1675 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1679 unsigned NumOutputs = Names.size();
1681 // Parse Inputs, if present.
1682 if (AteExtraColon ||
1683 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1684 // In C++ mode, parse "::" like ": :".
1686 AteExtraColon = false;
1688 AteExtraColon = Tok.is(tok::coloncolon);
1692 if (!AteExtraColon &&
1693 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1697 assert(Names.size() == Constraints.size() &&
1698 Constraints.size() == Exprs.size() &&
1699 "Input operand size mismatch!");
1701 unsigned NumInputs = Names.size() - NumOutputs;
1703 // Parse the clobbers, if present.
1704 if (AteExtraColon || Tok.is(tok::colon)) {
1708 // Parse the asm-string list for clobbers if present.
1709 if (Tok.isNot(tok::r_paren)) {
1711 ExprResult Clobber(ParseAsmStringLiteral());
1713 if (Clobber.isInvalid())
1716 Clobbers.push_back(Clobber.release());
1718 if (Tok.isNot(tok::comma)) break;
1724 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1725 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1726 NumOutputs, NumInputs, Names.data(),
1727 move_arg(Constraints), move_arg(Exprs),
1728 AsmString.take(), move_arg(Clobbers),
1732 /// ParseAsmOperands - Parse the asm-operands production as used by
1733 /// asm-statement, assuming the leading ':' token was eaten.
1735 /// [GNU] asm-operands:
1737 /// asm-operands ',' asm-operand
1739 /// [GNU] asm-operand:
1740 /// asm-string-literal '(' expression ')'
1741 /// '[' identifier ']' asm-string-literal '(' expression ')'
1744 // FIXME: Avoid unnecessary std::string trashing.
1745 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1746 llvm::SmallVectorImpl<ExprTy *> &Constraints,
1747 llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1748 // 'asm-operands' isn't present?
1749 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1753 // Read the [id] if present.
1754 if (Tok.is(tok::l_square)) {
1755 SourceLocation Loc = ConsumeBracket();
1757 if (Tok.isNot(tok::identifier)) {
1758 Diag(Tok, diag::err_expected_ident);
1759 SkipUntil(tok::r_paren);
1763 IdentifierInfo *II = Tok.getIdentifierInfo();
1766 Names.push_back(II);
1767 MatchRHSPunctuation(tok::r_square, Loc);
1771 ExprResult Constraint(ParseAsmStringLiteral());
1772 if (Constraint.isInvalid()) {
1773 SkipUntil(tok::r_paren);
1776 Constraints.push_back(Constraint.release());
1778 if (Tok.isNot(tok::l_paren)) {
1779 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1780 SkipUntil(tok::r_paren);
1784 // Read the parenthesized expression.
1785 SourceLocation OpenLoc = ConsumeParen();
1786 ExprResult Res(ParseExpression());
1787 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1788 if (Res.isInvalid()) {
1789 SkipUntil(tok::r_paren);
1792 Exprs.push_back(Res.release());
1793 // Eat the comma and continue parsing if it exists.
1794 if (Tok.isNot(tok::comma)) return false;
1801 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1802 assert(Tok.is(tok::l_brace));
1803 SourceLocation LBraceLoc = Tok.getLocation();
1805 if (PP.isCodeCompletionEnabled()) {
1806 if (trySkippingFunctionBodyForCodeCompletion()) {
1808 return Actions.ActOnFinishFunctionBody(Decl, 0);
1812 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1813 "parsing function body");
1815 // Do not enter a scope for the brace, as the arguments are in the same scope
1816 // (the function body) as the body itself. Instead, just read the statement
1817 // list and put it into a CompoundStmt for safe keeping.
1818 StmtResult FnBody(ParseCompoundStatementBody());
1820 // If the function body could not be parsed, make a bogus compoundstmt.
1821 if (FnBody.isInvalid())
1822 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1823 MultiStmtArg(Actions), false);
1826 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1829 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1831 /// function-try-block:
1832 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1834 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1835 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1836 SourceLocation TryLoc = ConsumeToken();
1838 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1839 "parsing function try block");
1841 // Constructor initializer list?
1842 if (Tok.is(tok::colon))
1843 ParseConstructorInitializer(Decl);
1845 if (PP.isCodeCompletionEnabled()) {
1846 if (trySkippingFunctionBodyForCodeCompletion()) {
1848 return Actions.ActOnFinishFunctionBody(Decl, 0);
1852 SourceLocation LBraceLoc = Tok.getLocation();
1853 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1854 // If we failed to parse the try-catch, we just give the function an empty
1855 // compound statement as the body.
1856 if (FnBody.isInvalid())
1857 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1858 MultiStmtArg(Actions), false);
1861 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1864 bool Parser::trySkippingFunctionBodyForCodeCompletion() {
1865 assert(Tok.is(tok::l_brace));
1866 assert(PP.isCodeCompletionEnabled() &&
1867 "Should only be called when in code-completion mode");
1869 // We're in code-completion mode. Skip parsing for all function bodies unless
1870 // the body contains the code-completion point.
1871 TentativeParsingAction PA(*this);
1873 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
1874 /*StopAtCodeCompletion=*/true)) {
1883 /// ParseCXXTryBlock - Parse a C++ try-block.
1886 /// 'try' compound-statement handler-seq
1888 StmtResult Parser::ParseCXXTryBlock(ParsedAttributes &attrs) {
1889 // FIXME: Add attributes?
1891 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1893 SourceLocation TryLoc = ConsumeToken();
1894 return ParseCXXTryBlockCommon(TryLoc);
1897 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1898 /// function-try-block.
1901 /// 'try' compound-statement handler-seq
1903 /// function-try-block:
1904 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1907 /// handler handler-seq[opt]
1909 /// [Borland] try-block:
1910 /// 'try' compound-statement seh-except-block
1911 /// 'try' compound-statment seh-finally-block
1913 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1914 if (Tok.isNot(tok::l_brace))
1915 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1916 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1917 ParsedAttributesWithRange attrs(AttrFactory);
1918 StmtResult TryBlock(ParseCompoundStatement(attrs, /*isStmtExpr=*/false,
1919 Scope::DeclScope|Scope::TryScope));
1920 if (TryBlock.isInvalid())
1921 return move(TryBlock);
1923 // Borland allows SEH-handlers with 'try'
1924 if(Tok.is(tok::kw___except) || Tok.is(tok::kw___finally)) {
1925 // TODO: Factor into common return ParseSEHHandlerCommon(...)
1927 if(Tok.is(tok::kw___except)) {
1928 SourceLocation Loc = ConsumeToken();
1929 Handler = ParseSEHExceptBlock(Loc);
1932 SourceLocation Loc = ConsumeToken();
1933 Handler = ParseSEHFinallyBlock(Loc);
1935 if(Handler.isInvalid())
1936 return move(Handler);
1938 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
1944 StmtVector Handlers(Actions);
1945 MaybeParseCXX0XAttributes(attrs);
1946 ProhibitAttributes(attrs);
1948 if (Tok.isNot(tok::kw_catch))
1949 return StmtError(Diag(Tok, diag::err_expected_catch));
1950 while (Tok.is(tok::kw_catch)) {
1951 StmtResult Handler(ParseCXXCatchBlock());
1952 if (!Handler.isInvalid())
1953 Handlers.push_back(Handler.release());
1955 // Don't bother creating the full statement if we don't have any usable
1957 if (Handlers.empty())
1960 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
1964 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1967 /// 'catch' '(' exception-declaration ')' compound-statement
1969 /// exception-declaration:
1970 /// type-specifier-seq declarator
1971 /// type-specifier-seq abstract-declarator
1972 /// type-specifier-seq
1975 StmtResult Parser::ParseCXXCatchBlock() {
1976 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1978 SourceLocation CatchLoc = ConsumeToken();
1980 SourceLocation LParenLoc = Tok.getLocation();
1981 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1985 // The name in a catch exception-declaration is local to the handler and
1986 // shall not be redeclared in the outermost block of the handler.
1987 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1989 // exception-declaration is equivalent to '...' or a parameter-declaration
1990 // without default arguments.
1991 Decl *ExceptionDecl = 0;
1992 if (Tok.isNot(tok::ellipsis)) {
1993 DeclSpec DS(AttrFactory);
1994 if (ParseCXXTypeSpecifierSeq(DS))
1996 Declarator ExDecl(DS, Declarator::CXXCatchContext);
1997 ParseDeclarator(ExDecl);
1998 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2002 if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
2005 if (Tok.isNot(tok::l_brace))
2006 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2008 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2009 ParsedAttributes attrs(AttrFactory);
2010 StmtResult Block(ParseCompoundStatement(attrs));
2011 if (Block.isInvalid())
2014 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
2017 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2019 if (ParseMicrosoftIfExistsCondition(Result))
2022 if (Tok.isNot(tok::l_brace)) {
2023 Diag(Tok, diag::err_expected_lbrace);
2028 // Condition is false skip all inside the {}.
2030 SkipUntil(tok::r_brace, false);
2034 // Condition is true, parse the statements.
2035 while (Tok.isNot(tok::r_brace)) {
2036 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2038 Stmts.push_back(R.release());
2041 if (Tok.isNot(tok::r_brace)) {
2042 Diag(Tok, diag::err_expected_rbrace);