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 /// [OBC] objc-throw-statement
44 /// [OBC] objc-try-catch-statement
45 /// [OBC] objc-synchronized-statement
46 /// [GNU] asm-statement
47 /// [OMP] openmp-construct [TODO]
49 /// labeled-statement:
50 /// identifier ':' statement
51 /// 'case' constant-expression ':' statement
52 /// 'default' ':' statement
54 /// selection-statement:
58 /// iteration-statement:
63 /// expression-statement:
64 /// expression[opt] ';'
67 /// 'goto' identifier ';'
70 /// 'return' expression[opt] ';'
71 /// [GNU] 'goto' '*' expression ';'
73 /// [OBC] objc-throw-statement:
74 /// [OBC] '@' 'throw' expression ';'
75 /// [OBC] '@' 'throw' ';'
78 Parser::ParseStatementOrDeclaration(bool OnlyStatement) {
79 const char *SemiError = 0;
82 ParenBraceBracketBalancer BalancerRAIIObj(*this);
84 CXX0XAttributeList Attr;
85 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
86 Attr = ParseCXX0XAttributes();
87 llvm::OwningPtr<AttributeList> AttrList(Attr.AttrList);
89 // Cases in this switch statement should fall through if the parser expects
90 // the token to end in a semicolon (in which case SemiError should be set),
91 // 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(OnlyStatement);
106 case tok::identifier:
107 if (NextToken().is(tok::colon)) { // C99 6.8.1: labeled-statement
108 // identifier ':' statement
109 return ParseLabeledStatement(AttrList.take());
114 if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
115 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
116 AttrList.take(); //Passing 'Attr' to ParseDeclaration transfers ownership.
117 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext, DeclEnd,
119 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
122 if (Tok.is(tok::r_brace)) {
123 Diag(Tok, diag::err_expected_statement);
127 // FIXME: Use the attributes
128 // expression[opt] ';'
129 ExprResult Expr(ParseExpression());
130 if (Expr.isInvalid()) {
131 // If the expression is invalid, skip ahead to the next semicolon or '}'.
132 // Not doing this opens us up to the possibility of infinite loops if
133 // ParseExpression does not consume any tokens.
134 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
135 if (Tok.is(tok::semi))
139 // Otherwise, eat the semicolon.
140 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
141 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
144 case tok::kw_case: // C99 6.8.1: labeled-statement
145 return ParseCaseStatement(AttrList.take());
146 case tok::kw_default: // C99 6.8.1: labeled-statement
147 return ParseDefaultStatement(AttrList.take());
149 case tok::l_brace: // C99 6.8.2: compound-statement
150 return ParseCompoundStatement(AttrList.take());
151 case tok::semi: // C99 6.8.3p3: expression[opt] ';'
152 return Actions.ActOnNullStmt(ConsumeToken());
154 case tok::kw_if: // C99 6.8.4.1: if-statement
155 return ParseIfStatement(AttrList.take());
156 case tok::kw_switch: // C99 6.8.4.2: switch-statement
157 return ParseSwitchStatement(AttrList.take());
159 case tok::kw_while: // C99 6.8.5.1: while-statement
160 return ParseWhileStatement(AttrList.take());
161 case tok::kw_do: // C99 6.8.5.2: do-statement
162 Res = ParseDoStatement(AttrList.take());
163 SemiError = "do/while";
165 case tok::kw_for: // C99 6.8.5.3: for-statement
166 return ParseForStatement(AttrList.take());
168 case tok::kw_goto: // C99 6.8.6.1: goto-statement
169 Res = ParseGotoStatement(AttrList.take());
172 case tok::kw_continue: // C99 6.8.6.2: continue-statement
173 Res = ParseContinueStatement(AttrList.take());
174 SemiError = "continue";
176 case tok::kw_break: // C99 6.8.6.3: break-statement
177 Res = ParseBreakStatement(AttrList.take());
180 case tok::kw_return: // C99 6.8.6.4: return-statement
181 Res = ParseReturnStatement(AttrList.take());
182 SemiError = "return";
187 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
190 Res = ParseAsmStatement(msAsm);
191 if (msAsm) return move(Res);
196 case tok::kw_try: // C++ 15: try-block
197 return ParseCXXTryBlock(AttrList.take());
200 // If we reached this code, the statement must end in a semicolon.
201 if (Tok.is(tok::semi)) {
203 } else if (!Res.isInvalid()) {
204 // If the result was valid, then we do want to diagnose this. Use
205 // ExpectAndConsume to emit the diagnostic, even though we know it won't
207 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
208 // Skip until we see a } or ;, but don't eat it.
209 SkipUntil(tok::r_brace, true, true);
215 /// ParseLabeledStatement - We have an identifier and a ':' after it.
217 /// labeled-statement:
218 /// identifier ':' statement
219 /// [GNU] identifier ':' attributes[opt] statement
221 StmtResult Parser::ParseLabeledStatement(AttributeList *Attr) {
222 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
223 "Not an identifier!");
225 llvm::OwningPtr<AttributeList> AttrList(Attr);
226 Token IdentTok = Tok; // Save the whole token.
227 ConsumeToken(); // eat the identifier.
229 assert(Tok.is(tok::colon) && "Not a label!");
231 // identifier ':' statement
232 SourceLocation ColonLoc = ConsumeToken();
234 // Read label attributes, if present.
235 if (Tok.is(tok::kw___attribute))
236 AttrList.reset(addAttributeLists(AttrList.take(), ParseGNUAttributes()));
238 StmtResult SubStmt(ParseStatement());
240 // Broken substmt shouldn't prevent the label from being added to the AST.
241 if (SubStmt.isInvalid())
242 SubStmt = Actions.ActOnNullStmt(ColonLoc);
244 // FIXME: use attributes?
245 return Actions.ActOnLabelStmt(IdentTok.getLocation(),
246 IdentTok.getIdentifierInfo(),
247 ColonLoc, SubStmt.get());
250 /// ParseCaseStatement
251 /// labeled-statement:
252 /// 'case' constant-expression ':' statement
253 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
255 StmtResult Parser::ParseCaseStatement(AttributeList *Attr) {
256 assert(Tok.is(tok::kw_case) && "Not a case stmt!");
257 // FIXME: Use attributes?
260 // It is very very common for code to contain many case statements recursively
261 // nested, as in (but usually without indentation):
268 // Parsing this naively works, but is both inefficient and can cause us to run
269 // out of stack space in our recursive descent parser. As a special case,
270 // flatten this recursion into an iterative loop. This is complex and gross,
271 // but all the grossness is constrained to ParseCaseStatement (and some
272 // wierdness in the actions), so this is just local grossness :).
274 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
276 StmtResult TopLevelCase(true);
278 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
279 // gets updated each time a new case is parsed, and whose body is unset so
280 // far. When parsing 'case 4', this is the 'case 3' node.
281 StmtTy *DeepestParsedCaseStmt = 0;
283 // While we have case statements, eat and stack them.
285 SourceLocation CaseLoc = ConsumeToken(); // eat the 'case'.
287 if (Tok.is(tok::code_completion)) {
288 Actions.CodeCompleteCase(getCurScope());
289 ConsumeCodeCompletionToken();
292 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
293 /// Disable this form of error recovery while we're parsing the case
295 ColonProtectionRAIIObject ColonProtection(*this);
297 ExprResult LHS(ParseConstantExpression());
298 if (LHS.isInvalid()) {
299 SkipUntil(tok::colon);
303 // GNU case range extension.
304 SourceLocation DotDotDotLoc;
306 if (Tok.is(tok::ellipsis)) {
307 Diag(Tok, diag::ext_gnu_case_range);
308 DotDotDotLoc = ConsumeToken();
310 RHS = ParseConstantExpression();
311 if (RHS.isInvalid()) {
312 SkipUntil(tok::colon);
317 ColonProtection.restore();
319 if (Tok.isNot(tok::colon)) {
320 Diag(Tok, diag::err_expected_colon_after) << "'case'";
321 SkipUntil(tok::colon);
325 SourceLocation ColonLoc = ConsumeToken();
328 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
329 RHS.get(), ColonLoc);
331 // If we had a sema error parsing this case, then just ignore it and
332 // continue parsing the sub-stmt.
333 if (Case.isInvalid()) {
334 if (TopLevelCase.isInvalid()) // No parsed case stmts.
335 return ParseStatement();
336 // Otherwise, just don't add it as a nested case.
338 // If this is the first case statement we parsed, it becomes TopLevelCase.
339 // Otherwise we link it into the current chain.
340 Stmt *NextDeepest = Case.get();
341 if (TopLevelCase.isInvalid())
342 TopLevelCase = move(Case);
344 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
345 DeepestParsedCaseStmt = NextDeepest;
348 // Handle all case statements.
349 } while (Tok.is(tok::kw_case));
351 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
353 // If we found a non-case statement, start by parsing it.
356 if (Tok.isNot(tok::r_brace)) {
357 SubStmt = ParseStatement();
359 // Nicely diagnose the common error "switch (X) { case 4: }", which is
361 // FIXME: add insertion hint.
362 Diag(Tok, diag::err_label_end_of_compound_statement);
366 // Broken sub-stmt shouldn't prevent forming the case statement properly.
367 if (SubStmt.isInvalid())
368 SubStmt = Actions.ActOnNullStmt(SourceLocation());
370 // Install the body into the most deeply-nested case.
371 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
373 // Return the top level parsed statement tree.
374 return move(TopLevelCase);
377 /// ParseDefaultStatement
378 /// labeled-statement:
379 /// 'default' ':' statement
380 /// Note that this does not parse the 'statement' at the end.
382 StmtResult Parser::ParseDefaultStatement(AttributeList *Attr) {
383 //FIXME: Use attributes?
386 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
387 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
389 if (Tok.isNot(tok::colon)) {
390 Diag(Tok, diag::err_expected_colon_after) << "'default'";
391 SkipUntil(tok::colon);
395 SourceLocation ColonLoc = ConsumeToken();
397 // Diagnose the common error "switch (X) {... default: }", which is not valid.
398 if (Tok.is(tok::r_brace)) {
399 Diag(Tok, diag::err_label_end_of_compound_statement);
403 StmtResult SubStmt(ParseStatement());
404 if (SubStmt.isInvalid())
407 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
408 SubStmt.get(), getCurScope());
412 /// ParseCompoundStatement - Parse a "{}" block.
414 /// compound-statement: [C99 6.8.2]
415 /// { block-item-list[opt] }
416 /// [GNU] { label-declarations block-item-list } [TODO]
420 /// block-item-list block-item
424 /// [GNU] '__extension__' declaration
426 /// [OMP] openmp-directive [TODO]
428 /// [GNU] label-declarations:
429 /// [GNU] label-declaration
430 /// [GNU] label-declarations label-declaration
432 /// [GNU] label-declaration:
433 /// [GNU] '__label__' identifier-list ';'
435 /// [OMP] openmp-directive: [TODO]
436 /// [OMP] barrier-directive
437 /// [OMP] flush-directive
439 StmtResult Parser::ParseCompoundStatement(AttributeList *Attr,
441 //FIXME: Use attributes?
444 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
446 // Enter a scope to hold everything within the compound stmt. Compound
447 // statements can always hold declarations.
448 ParseScope CompoundScope(this, Scope::DeclScope);
450 // Parse the statements in the body.
451 return ParseCompoundStatementBody(isStmtExpr);
455 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
456 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
457 /// consume the '}' at the end of the block. It does not manipulate the scope
459 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
460 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
462 "in compound statement ('{}')");
464 SourceLocation LBraceLoc = ConsumeBrace(); // eat the '{'.
466 // TODO: "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
467 // only allowed at the start of a compound stmt regardless of the language.
469 typedef StmtVector StmtsTy;
470 StmtsTy Stmts(Actions);
471 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
473 if (Tok.isNot(tok::kw___extension__)) {
474 R = ParseStatementOrDeclaration(false);
476 // __extension__ can start declarations and it can also be a unary
477 // operator for expressions. Consume multiple __extension__ markers here
478 // until we can determine which is which.
479 // FIXME: This loses extension expressions in the AST!
480 SourceLocation ExtLoc = ConsumeToken();
481 while (Tok.is(tok::kw___extension__))
484 CXX0XAttributeList Attr;
485 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
486 Attr = ParseCXX0XAttributes();
488 // If this is the start of a declaration, parse it as such.
489 if (isDeclarationStatement()) {
490 // __extension__ silences extension warnings in the subdeclaration.
491 // FIXME: Save the __extension__ on the decl as a node somehow?
492 ExtensionRAIIObject O(Diags);
494 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
495 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
497 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
499 // Otherwise this was a unary __extension__ marker.
500 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
502 if (Res.isInvalid()) {
503 SkipUntil(tok::semi);
507 // FIXME: Use attributes?
508 // Eat the semicolon at the end of stmt and convert the expr into a
510 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
511 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
516 Stmts.push_back(R.release());
519 // We broke out of the while loop because we found a '}' or EOF.
520 if (Tok.isNot(tok::r_brace)) {
521 Diag(Tok, diag::err_expected_rbrace);
522 Diag(LBraceLoc, diag::note_matching) << "{";
526 SourceLocation RBraceLoc = ConsumeBrace();
527 return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
531 /// ParseParenExprOrCondition:
532 /// [C ] '(' expression ')'
533 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
535 /// This function parses and performs error recovery on the specified condition
536 /// or expression (depending on whether we're in C++ or C mode). This function
537 /// goes out of its way to recover well. It returns true if there was a parser
538 /// error (the right paren couldn't be found), which indicates that the caller
539 /// should try to recover harder. It returns false if the condition is
540 /// successfully parsed. Note that a successful parse can still have semantic
541 /// errors in the condition.
542 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
545 bool ConvertToBoolean) {
546 bool ParseError = false;
548 SourceLocation LParenLoc = ConsumeParen();
549 if (getLang().CPlusPlus)
550 ParseError = ParseCXXCondition(ExprResult, DeclResult, Loc,
553 ExprResult = ParseExpression();
556 // If required, convert to a boolean value.
557 if (!ExprResult.isInvalid() && ConvertToBoolean)
559 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
562 // If the parser was confused by the condition and we don't have a ')', try to
563 // recover by skipping ahead to a semi and bailing out. If condexp is
564 // semantically invalid but we have well formed code, keep going.
565 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
566 SkipUntil(tok::semi);
567 // Skipping may have stopped if it found the containing ')'. If so, we can
568 // continue parsing the if statement.
569 if (Tok.isNot(tok::r_paren))
573 // Otherwise the condition is valid or the rparen is present.
574 MatchRHSPunctuation(tok::r_paren, LParenLoc);
580 /// if-statement: [C99 6.8.4.1]
581 /// 'if' '(' expression ')' statement
582 /// 'if' '(' expression ')' statement 'else' statement
583 /// [C++] 'if' '(' condition ')' statement
584 /// [C++] 'if' '(' condition ')' statement 'else' statement
586 StmtResult Parser::ParseIfStatement(AttributeList *Attr) {
587 // FIXME: Use attributes?
590 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
591 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
593 if (Tok.isNot(tok::l_paren)) {
594 Diag(Tok, diag::err_expected_lparen_after) << "if";
595 SkipUntil(tok::semi);
599 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
601 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
605 // A name introduced by a declaration in a condition is in scope from its
606 // point of declaration until the end of the substatements controlled by the
609 // Names declared in the for-init-statement, and in the condition of if,
610 // while, for, and switch statements are local to the if, while, for, or
611 // switch statement (including the controlled statement).
613 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
615 // Parse the condition.
618 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
621 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
623 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
624 // there is no compound stmt. C90 does not have this clause. We only do this
625 // if the body isn't a compound statement to avoid push/pop in common cases.
628 // The substatement in a selection-statement (each substatement, in the else
629 // form of the if statement) implicitly defines a local scope.
631 // For C++ we create a scope for the condition and a new scope for
632 // substatements because:
633 // -When the 'then' scope exits, we want the condition declaration to still be
634 // active for the 'else' scope too.
635 // -Sema will detect name clashes by considering declarations of a
636 // 'ControlScope' as part of its direct subscope.
637 // -If we wanted the condition and substatement to be in the same scope, we
638 // would have to notify ParseStatement not to create a new scope. It's
639 // simpler to let it create a new scope.
641 ParseScope InnerScope(this, Scope::DeclScope,
642 C99orCXX && Tok.isNot(tok::l_brace));
644 // Read the 'then' stmt.
645 SourceLocation ThenStmtLoc = Tok.getLocation();
646 StmtResult ThenStmt(ParseStatement());
648 // Pop the 'if' scope if needed.
651 // If it has an else, parse it.
652 SourceLocation ElseLoc;
653 SourceLocation ElseStmtLoc;
656 if (Tok.is(tok::kw_else)) {
657 ElseLoc = ConsumeToken();
658 ElseStmtLoc = Tok.getLocation();
660 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
661 // there is no compound stmt. C90 does not have this clause. We only do
662 // this if the body isn't a compound statement to avoid push/pop in common
666 // The substatement in a selection-statement (each substatement, in the else
667 // form of the if statement) implicitly defines a local scope.
669 ParseScope InnerScope(this, Scope::DeclScope,
670 C99orCXX && Tok.isNot(tok::l_brace));
672 ElseStmt = ParseStatement();
674 // Pop the 'else' scope if needed.
680 // If the condition was invalid, discard the if statement. We could recover
681 // better by replacing it with a valid expr, but don't do that yet.
682 if (CondExp.isInvalid() && !CondVar)
685 // If the then or else stmt is invalid and the other is valid (and present),
686 // make turn the invalid one into a null stmt to avoid dropping the other
687 // part. If both are invalid, return error.
688 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
689 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
690 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
691 // Both invalid, or one is invalid and other is non-present: return error.
695 // Now if either are invalid, replace with a ';'.
696 if (ThenStmt.isInvalid())
697 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
698 if (ElseStmt.isInvalid())
699 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
701 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
702 ElseLoc, ElseStmt.get());
705 /// ParseSwitchStatement
706 /// switch-statement:
707 /// 'switch' '(' expression ')' statement
708 /// [C++] 'switch' '(' condition ')' statement
709 StmtResult Parser::ParseSwitchStatement(AttributeList *Attr) {
710 // FIXME: Use attributes?
713 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
714 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
716 if (Tok.isNot(tok::l_paren)) {
717 Diag(Tok, diag::err_expected_lparen_after) << "switch";
718 SkipUntil(tok::semi);
722 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
724 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
725 // not the case for C90. Start the switch scope.
728 // A name introduced by a declaration in a condition is in scope from its
729 // point of declaration until the end of the substatements controlled by the
732 // Names declared in the for-init-statement, and in the condition of if,
733 // while, for, and switch statements are local to the if, while, for, or
734 // switch statement (including the controlled statement).
736 unsigned ScopeFlags = Scope::BreakScope;
738 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
739 ParseScope SwitchScope(this, ScopeFlags);
741 // Parse the condition.
744 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
748 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
750 if (Switch.isInvalid()) {
751 // Skip the switch body.
752 // FIXME: This is not optimal recovery, but parsing the body is more
753 // dangerous due to the presence of case and default statements, which
754 // will have no place to connect back with the switch.
755 if (Tok.is(tok::l_brace)) {
757 SkipUntil(tok::r_brace, false, false);
759 SkipUntil(tok::semi);
763 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
764 // there is no compound stmt. C90 does not have this clause. We only do this
765 // if the body isn't a compound statement to avoid push/pop in common cases.
768 // The substatement in a selection-statement (each substatement, in the else
769 // form of the if statement) implicitly defines a local scope.
771 // See comments in ParseIfStatement for why we create a scope for the
772 // condition and a new scope for substatement in C++.
774 ParseScope InnerScope(this, Scope::DeclScope,
775 C99orCXX && Tok.isNot(tok::l_brace));
777 // Read the body statement.
778 StmtResult Body(ParseStatement());
784 if (Body.isInvalid())
785 // FIXME: Remove the case statement list from the Switch statement.
786 Body = Actions.ActOnNullStmt(Tok.getLocation());
788 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
791 /// ParseWhileStatement
792 /// while-statement: [C99 6.8.5.1]
793 /// 'while' '(' expression ')' statement
794 /// [C++] 'while' '(' condition ')' statement
795 StmtResult Parser::ParseWhileStatement(AttributeList *Attr) {
796 // FIXME: Use attributes?
799 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
800 SourceLocation WhileLoc = Tok.getLocation();
801 ConsumeToken(); // eat the 'while'.
803 if (Tok.isNot(tok::l_paren)) {
804 Diag(Tok, diag::err_expected_lparen_after) << "while";
805 SkipUntil(tok::semi);
809 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
811 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
812 // the case for C90. Start the loop scope.
815 // A name introduced by a declaration in a condition is in scope from its
816 // point of declaration until the end of the substatements controlled by the
819 // Names declared in the for-init-statement, and in the condition of if,
820 // while, for, and switch statements are local to the if, while, for, or
821 // switch statement (including the controlled statement).
825 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
826 Scope::DeclScope | Scope::ControlScope;
828 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
829 ParseScope WhileScope(this, ScopeFlags);
831 // Parse the condition.
834 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
837 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
839 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
840 // there is no compound stmt. C90 does not have this clause. We only do this
841 // if the body isn't a compound statement to avoid push/pop in common cases.
844 // The substatement in an iteration-statement implicitly defines a local scope
845 // which is entered and exited each time through the loop.
847 // See comments in ParseIfStatement for why we create a scope for the
848 // condition and a new scope for substatement in C++.
850 ParseScope InnerScope(this, Scope::DeclScope,
851 C99orCXX && Tok.isNot(tok::l_brace));
853 // Read the body statement.
854 StmtResult Body(ParseStatement());
856 // Pop the body scope if needed.
860 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
863 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
867 /// do-statement: [C99 6.8.5.2]
868 /// 'do' statement 'while' '(' expression ')' ';'
869 /// Note: this lets the caller parse the end ';'.
870 StmtResult Parser::ParseDoStatement(AttributeList *Attr) {
871 // FIXME: Use attributes?
874 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
875 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
877 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
878 // the case for C90. Start the loop scope.
881 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
883 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
885 ParseScope DoScope(this, ScopeFlags);
887 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
888 // there is no compound stmt. C90 does not have this clause. We only do this
889 // if the body isn't a compound statement to avoid push/pop in common cases.
892 // The substatement in an iteration-statement implicitly defines a local scope
893 // which is entered and exited each time through the loop.
895 ParseScope InnerScope(this, Scope::DeclScope,
896 (getLang().C99 || getLang().CPlusPlus) &&
897 Tok.isNot(tok::l_brace));
899 // Read the body statement.
900 StmtResult Body(ParseStatement());
902 // Pop the body scope if needed.
905 if (Tok.isNot(tok::kw_while)) {
906 if (!Body.isInvalid()) {
907 Diag(Tok, diag::err_expected_while);
908 Diag(DoLoc, diag::note_matching) << "do";
909 SkipUntil(tok::semi, false, true);
913 SourceLocation WhileLoc = ConsumeToken();
915 if (Tok.isNot(tok::l_paren)) {
916 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
917 SkipUntil(tok::semi, false, true);
921 // Parse the parenthesized condition.
922 SourceLocation LPLoc = ConsumeParen();
923 ExprResult Cond = ParseExpression();
924 SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
927 if (Cond.isInvalid() || Body.isInvalid())
930 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, LPLoc,
934 /// ParseForStatement
935 /// for-statement: [C99 6.8.5.3]
936 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
937 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
938 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
940 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
941 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
943 /// [C++] for-init-statement:
944 /// [C++] expression-statement
945 /// [C++] simple-declaration
947 StmtResult Parser::ParseForStatement(AttributeList *Attr) {
948 // FIXME: Use attributes?
951 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
952 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
954 if (Tok.isNot(tok::l_paren)) {
955 Diag(Tok, diag::err_expected_lparen_after) << "for";
956 SkipUntil(tok::semi);
960 bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
962 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
963 // the case for C90. Start the loop scope.
966 // A name introduced by a declaration in a condition is in scope from its
967 // point of declaration until the end of the substatements controlled by the
970 // Names declared in the for-init-statement, and in the condition of if,
971 // while, for, and switch statements are local to the if, while, for, or
972 // switch statement (including the controlled statement).
974 // Names declared in the for-init-statement are in the same declarative-region
975 // as those declared in the condition.
979 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
980 Scope::DeclScope | Scope::ControlScope;
982 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
984 ParseScope ForScope(this, ScopeFlags);
986 SourceLocation LParenLoc = ConsumeParen();
989 bool ForEach = false;
990 StmtResult FirstPart;
991 bool SecondPartIsInvalid = false;
992 FullExprArg SecondPart(Actions);
993 ExprResult Collection;
994 FullExprArg ThirdPart(Actions);
997 if (Tok.is(tok::code_completion)) {
998 Actions.CodeCompleteOrdinaryName(getCurScope(),
999 C99orCXXorObjC? Sema::PCC_ForInit
1000 : Sema::PCC_Expression);
1001 ConsumeCodeCompletionToken();
1004 // Parse the first part of the for specifier.
1005 if (Tok.is(tok::semi)) { // for (;
1006 // no first part, eat the ';'.
1008 } else if (isSimpleDeclaration()) { // for (int X = 4;
1009 // Parse declaration, which eats the ';'.
1010 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1011 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1013 AttributeList *AttrList = 0;
1014 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1015 AttrList = ParseCXX0XAttributes().AttrList;
1017 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1018 DeclGroupPtrTy DG = ParseSimpleDeclaration(Declarator::ForContext, DeclEnd,
1020 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1022 if (Tok.is(tok::semi)) { // for (int x = 4;
1024 } else if ((ForEach = isTokIdentifier_in())) {
1025 Actions.ActOnForEachDeclStmt(DG);
1026 // ObjC: for (id x in expr)
1027 ConsumeToken(); // consume 'in'
1029 if (Tok.is(tok::code_completion)) {
1030 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1031 ConsumeCodeCompletionToken();
1033 Collection = ParseExpression();
1035 Diag(Tok, diag::err_expected_semi_for);
1036 SkipUntil(tok::semi);
1039 Value = ParseExpression();
1041 // Turn the expression into a stmt.
1042 if (!Value.isInvalid())
1043 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1045 if (Tok.is(tok::semi)) {
1047 } else if ((ForEach = isTokIdentifier_in())) {
1048 ConsumeToken(); // consume 'in'
1050 if (Tok.is(tok::code_completion)) {
1051 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1052 ConsumeCodeCompletionToken();
1054 Collection = ParseExpression();
1056 if (!Value.isInvalid()) Diag(Tok, diag::err_expected_semi_for);
1057 SkipUntil(tok::semi);
1061 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1062 // Parse the second part of the for specifier.
1063 if (Tok.is(tok::semi)) { // for (...;;
1067 if (getLang().CPlusPlus)
1068 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1070 Second = ParseExpression();
1071 if (!Second.isInvalid())
1072 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1075 SecondPartIsInvalid = Second.isInvalid();
1076 SecondPart = Actions.MakeFullExpr(Second.get());
1079 if (Tok.is(tok::semi)) {
1082 if (!SecondPartIsInvalid || SecondVar)
1083 Diag(Tok, diag::err_expected_semi_for);
1084 SkipUntil(tok::semi);
1087 // Parse the third part of the for specifier.
1088 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1089 ExprResult Third = ParseExpression();
1090 ThirdPart = Actions.MakeFullExpr(Third.take());
1094 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1096 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1097 // there is no compound stmt. C90 does not have this clause. We only do this
1098 // if the body isn't a compound statement to avoid push/pop in common cases.
1101 // The substatement in an iteration-statement implicitly defines a local scope
1102 // which is entered and exited each time through the loop.
1104 // See comments in ParseIfStatement for why we create a scope for
1105 // for-init-statement/condition and a new scope for substatement in C++.
1107 ParseScope InnerScope(this, Scope::DeclScope,
1108 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1110 // Read the body statement.
1111 StmtResult Body(ParseStatement());
1113 // Pop the body scope if needed.
1116 // Leave the for-scope.
1119 if (Body.isInvalid())
1123 return Actions.ActOnForStmt(ForLoc, LParenLoc, FirstPart.take(), SecondPart,
1124 SecondVar, ThirdPart, RParenLoc, Body.take());
1126 // FIXME: It isn't clear how to communicate the late destruction of
1127 // C++ temporaries used to create the collection.
1128 return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc, FirstPart.take(),
1129 Collection.take(), RParenLoc,
1133 /// ParseGotoStatement
1135 /// 'goto' identifier ';'
1136 /// [GNU] 'goto' '*' expression ';'
1138 /// Note: this lets the caller parse the end ';'.
1140 StmtResult Parser::ParseGotoStatement(AttributeList *Attr) {
1141 // FIXME: Use attributes?
1144 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1145 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1148 if (Tok.is(tok::identifier)) {
1149 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(),
1150 Tok.getIdentifierInfo());
1152 } else if (Tok.is(tok::star)) {
1153 // GNU indirect goto extension.
1154 Diag(Tok, diag::ext_gnu_indirect_goto);
1155 SourceLocation StarLoc = ConsumeToken();
1156 ExprResult R(ParseExpression());
1157 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1158 SkipUntil(tok::semi, false, true);
1161 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1163 Diag(Tok, diag::err_expected_ident);
1170 /// ParseContinueStatement
1174 /// Note: this lets the caller parse the end ';'.
1176 StmtResult Parser::ParseContinueStatement(AttributeList *Attr) {
1177 // FIXME: Use attributes?
1180 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1181 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1184 /// ParseBreakStatement
1188 /// Note: this lets the caller parse the end ';'.
1190 StmtResult Parser::ParseBreakStatement(AttributeList *Attr) {
1191 // FIXME: Use attributes?
1194 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1195 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1198 /// ParseReturnStatement
1200 /// 'return' expression[opt] ';'
1201 StmtResult Parser::ParseReturnStatement(AttributeList *Attr) {
1202 // FIXME: Use attributes?
1205 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1206 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1209 if (Tok.isNot(tok::semi)) {
1210 if (Tok.is(tok::code_completion)) {
1211 Actions.CodeCompleteReturn(getCurScope());
1212 ConsumeCodeCompletionToken();
1213 SkipUntil(tok::semi, false, true);
1217 R = ParseExpression();
1218 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1219 SkipUntil(tok::semi, false, true);
1223 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1226 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1227 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1228 StmtResult Parser::FuzzyParseMicrosoftAsmStatement() {
1229 if (Tok.is(tok::l_brace)) {
1230 unsigned short savedBraceCount = BraceCount;
1233 } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1235 // From the MS website: If used without braces, the __asm keyword means
1236 // that the rest of the line is an assembly-language statement.
1237 SourceManager &SrcMgr = PP.getSourceManager();
1238 SourceLocation TokLoc = Tok.getLocation();
1239 unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1242 TokLoc = Tok.getLocation();
1243 } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1244 Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1245 Tok.isNot(tok::eof));
1248 t.setKind(tok::string_literal);
1249 t.setLiteralData("\"/*FIXME: not done*/\"");
1250 t.clearFlag(Token::NeedsCleaning);
1252 ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1253 ExprVector Constraints(Actions);
1254 ExprVector Exprs(Actions);
1255 ExprVector Clobbers(Actions);
1256 return Actions.ActOnAsmStmt(Tok.getLocation(), true, true, 0, 0, 0,
1257 move_arg(Constraints), move_arg(Exprs),
1258 AsmString.take(), move_arg(Clobbers),
1259 Tok.getLocation(), true);
1262 /// ParseAsmStatement - Parse a GNU extended asm statement.
1264 /// gnu-asm-statement
1265 /// ms-asm-statement
1267 /// [GNU] gnu-asm-statement:
1268 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1270 /// [GNU] asm-argument:
1271 /// asm-string-literal
1272 /// asm-string-literal ':' asm-operands[opt]
1273 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1274 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1275 /// ':' asm-clobbers
1277 /// [GNU] asm-clobbers:
1278 /// asm-string-literal
1279 /// asm-clobbers ',' asm-string-literal
1281 /// [MS] ms-asm-statement:
1282 /// '__asm' assembly-instruction ';'[opt]
1283 /// '__asm' '{' assembly-instruction-list '}' ';'[opt]
1285 /// [MS] assembly-instruction-list:
1286 /// assembly-instruction ';'[opt]
1287 /// assembly-instruction-list ';' assembly-instruction ';'[opt]
1289 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
1290 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1291 SourceLocation AsmLoc = ConsumeToken();
1293 if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1295 return FuzzyParseMicrosoftAsmStatement();
1298 SourceLocation Loc = Tok.getLocation();
1299 ParseTypeQualifierListOpt(DS, true, false);
1301 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1302 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1303 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1304 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1305 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1307 // Remember if this was a volatile asm.
1308 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1309 if (Tok.isNot(tok::l_paren)) {
1310 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1311 SkipUntil(tok::r_paren);
1314 Loc = ConsumeParen();
1316 ExprResult AsmString(ParseAsmStringLiteral());
1317 if (AsmString.isInvalid())
1320 llvm::SmallVector<IdentifierInfo *, 4> Names;
1321 ExprVector Constraints(Actions);
1322 ExprVector Exprs(Actions);
1323 ExprVector Clobbers(Actions);
1325 if (Tok.is(tok::r_paren)) {
1326 // We have a simple asm expression like 'asm("foo")'.
1327 SourceLocation RParenLoc = ConsumeParen();
1328 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1329 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1330 move_arg(Constraints), move_arg(Exprs),
1331 AsmString.take(), move_arg(Clobbers),
1335 // Parse Outputs, if present.
1336 bool AteExtraColon = false;
1337 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1338 // In C++ mode, parse "::" like ": :".
1339 AteExtraColon = Tok.is(tok::coloncolon);
1342 if (!AteExtraColon &&
1343 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1347 unsigned NumOutputs = Names.size();
1349 // Parse Inputs, if present.
1350 if (AteExtraColon ||
1351 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1352 // In C++ mode, parse "::" like ": :".
1354 AteExtraColon = false;
1356 AteExtraColon = Tok.is(tok::coloncolon);
1360 if (!AteExtraColon &&
1361 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1365 assert(Names.size() == Constraints.size() &&
1366 Constraints.size() == Exprs.size() &&
1367 "Input operand size mismatch!");
1369 unsigned NumInputs = Names.size() - NumOutputs;
1371 // Parse the clobbers, if present.
1372 if (AteExtraColon || Tok.is(tok::colon)) {
1376 // Parse the asm-string list for clobbers if present.
1377 if (Tok.isNot(tok::r_paren)) {
1379 ExprResult Clobber(ParseAsmStringLiteral());
1381 if (Clobber.isInvalid())
1384 Clobbers.push_back(Clobber.release());
1386 if (Tok.isNot(tok::comma)) break;
1392 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1393 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1394 NumOutputs, NumInputs, Names.data(),
1395 move_arg(Constraints), move_arg(Exprs),
1396 AsmString.take(), move_arg(Clobbers),
1400 /// ParseAsmOperands - Parse the asm-operands production as used by
1401 /// asm-statement, assuming the leading ':' token was eaten.
1403 /// [GNU] asm-operands:
1405 /// asm-operands ',' asm-operand
1407 /// [GNU] asm-operand:
1408 /// asm-string-literal '(' expression ')'
1409 /// '[' identifier ']' asm-string-literal '(' expression ')'
1412 // FIXME: Avoid unnecessary std::string trashing.
1413 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1414 llvm::SmallVectorImpl<ExprTy *> &Constraints,
1415 llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1416 // 'asm-operands' isn't present?
1417 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1421 // Read the [id] if present.
1422 if (Tok.is(tok::l_square)) {
1423 SourceLocation Loc = ConsumeBracket();
1425 if (Tok.isNot(tok::identifier)) {
1426 Diag(Tok, diag::err_expected_ident);
1427 SkipUntil(tok::r_paren);
1431 IdentifierInfo *II = Tok.getIdentifierInfo();
1434 Names.push_back(II);
1435 MatchRHSPunctuation(tok::r_square, Loc);
1439 ExprResult Constraint(ParseAsmStringLiteral());
1440 if (Constraint.isInvalid()) {
1441 SkipUntil(tok::r_paren);
1444 Constraints.push_back(Constraint.release());
1446 if (Tok.isNot(tok::l_paren)) {
1447 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1448 SkipUntil(tok::r_paren);
1452 // Read the parenthesized expression.
1453 SourceLocation OpenLoc = ConsumeParen();
1454 ExprResult Res(ParseExpression());
1455 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1456 if (Res.isInvalid()) {
1457 SkipUntil(tok::r_paren);
1460 Exprs.push_back(Res.release());
1461 // Eat the comma and continue parsing if it exists.
1462 if (Tok.isNot(tok::comma)) return false;
1469 Decl *Parser::ParseFunctionStatementBody(Decl *Decl) {
1470 assert(Tok.is(tok::l_brace));
1471 SourceLocation LBraceLoc = Tok.getLocation();
1473 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1474 "parsing function body");
1476 // Do not enter a scope for the brace, as the arguments are in the same scope
1477 // (the function body) as the body itself. Instead, just read the statement
1478 // list and put it into a CompoundStmt for safe keeping.
1479 StmtResult FnBody(ParseCompoundStatementBody());
1481 // If the function body could not be parsed, make a bogus compoundstmt.
1482 if (FnBody.isInvalid())
1483 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1484 MultiStmtArg(Actions), false);
1486 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1489 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1491 /// function-try-block:
1492 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1494 Decl *Parser::ParseFunctionTryBlock(Decl *Decl) {
1495 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1496 SourceLocation TryLoc = ConsumeToken();
1498 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1499 "parsing function try block");
1501 // Constructor initializer list?
1502 if (Tok.is(tok::colon))
1503 ParseConstructorInitializer(Decl);
1505 SourceLocation LBraceLoc = Tok.getLocation();
1506 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1507 // If we failed to parse the try-catch, we just give the function an empty
1508 // compound statement as the body.
1509 if (FnBody.isInvalid())
1510 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1511 MultiStmtArg(Actions), false);
1513 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1516 /// ParseCXXTryBlock - Parse a C++ try-block.
1519 /// 'try' compound-statement handler-seq
1521 StmtResult Parser::ParseCXXTryBlock(AttributeList* Attr) {
1522 // FIXME: Add attributes?
1525 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1527 SourceLocation TryLoc = ConsumeToken();
1528 return ParseCXXTryBlockCommon(TryLoc);
1531 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1532 /// function-try-block.
1535 /// 'try' compound-statement handler-seq
1537 /// function-try-block:
1538 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1541 /// handler handler-seq[opt]
1543 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1544 if (Tok.isNot(tok::l_brace))
1545 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1546 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1547 StmtResult TryBlock(ParseCompoundStatement(0));
1548 if (TryBlock.isInvalid())
1549 return move(TryBlock);
1551 StmtVector Handlers(Actions);
1552 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1553 CXX0XAttributeList Attr = ParseCXX0XAttributes();
1554 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
1557 if (Tok.isNot(tok::kw_catch))
1558 return StmtError(Diag(Tok, diag::err_expected_catch));
1559 while (Tok.is(tok::kw_catch)) {
1560 StmtResult Handler(ParseCXXCatchBlock());
1561 if (!Handler.isInvalid())
1562 Handlers.push_back(Handler.release());
1564 // Don't bother creating the full statement if we don't have any usable
1566 if (Handlers.empty())
1569 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
1572 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1575 /// 'catch' '(' exception-declaration ')' compound-statement
1577 /// exception-declaration:
1578 /// type-specifier-seq declarator
1579 /// type-specifier-seq abstract-declarator
1580 /// type-specifier-seq
1583 StmtResult Parser::ParseCXXCatchBlock() {
1584 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1586 SourceLocation CatchLoc = ConsumeToken();
1588 SourceLocation LParenLoc = Tok.getLocation();
1589 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1593 // The name in a catch exception-declaration is local to the handler and
1594 // shall not be redeclared in the outermost block of the handler.
1595 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1597 // exception-declaration is equivalent to '...' or a parameter-declaration
1598 // without default arguments.
1599 Decl *ExceptionDecl = 0;
1600 if (Tok.isNot(tok::ellipsis)) {
1602 if (ParseCXXTypeSpecifierSeq(DS))
1604 Declarator ExDecl(DS, Declarator::CXXCatchContext);
1605 ParseDeclarator(ExDecl);
1606 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
1610 if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
1613 if (Tok.isNot(tok::l_brace))
1614 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1616 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1617 StmtResult Block(ParseCompoundStatement(0));
1618 if (Block.isInvalid())
1621 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());