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/Parse/DeclSpec.h"
18 #include "clang/Parse/Scope.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/PrettyStackTrace.h"
21 #include "clang/Basic/SourceManager.h"
22 using namespace clang;
24 //===----------------------------------------------------------------------===//
25 // C99 6.8: Statements and Blocks.
26 //===----------------------------------------------------------------------===//
28 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
29 /// StatementOrDeclaration:
35 /// compound-statement
36 /// expression-statement
37 /// selection-statement
38 /// iteration-statement
40 /// [C++] declaration-statement
42 /// [OBC] objc-throw-statement
43 /// [OBC] objc-try-catch-statement
44 /// [OBC] objc-synchronized-statement
45 /// [GNU] asm-statement
46 /// [OMP] openmp-construct [TODO]
48 /// labeled-statement:
49 /// identifier ':' statement
50 /// 'case' constant-expression ':' statement
51 /// 'default' ':' statement
53 /// selection-statement:
57 /// iteration-statement:
62 /// expression-statement:
63 /// expression[opt] ';'
66 /// 'goto' identifier ';'
69 /// 'return' expression[opt] ';'
70 /// [GNU] 'goto' '*' expression ';'
72 /// [OBC] objc-throw-statement:
73 /// [OBC] '@' 'throw' expression ';'
74 /// [OBC] '@' 'throw' ';'
76 Parser::OwningStmtResult
77 Parser::ParseStatementOrDeclaration(bool OnlyStatement) {
78 const char *SemiError = 0;
79 OwningStmtResult Res(Actions);
81 ParenBraceBracketBalancer BalancerRAIIObj(*this);
83 CXX0XAttributeList Attr;
84 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
85 Attr = ParseCXX0XAttributes();
86 llvm::OwningPtr<AttributeList> AttrList(Attr.AttrList);
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.
91 tok::TokenKind Kind = Tok.getKind();
94 case tok::at: // May be a @try or @throw statement
96 AtLoc = ConsumeToken(); // consume @
97 return ParseObjCAtStatement(AtLoc);
100 case tok::code_completion:
101 Actions.CodeCompleteOrdinaryName(getCurScope(), Action::CCC_Statement);
102 ConsumeCodeCompletionToken();
103 return ParseStatementOrDeclaration(OnlyStatement);
105 case tok::identifier:
106 if (NextToken().is(tok::colon)) { // C99 6.8.1: labeled-statement
107 // identifier ':' statement
108 return ParseLabeledStatement(AttrList.take());
113 if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
114 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
115 AttrList.take(); //Passing 'Attr' to ParseDeclaration transfers ownership.
116 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext, DeclEnd,
118 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
121 if (Tok.is(tok::r_brace)) {
122 Diag(Tok, diag::err_expected_statement);
126 // FIXME: Use the attributes
127 // expression[opt] ';'
128 OwningExprResult Expr(ParseExpression());
129 if (Expr.isInvalid()) {
130 // If the expression is invalid, skip ahead to the next semicolon or '}'.
131 // Not doing this opens us up to the possibility of infinite loops if
132 // ParseExpression does not consume any tokens.
133 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
134 if (Tok.is(tok::semi))
138 // Otherwise, eat the semicolon.
139 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
140 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr));
143 case tok::kw_case: // C99 6.8.1: labeled-statement
144 return ParseCaseStatement(AttrList.take());
145 case tok::kw_default: // C99 6.8.1: labeled-statement
146 return ParseDefaultStatement(AttrList.take());
148 case tok::l_brace: // C99 6.8.2: compound-statement
149 return ParseCompoundStatement(AttrList.take());
150 case tok::semi: // C99 6.8.3p3: expression[opt] ';'
151 return Actions.ActOnNullStmt(ConsumeToken());
153 case tok::kw_if: // C99 6.8.4.1: if-statement
154 return ParseIfStatement(AttrList.take());
155 case tok::kw_switch: // C99 6.8.4.2: switch-statement
156 return ParseSwitchStatement(AttrList.take());
158 case tok::kw_while: // C99 6.8.5.1: while-statement
159 return ParseWhileStatement(AttrList.take());
160 case tok::kw_do: // C99 6.8.5.2: do-statement
161 Res = ParseDoStatement(AttrList.take());
162 SemiError = "do/while";
164 case tok::kw_for: // C99 6.8.5.3: for-statement
165 return ParseForStatement(AttrList.take());
167 case tok::kw_goto: // C99 6.8.6.1: goto-statement
168 Res = ParseGotoStatement(AttrList.take());
171 case tok::kw_continue: // C99 6.8.6.2: continue-statement
172 Res = ParseContinueStatement(AttrList.take());
173 SemiError = "continue";
175 case tok::kw_break: // C99 6.8.6.3: break-statement
176 Res = ParseBreakStatement(AttrList.take());
179 case tok::kw_return: // C99 6.8.6.4: return-statement
180 Res = ParseReturnStatement(AttrList.take());
181 SemiError = "return";
186 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
189 Res = ParseAsmStatement(msAsm);
190 if (msAsm) return move(Res);
195 case tok::kw_try: // C++ 15: try-block
196 return ParseCXXTryBlock(AttrList.take());
199 // If we reached this code, the statement must end in a semicolon.
200 if (Tok.is(tok::semi)) {
202 } else if (!Res.isInvalid()) {
203 // If the result was valid, then we do want to diagnose this. Use
204 // ExpectAndConsume to emit the diagnostic, even though we know it won't
206 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
207 // Skip until we see a } or ;, but don't eat it.
208 SkipUntil(tok::r_brace, true, true);
214 /// ParseLabeledStatement - We have an identifier and a ':' after it.
216 /// labeled-statement:
217 /// identifier ':' statement
218 /// [GNU] identifier ':' attributes[opt] statement
220 Parser::OwningStmtResult Parser::ParseLabeledStatement(AttributeList *Attr) {
221 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
222 "Not an identifier!");
224 llvm::OwningPtr<AttributeList> AttrList(Attr);
225 Token IdentTok = Tok; // Save the whole token.
226 ConsumeToken(); // eat the identifier.
228 assert(Tok.is(tok::colon) && "Not a label!");
230 // identifier ':' statement
231 SourceLocation ColonLoc = ConsumeToken();
233 // Read label attributes, if present.
234 if (Tok.is(tok::kw___attribute))
235 AttrList.reset(addAttributeLists(AttrList.take(), ParseGNUAttributes()));
237 OwningStmtResult SubStmt(ParseStatement());
239 // Broken substmt shouldn't prevent the label from being added to the AST.
240 if (SubStmt.isInvalid())
241 SubStmt = Actions.ActOnNullStmt(ColonLoc);
243 // FIXME: use attributes?
244 return Actions.ActOnLabelStmt(IdentTok.getLocation(),
245 IdentTok.getIdentifierInfo(),
246 ColonLoc, move(SubStmt));
249 /// ParseCaseStatement
250 /// labeled-statement:
251 /// 'case' constant-expression ':' statement
252 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
254 Parser::OwningStmtResult Parser::ParseCaseStatement(AttributeList *Attr) {
255 assert(Tok.is(tok::kw_case) && "Not a case stmt!");
256 // FIXME: Use attributes?
259 // It is very very common for code to contain many case statements recursively
260 // nested, as in (but usually without indentation):
267 // Parsing this naively works, but is both inefficient and can cause us to run
268 // out of stack space in our recursive descent parser. As a special case,
269 // flatten this recursion into an iterative loop. This is complex and gross,
270 // but all the grossness is constrained to ParseCaseStatement (and some
271 // wierdness in the actions), so this is just local grossness :).
273 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
275 OwningStmtResult TopLevelCase(Actions, true);
277 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
278 // gets updated each time a new case is parsed, and whose body is unset so
279 // far. When parsing 'case 4', this is the 'case 3' node.
280 StmtTy *DeepestParsedCaseStmt = 0;
282 // While we have case statements, eat and stack them.
284 SourceLocation CaseLoc = ConsumeToken(); // eat the 'case'.
286 if (Tok.is(tok::code_completion)) {
287 Actions.CodeCompleteCase(getCurScope());
288 ConsumeCodeCompletionToken();
291 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
292 /// Disable this form of error recovery while we're parsing the case
294 ColonProtectionRAIIObject ColonProtection(*this);
296 OwningExprResult LHS(ParseConstantExpression());
297 if (LHS.isInvalid()) {
298 SkipUntil(tok::colon);
302 // GNU case range extension.
303 SourceLocation DotDotDotLoc;
304 OwningExprResult RHS(Actions);
305 if (Tok.is(tok::ellipsis)) {
306 Diag(Tok, diag::ext_gnu_case_range);
307 DotDotDotLoc = ConsumeToken();
309 RHS = ParseConstantExpression();
310 if (RHS.isInvalid()) {
311 SkipUntil(tok::colon);
316 ColonProtection.restore();
318 if (Tok.isNot(tok::colon)) {
319 Diag(Tok, diag::err_expected_colon_after) << "'case'";
320 SkipUntil(tok::colon);
324 SourceLocation ColonLoc = ConsumeToken();
326 OwningStmtResult Case =
327 Actions.ActOnCaseStmt(CaseLoc, move(LHS), DotDotDotLoc,
328 move(RHS), ColonLoc);
330 // If we had a sema error parsing this case, then just ignore it and
331 // continue parsing the sub-stmt.
332 if (Case.isInvalid()) {
333 if (TopLevelCase.isInvalid()) // No parsed case stmts.
334 return ParseStatement();
335 // Otherwise, just don't add it as a nested case.
337 // If this is the first case statement we parsed, it becomes TopLevelCase.
338 // Otherwise we link it into the current chain.
339 StmtTy *NextDeepest = Case.get();
340 if (TopLevelCase.isInvalid())
341 TopLevelCase = move(Case);
343 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, move(Case));
344 DeepestParsedCaseStmt = NextDeepest;
347 // Handle all case statements.
348 } while (Tok.is(tok::kw_case));
350 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
352 // If we found a non-case statement, start by parsing it.
353 OwningStmtResult SubStmt(Actions);
355 if (Tok.isNot(tok::r_brace)) {
356 SubStmt = ParseStatement();
358 // Nicely diagnose the common error "switch (X) { case 4: }", which is
360 // FIXME: add insertion hint.
361 Diag(Tok, diag::err_label_end_of_compound_statement);
365 // Broken sub-stmt shouldn't prevent forming the case statement properly.
366 if (SubStmt.isInvalid())
367 SubStmt = Actions.ActOnNullStmt(SourceLocation());
369 // Install the body into the most deeply-nested case.
370 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, move(SubStmt));
372 // Return the top level parsed statement tree.
373 return move(TopLevelCase);
376 /// ParseDefaultStatement
377 /// labeled-statement:
378 /// 'default' ':' statement
379 /// Note that this does not parse the 'statement' at the end.
381 Parser::OwningStmtResult Parser::ParseDefaultStatement(AttributeList *Attr) {
382 //FIXME: Use attributes?
385 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
386 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
388 if (Tok.isNot(tok::colon)) {
389 Diag(Tok, diag::err_expected_colon_after) << "'default'";
390 SkipUntil(tok::colon);
394 SourceLocation ColonLoc = ConsumeToken();
396 // Diagnose the common error "switch (X) {... default: }", which is not valid.
397 if (Tok.is(tok::r_brace)) {
398 Diag(Tok, diag::err_label_end_of_compound_statement);
402 OwningStmtResult SubStmt(ParseStatement());
403 if (SubStmt.isInvalid())
406 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
407 move(SubStmt), getCurScope());
411 /// ParseCompoundStatement - Parse a "{}" block.
413 /// compound-statement: [C99 6.8.2]
414 /// { block-item-list[opt] }
415 /// [GNU] { label-declarations block-item-list } [TODO]
419 /// block-item-list block-item
423 /// [GNU] '__extension__' declaration
425 /// [OMP] openmp-directive [TODO]
427 /// [GNU] label-declarations:
428 /// [GNU] label-declaration
429 /// [GNU] label-declarations label-declaration
431 /// [GNU] label-declaration:
432 /// [GNU] '__label__' identifier-list ';'
434 /// [OMP] openmp-directive: [TODO]
435 /// [OMP] barrier-directive
436 /// [OMP] flush-directive
438 Parser::OwningStmtResult Parser::ParseCompoundStatement(AttributeList *Attr,
440 //FIXME: Use attributes?
443 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
445 // Enter a scope to hold everything within the compound stmt. Compound
446 // statements can always hold declarations.
447 ParseScope CompoundScope(this, Scope::DeclScope);
449 // Parse the statements in the body.
450 return ParseCompoundStatementBody(isStmtExpr);
454 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
455 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
456 /// consume the '}' at the end of the block. It does not manipulate the scope
458 Parser::OwningStmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
459 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
461 "in compound statement ('{}')");
463 SourceLocation LBraceLoc = ConsumeBrace(); // eat the '{'.
465 // TODO: "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
466 // only allowed at the start of a compound stmt regardless of the language.
468 typedef StmtVector StmtsTy;
469 StmtsTy Stmts(Actions);
470 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
471 OwningStmtResult R(Actions);
472 if (Tok.isNot(tok::kw___extension__)) {
473 R = ParseStatementOrDeclaration(false);
475 // __extension__ can start declarations and it can also be a unary
476 // operator for expressions. Consume multiple __extension__ markers here
477 // until we can determine which is which.
478 // FIXME: This loses extension expressions in the AST!
479 SourceLocation ExtLoc = ConsumeToken();
480 while (Tok.is(tok::kw___extension__))
483 CXX0XAttributeList Attr;
484 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
485 Attr = ParseCXX0XAttributes();
487 // If this is the start of a declaration, parse it as such.
488 if (isDeclarationStatement()) {
489 // __extension__ silences extension warnings in the subdeclaration.
490 // FIXME: Save the __extension__ on the decl as a node somehow?
491 ExtensionRAIIObject O(Diags);
493 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
494 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
496 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
498 // Otherwise this was a unary __extension__ marker.
499 OwningExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
501 if (Res.isInvalid()) {
502 SkipUntil(tok::semi);
506 // FIXME: Use attributes?
507 // Eat the semicolon at the end of stmt and convert the expr into a
509 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
510 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res));
515 Stmts.push_back(R.release());
518 // We broke out of the while loop because we found a '}' or EOF.
519 if (Tok.isNot(tok::r_brace)) {
520 Diag(Tok, diag::err_expected_rbrace);
524 SourceLocation RBraceLoc = ConsumeBrace();
525 return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
529 /// ParseParenExprOrCondition:
530 /// [C ] '(' expression ')'
531 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
533 /// This function parses and performs error recovery on the specified condition
534 /// or expression (depending on whether we're in C++ or C mode). This function
535 /// goes out of its way to recover well. It returns true if there was a parser
536 /// error (the right paren couldn't be found), which indicates that the caller
537 /// should try to recover harder. It returns false if the condition is
538 /// successfully parsed. Note that a successful parse can still have semantic
539 /// errors in the condition.
540 bool Parser::ParseParenExprOrCondition(OwningExprResult &ExprResult,
541 DeclPtrTy &DeclResult,
543 bool ConvertToBoolean) {
544 bool ParseError = false;
546 SourceLocation LParenLoc = ConsumeParen();
547 if (getLang().CPlusPlus)
548 ParseError = ParseCXXCondition(ExprResult, DeclResult, Loc,
551 ExprResult = ParseExpression();
552 DeclResult = DeclPtrTy();
554 // If required, convert to a boolean value.
555 if (!ExprResult.isInvalid() && ConvertToBoolean)
557 = Actions.ActOnBooleanCondition(getCurScope(), Loc, move(ExprResult));
560 // If the parser was confused by the condition and we don't have a ')', try to
561 // recover by skipping ahead to a semi and bailing out. If condexp is
562 // semantically invalid but we have well formed code, keep going.
563 if (ExprResult.isInvalid() && !DeclResult.get() && Tok.isNot(tok::r_paren)) {
564 SkipUntil(tok::semi);
565 // Skipping may have stopped if it found the containing ')'. If so, we can
566 // continue parsing the if statement.
567 if (Tok.isNot(tok::r_paren))
571 // Otherwise the condition is valid or the rparen is present.
572 MatchRHSPunctuation(tok::r_paren, LParenLoc);
578 /// if-statement: [C99 6.8.4.1]
579 /// 'if' '(' expression ')' statement
580 /// 'if' '(' expression ')' statement 'else' statement
581 /// [C++] 'if' '(' condition ')' statement
582 /// [C++] 'if' '(' condition ')' statement 'else' statement
584 Parser::OwningStmtResult Parser::ParseIfStatement(AttributeList *Attr) {
585 // FIXME: Use attributes?
588 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
589 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
591 if (Tok.isNot(tok::l_paren)) {
592 Diag(Tok, diag::err_expected_lparen_after) << "if";
593 SkipUntil(tok::semi);
597 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
599 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
603 // A name introduced by a declaration in a condition is in scope from its
604 // point of declaration until the end of the substatements controlled by the
607 // Names declared in the for-init-statement, and in the condition of if,
608 // while, for, and switch statements are local to the if, while, for, or
609 // switch statement (including the controlled statement).
611 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
613 // Parse the condition.
614 OwningExprResult CondExp(Actions);
616 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
619 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp));
621 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
622 // there is no compound stmt. C90 does not have this clause. We only do this
623 // if the body isn't a compound statement to avoid push/pop in common cases.
626 // The substatement in a selection-statement (each substatement, in the else
627 // form of the if statement) implicitly defines a local scope.
629 // For C++ we create a scope for the condition and a new scope for
630 // substatements because:
631 // -When the 'then' scope exits, we want the condition declaration to still be
632 // active for the 'else' scope too.
633 // -Sema will detect name clashes by considering declarations of a
634 // 'ControlScope' as part of its direct subscope.
635 // -If we wanted the condition and substatement to be in the same scope, we
636 // would have to notify ParseStatement not to create a new scope. It's
637 // simpler to let it create a new scope.
639 ParseScope InnerScope(this, Scope::DeclScope,
640 C99orCXX && Tok.isNot(tok::l_brace));
642 // Read the 'then' stmt.
643 SourceLocation ThenStmtLoc = Tok.getLocation();
644 OwningStmtResult ThenStmt(ParseStatement());
646 // Pop the 'if' scope if needed.
649 // If it has an else, parse it.
650 SourceLocation ElseLoc;
651 SourceLocation ElseStmtLoc;
652 OwningStmtResult ElseStmt(Actions);
654 if (Tok.is(tok::kw_else)) {
655 ElseLoc = ConsumeToken();
656 ElseStmtLoc = Tok.getLocation();
658 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
659 // there is no compound stmt. C90 does not have this clause. We only do
660 // this if the body isn't a compound statement to avoid push/pop in common
664 // The substatement in a selection-statement (each substatement, in the else
665 // form of the if statement) implicitly defines a local scope.
667 ParseScope InnerScope(this, Scope::DeclScope,
668 C99orCXX && Tok.isNot(tok::l_brace));
670 // Regardless of whether or not InnerScope actually pushed a scope, set the
671 // ElseScope flag for the innermost scope so we can diagnose use of the if
672 // condition variable in C++.
673 unsigned OldFlags = getCurScope()->getFlags();
674 getCurScope()->setFlags(OldFlags | Scope::ElseScope);
675 ElseStmt = ParseStatement();
676 getCurScope()->setFlags(OldFlags);
678 // Pop the 'else' scope if needed.
684 // If the condition was invalid, discard the if statement. We could recover
685 // better by replacing it with a valid expr, but don't do that yet.
686 if (CondExp.isInvalid() && !CondVar.get())
689 // If the then or else stmt is invalid and the other is valid (and present),
690 // make turn the invalid one into a null stmt to avoid dropping the other
691 // part. If both are invalid, return error.
692 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
693 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
694 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
695 // Both invalid, or one is invalid and other is non-present: return error.
699 // Now if either are invalid, replace with a ';'.
700 if (ThenStmt.isInvalid())
701 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
702 if (ElseStmt.isInvalid())
703 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
705 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, move(ThenStmt),
706 ElseLoc, move(ElseStmt));
709 /// ParseSwitchStatement
710 /// switch-statement:
711 /// 'switch' '(' expression ')' statement
712 /// [C++] 'switch' '(' condition ')' statement
713 Parser::OwningStmtResult Parser::ParseSwitchStatement(AttributeList *Attr) {
714 // FIXME: Use attributes?
717 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
718 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
720 if (Tok.isNot(tok::l_paren)) {
721 Diag(Tok, diag::err_expected_lparen_after) << "switch";
722 SkipUntil(tok::semi);
726 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
728 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
729 // not the case for C90. Start the switch scope.
732 // A name introduced by a declaration in a condition is in scope from its
733 // point of declaration until the end of the substatements controlled by the
736 // Names declared in the for-init-statement, and in the condition of if,
737 // while, for, and switch statements are local to the if, while, for, or
738 // switch statement (including the controlled statement).
740 unsigned ScopeFlags = Scope::BreakScope;
742 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
743 ParseScope SwitchScope(this, ScopeFlags);
745 // Parse the condition.
746 OwningExprResult Cond(Actions);
748 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
751 OwningStmtResult Switch
752 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, move(Cond), CondVar);
754 if (Switch.isInvalid()) {
755 // Skip the switch body.
756 // FIXME: This is not optimal recovery, but parsing the body is more
757 // dangerous due to the presence of case and default statements, which
758 // will have no place to connect back with the switch.
759 if (Tok.is(tok::l_brace)) {
761 SkipUntil(tok::r_brace, false, false);
763 SkipUntil(tok::semi);
767 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
768 // there is no compound stmt. C90 does not have this clause. We only do this
769 // if the body isn't a compound statement to avoid push/pop in common cases.
772 // The substatement in a selection-statement (each substatement, in the else
773 // form of the if statement) implicitly defines a local scope.
775 // See comments in ParseIfStatement for why we create a scope for the
776 // condition and a new scope for substatement in C++.
778 ParseScope InnerScope(this, Scope::DeclScope,
779 C99orCXX && Tok.isNot(tok::l_brace));
781 // Read the body statement.
782 OwningStmtResult Body(ParseStatement());
788 if (Body.isInvalid())
789 // FIXME: Remove the case statement list from the Switch statement.
790 Body = Actions.ActOnNullStmt(Tok.getLocation());
792 return Actions.ActOnFinishSwitchStmt(SwitchLoc, move(Switch), move(Body));
795 /// ParseWhileStatement
796 /// while-statement: [C99 6.8.5.1]
797 /// 'while' '(' expression ')' statement
798 /// [C++] 'while' '(' condition ')' statement
799 Parser::OwningStmtResult Parser::ParseWhileStatement(AttributeList *Attr) {
800 // FIXME: Use attributes?
803 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
804 SourceLocation WhileLoc = Tok.getLocation();
805 ConsumeToken(); // eat the 'while'.
807 if (Tok.isNot(tok::l_paren)) {
808 Diag(Tok, diag::err_expected_lparen_after) << "while";
809 SkipUntil(tok::semi);
813 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
815 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
816 // the case for C90. Start the loop scope.
819 // A name introduced by a declaration in a condition is in scope from its
820 // point of declaration until the end of the substatements controlled by the
823 // Names declared in the for-init-statement, and in the condition of if,
824 // while, for, and switch statements are local to the if, while, for, or
825 // switch statement (including the controlled statement).
829 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
830 Scope::DeclScope | Scope::ControlScope;
832 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
833 ParseScope WhileScope(this, ScopeFlags);
835 // Parse the condition.
836 OwningExprResult Cond(Actions);
838 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
841 FullExprArg FullCond(Actions.MakeFullExpr(Cond));
843 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
844 // there is no compound stmt. C90 does not have this clause. We only do this
845 // if the body isn't a compound statement to avoid push/pop in common cases.
848 // The substatement in an iteration-statement implicitly defines a local scope
849 // which is entered and exited each time through the loop.
851 // See comments in ParseIfStatement for why we create a scope for the
852 // condition and a new scope for substatement in C++.
854 ParseScope InnerScope(this, Scope::DeclScope,
855 C99orCXX && Tok.isNot(tok::l_brace));
857 // Read the body statement.
858 OwningStmtResult Body(ParseStatement());
860 // Pop the body scope if needed.
864 if ((Cond.isInvalid() && !CondVar.get()) || Body.isInvalid())
867 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, move(Body));
871 /// do-statement: [C99 6.8.5.2]
872 /// 'do' statement 'while' '(' expression ')' ';'
873 /// Note: this lets the caller parse the end ';'.
874 Parser::OwningStmtResult Parser::ParseDoStatement(AttributeList *Attr) {
875 // FIXME: Use attributes?
878 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
879 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
881 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
882 // the case for C90. Start the loop scope.
885 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
887 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
889 ParseScope DoScope(this, ScopeFlags);
891 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
892 // there is no compound stmt. C90 does not have this clause. We only do this
893 // if the body isn't a compound statement to avoid push/pop in common cases.
896 // The substatement in an iteration-statement implicitly defines a local scope
897 // which is entered and exited each time through the loop.
899 ParseScope InnerScope(this, Scope::DeclScope,
900 (getLang().C99 || getLang().CPlusPlus) &&
901 Tok.isNot(tok::l_brace));
903 // Read the body statement.
904 OwningStmtResult Body(ParseStatement());
906 // Pop the body scope if needed.
909 if (Tok.isNot(tok::kw_while)) {
910 if (!Body.isInvalid()) {
911 Diag(Tok, diag::err_expected_while);
912 Diag(DoLoc, diag::note_matching) << "do";
913 SkipUntil(tok::semi, false, true);
917 SourceLocation WhileLoc = ConsumeToken();
919 if (Tok.isNot(tok::l_paren)) {
920 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
921 SkipUntil(tok::semi, false, true);
925 // Parse the parenthesized condition.
926 SourceLocation LPLoc = ConsumeParen();
927 OwningExprResult Cond = ParseExpression();
928 SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
931 if (Cond.isInvalid() || Body.isInvalid())
934 return Actions.ActOnDoStmt(DoLoc, move(Body), WhileLoc, LPLoc,
938 /// ParseForStatement
939 /// for-statement: [C99 6.8.5.3]
940 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
941 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
942 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
944 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
945 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
947 /// [C++] for-init-statement:
948 /// [C++] expression-statement
949 /// [C++] simple-declaration
951 Parser::OwningStmtResult Parser::ParseForStatement(AttributeList *Attr) {
952 // FIXME: Use attributes?
955 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
956 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
958 if (Tok.isNot(tok::l_paren)) {
959 Diag(Tok, diag::err_expected_lparen_after) << "for";
960 SkipUntil(tok::semi);
964 bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
966 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
967 // the case for C90. Start the loop scope.
970 // A name introduced by a declaration in a condition is in scope from its
971 // point of declaration until the end of the substatements controlled by the
974 // Names declared in the for-init-statement, and in the condition of if,
975 // while, for, and switch statements are local to the if, while, for, or
976 // switch statement (including the controlled statement).
978 // Names declared in the for-init-statement are in the same declarative-region
979 // as those declared in the condition.
983 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
984 Scope::DeclScope | Scope::ControlScope;
986 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
988 ParseScope ForScope(this, ScopeFlags);
990 SourceLocation LParenLoc = ConsumeParen();
991 OwningExprResult Value(Actions);
993 bool ForEach = false;
994 OwningStmtResult FirstPart(Actions);
995 bool SecondPartIsInvalid = false;
996 FullExprArg SecondPart(Actions);
997 OwningExprResult Collection(Actions);
998 FullExprArg ThirdPart(Actions);
1001 if (Tok.is(tok::code_completion)) {
1002 Actions.CodeCompleteOrdinaryName(getCurScope(),
1003 C99orCXXorObjC? Action::CCC_ForInit
1004 : Action::CCC_Expression);
1005 ConsumeCodeCompletionToken();
1008 // Parse the first part of the for specifier.
1009 if (Tok.is(tok::semi)) { // for (;
1010 // no first part, eat the ';'.
1012 } else if (isSimpleDeclaration()) { // for (int X = 4;
1013 // Parse declaration, which eats the ';'.
1014 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1015 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1017 AttributeList *AttrList = 0;
1018 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1019 AttrList = ParseCXX0XAttributes().AttrList;
1021 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1022 DeclGroupPtrTy DG = ParseSimpleDeclaration(Declarator::ForContext, DeclEnd,
1024 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1026 if (Tok.is(tok::semi)) { // for (int x = 4;
1028 } else if ((ForEach = isTokIdentifier_in())) {
1029 Actions.ActOnForEachDeclStmt(DG);
1030 // ObjC: for (id x in expr)
1031 ConsumeToken(); // consume 'in'
1032 Collection = ParseExpression();
1034 Diag(Tok, diag::err_expected_semi_for);
1035 SkipUntil(tok::semi);
1038 Value = ParseExpression();
1040 // Turn the expression into a stmt.
1041 if (!Value.isInvalid())
1042 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value));
1044 if (Tok.is(tok::semi)) {
1046 } else if ((ForEach = isTokIdentifier_in())) {
1047 ConsumeToken(); // consume 'in'
1048 Collection = ParseExpression();
1050 if (!Value.isInvalid()) Diag(Tok, diag::err_expected_semi_for);
1051 SkipUntil(tok::semi);
1055 assert(!SecondPart->get() && "Shouldn't have a second expression yet.");
1056 // Parse the second part of the for specifier.
1057 if (Tok.is(tok::semi)) { // for (...;;
1060 OwningExprResult Second(Actions);
1061 if (getLang().CPlusPlus)
1062 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1064 Second = ParseExpression();
1065 if (!Second.isInvalid())
1066 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1069 SecondPartIsInvalid = Second.isInvalid();
1070 SecondPart = Actions.MakeFullExpr(Second);
1073 if (Tok.is(tok::semi)) {
1076 if (!SecondPartIsInvalid || SecondVar.get())
1077 Diag(Tok, diag::err_expected_semi_for);
1078 SkipUntil(tok::semi);
1081 // Parse the third part of the for specifier.
1082 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1083 OwningExprResult Third = ParseExpression();
1084 ThirdPart = Actions.MakeFullExpr(Third);
1088 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1090 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1091 // there is no compound stmt. C90 does not have this clause. We only do this
1092 // if the body isn't a compound statement to avoid push/pop in common cases.
1095 // The substatement in an iteration-statement implicitly defines a local scope
1096 // which is entered and exited each time through the loop.
1098 // See comments in ParseIfStatement for why we create a scope for
1099 // for-init-statement/condition and a new scope for substatement in C++.
1101 ParseScope InnerScope(this, Scope::DeclScope,
1102 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1104 // Read the body statement.
1105 OwningStmtResult Body(ParseStatement());
1107 // Pop the body scope if needed.
1110 // Leave the for-scope.
1113 if (Body.isInvalid())
1117 return Actions.ActOnForStmt(ForLoc, LParenLoc, move(FirstPart), SecondPart,
1118 SecondVar, ThirdPart, RParenLoc, move(Body));
1120 // FIXME: It isn't clear how to communicate the late destruction of
1121 // C++ temporaries used to create the collection.
1122 return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc, move(FirstPart),
1123 move(Collection), RParenLoc,
1127 /// ParseGotoStatement
1129 /// 'goto' identifier ';'
1130 /// [GNU] 'goto' '*' expression ';'
1132 /// Note: this lets the caller parse the end ';'.
1134 Parser::OwningStmtResult Parser::ParseGotoStatement(AttributeList *Attr) {
1135 // FIXME: Use attributes?
1138 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1139 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1141 OwningStmtResult Res(Actions);
1142 if (Tok.is(tok::identifier)) {
1143 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(),
1144 Tok.getIdentifierInfo());
1146 } else if (Tok.is(tok::star)) {
1147 // GNU indirect goto extension.
1148 Diag(Tok, diag::ext_gnu_indirect_goto);
1149 SourceLocation StarLoc = ConsumeToken();
1150 OwningExprResult R(ParseExpression());
1151 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1152 SkipUntil(tok::semi, false, true);
1155 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, move(R));
1157 Diag(Tok, diag::err_expected_ident);
1164 /// ParseContinueStatement
1168 /// Note: this lets the caller parse the end ';'.
1170 Parser::OwningStmtResult Parser::ParseContinueStatement(AttributeList *Attr) {
1171 // FIXME: Use attributes?
1174 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1175 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1178 /// ParseBreakStatement
1182 /// Note: this lets the caller parse the end ';'.
1184 Parser::OwningStmtResult Parser::ParseBreakStatement(AttributeList *Attr) {
1185 // FIXME: Use attributes?
1188 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1189 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1192 /// ParseReturnStatement
1194 /// 'return' expression[opt] ';'
1195 Parser::OwningStmtResult Parser::ParseReturnStatement(AttributeList *Attr) {
1196 // FIXME: Use attributes?
1199 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1200 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1202 OwningExprResult R(Actions);
1203 if (Tok.isNot(tok::semi)) {
1204 if (Tok.is(tok::code_completion)) {
1205 Actions.CodeCompleteReturn(getCurScope());
1206 ConsumeCodeCompletionToken();
1207 SkipUntil(tok::semi, false, true);
1211 R = ParseExpression();
1212 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1213 SkipUntil(tok::semi, false, true);
1217 return Actions.ActOnReturnStmt(ReturnLoc, move(R));
1220 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1221 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1222 Parser::OwningStmtResult Parser::FuzzyParseMicrosoftAsmStatement() {
1223 if (Tok.is(tok::l_brace)) {
1224 unsigned short savedBraceCount = BraceCount;
1227 } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1229 // From the MS website: If used without braces, the __asm keyword means
1230 // that the rest of the line is an assembly-language statement.
1231 SourceManager &SrcMgr = PP.getSourceManager();
1232 SourceLocation TokLoc = Tok.getLocation();
1233 unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1236 TokLoc = Tok.getLocation();
1237 } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1238 Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1239 Tok.isNot(tok::eof));
1242 t.setKind(tok::string_literal);
1243 t.setLiteralData("\"FIXME: not done\"");
1244 t.clearFlag(Token::NeedsCleaning);
1246 OwningExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1247 ExprVector Constraints(Actions);
1248 ExprVector Exprs(Actions);
1249 ExprVector Clobbers(Actions);
1250 return Actions.ActOnAsmStmt(Tok.getLocation(), true, true, 0, 0, 0,
1251 move_arg(Constraints), move_arg(Exprs),
1252 move(AsmString), move_arg(Clobbers),
1253 Tok.getLocation(), true);
1256 /// ParseAsmStatement - Parse a GNU extended asm statement.
1258 /// gnu-asm-statement
1259 /// ms-asm-statement
1261 /// [GNU] gnu-asm-statement:
1262 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1264 /// [GNU] asm-argument:
1265 /// asm-string-literal
1266 /// asm-string-literal ':' asm-operands[opt]
1267 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1268 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1269 /// ':' asm-clobbers
1271 /// [GNU] asm-clobbers:
1272 /// asm-string-literal
1273 /// asm-clobbers ',' asm-string-literal
1275 /// [MS] ms-asm-statement:
1276 /// '__asm' assembly-instruction ';'[opt]
1277 /// '__asm' '{' assembly-instruction-list '}' ';'[opt]
1279 /// [MS] assembly-instruction-list:
1280 /// assembly-instruction ';'[opt]
1281 /// assembly-instruction-list ';' assembly-instruction ';'[opt]
1283 Parser::OwningStmtResult Parser::ParseAsmStatement(bool &msAsm) {
1284 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1285 SourceLocation AsmLoc = ConsumeToken();
1287 if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1289 return FuzzyParseMicrosoftAsmStatement();
1292 SourceLocation Loc = Tok.getLocation();
1293 ParseTypeQualifierListOpt(DS, true, false);
1295 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1296 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1297 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1298 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1299 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1301 // Remember if this was a volatile asm.
1302 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1303 if (Tok.isNot(tok::l_paren)) {
1304 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1305 SkipUntil(tok::r_paren);
1308 Loc = ConsumeParen();
1310 OwningExprResult AsmString(ParseAsmStringLiteral());
1311 if (AsmString.isInvalid())
1314 llvm::SmallVector<IdentifierInfo *, 4> Names;
1315 ExprVector Constraints(Actions);
1316 ExprVector Exprs(Actions);
1317 ExprVector Clobbers(Actions);
1319 if (Tok.is(tok::r_paren)) {
1320 // We have a simple asm expression like 'asm("foo")'.
1321 SourceLocation RParenLoc = ConsumeParen();
1322 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1323 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1324 move_arg(Constraints), move_arg(Exprs),
1325 move(AsmString), move_arg(Clobbers),
1329 // Parse Outputs, if present.
1330 bool AteExtraColon = false;
1331 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1332 // In C++ mode, parse "::" like ": :".
1333 AteExtraColon = Tok.is(tok::coloncolon);
1336 if (!AteExtraColon &&
1337 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1341 unsigned NumOutputs = Names.size();
1343 // Parse Inputs, if present.
1344 if (AteExtraColon ||
1345 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1346 // In C++ mode, parse "::" like ": :".
1348 AteExtraColon = false;
1350 AteExtraColon = Tok.is(tok::coloncolon);
1354 if (!AteExtraColon &&
1355 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1359 assert(Names.size() == Constraints.size() &&
1360 Constraints.size() == Exprs.size() &&
1361 "Input operand size mismatch!");
1363 unsigned NumInputs = Names.size() - NumOutputs;
1365 // Parse the clobbers, if present.
1366 if (AteExtraColon || Tok.is(tok::colon)) {
1370 // Parse the asm-string list for clobbers.
1372 OwningExprResult Clobber(ParseAsmStringLiteral());
1374 if (Clobber.isInvalid())
1377 Clobbers.push_back(Clobber.release());
1379 if (Tok.isNot(tok::comma)) break;
1384 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1385 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1386 NumOutputs, NumInputs, Names.data(),
1387 move_arg(Constraints), move_arg(Exprs),
1388 move(AsmString), move_arg(Clobbers),
1392 /// ParseAsmOperands - Parse the asm-operands production as used by
1393 /// asm-statement, assuming the leading ':' token was eaten.
1395 /// [GNU] asm-operands:
1397 /// asm-operands ',' asm-operand
1399 /// [GNU] asm-operand:
1400 /// asm-string-literal '(' expression ')'
1401 /// '[' identifier ']' asm-string-literal '(' expression ')'
1404 // FIXME: Avoid unnecessary std::string trashing.
1405 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1406 llvm::SmallVectorImpl<ExprTy *> &Constraints,
1407 llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1408 // 'asm-operands' isn't present?
1409 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1413 // Read the [id] if present.
1414 if (Tok.is(tok::l_square)) {
1415 SourceLocation Loc = ConsumeBracket();
1417 if (Tok.isNot(tok::identifier)) {
1418 Diag(Tok, diag::err_expected_ident);
1419 SkipUntil(tok::r_paren);
1423 IdentifierInfo *II = Tok.getIdentifierInfo();
1426 Names.push_back(II);
1427 MatchRHSPunctuation(tok::r_square, Loc);
1431 OwningExprResult Constraint(ParseAsmStringLiteral());
1432 if (Constraint.isInvalid()) {
1433 SkipUntil(tok::r_paren);
1436 Constraints.push_back(Constraint.release());
1438 if (Tok.isNot(tok::l_paren)) {
1439 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1440 SkipUntil(tok::r_paren);
1444 // Read the parenthesized expression.
1445 SourceLocation OpenLoc = ConsumeParen();
1446 OwningExprResult Res(ParseExpression());
1447 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1448 if (Res.isInvalid()) {
1449 SkipUntil(tok::r_paren);
1452 Exprs.push_back(Res.release());
1453 // Eat the comma and continue parsing if it exists.
1454 if (Tok.isNot(tok::comma)) return false;
1461 Parser::DeclPtrTy Parser::ParseFunctionStatementBody(DeclPtrTy Decl) {
1462 assert(Tok.is(tok::l_brace));
1463 SourceLocation LBraceLoc = Tok.getLocation();
1465 PrettyStackTraceActionsDecl CrashInfo(Decl, LBraceLoc, Actions,
1466 PP.getSourceManager(),
1467 "parsing function body");
1469 // Do not enter a scope for the brace, as the arguments are in the same scope
1470 // (the function body) as the body itself. Instead, just read the statement
1471 // list and put it into a CompoundStmt for safe keeping.
1472 OwningStmtResult FnBody(ParseCompoundStatementBody());
1474 // If the function body could not be parsed, make a bogus compoundstmt.
1475 if (FnBody.isInvalid())
1476 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1477 MultiStmtArg(Actions), false);
1479 return Actions.ActOnFinishFunctionBody(Decl, move(FnBody));
1482 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1484 /// function-try-block:
1485 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1487 Parser::DeclPtrTy Parser::ParseFunctionTryBlock(DeclPtrTy Decl) {
1488 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1489 SourceLocation TryLoc = ConsumeToken();
1491 PrettyStackTraceActionsDecl CrashInfo(Decl, TryLoc, Actions,
1492 PP.getSourceManager(),
1493 "parsing function try block");
1495 // Constructor initializer list?
1496 if (Tok.is(tok::colon))
1497 ParseConstructorInitializer(Decl);
1499 SourceLocation LBraceLoc = Tok.getLocation();
1500 OwningStmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1501 // If we failed to parse the try-catch, we just give the function an empty
1502 // compound statement as the body.
1503 if (FnBody.isInvalid())
1504 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1505 MultiStmtArg(Actions), false);
1507 return Actions.ActOnFinishFunctionBody(Decl, move(FnBody));
1510 /// ParseCXXTryBlock - Parse a C++ try-block.
1513 /// 'try' compound-statement handler-seq
1515 Parser::OwningStmtResult Parser::ParseCXXTryBlock(AttributeList* Attr) {
1516 // FIXME: Add attributes?
1519 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1521 SourceLocation TryLoc = ConsumeToken();
1522 return ParseCXXTryBlockCommon(TryLoc);
1525 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1526 /// function-try-block.
1529 /// 'try' compound-statement handler-seq
1531 /// function-try-block:
1532 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1535 /// handler handler-seq[opt]
1537 Parser::OwningStmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1538 if (Tok.isNot(tok::l_brace))
1539 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1540 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1541 OwningStmtResult TryBlock(ParseCompoundStatement(0));
1542 if (TryBlock.isInvalid())
1543 return move(TryBlock);
1545 StmtVector Handlers(Actions);
1546 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1547 CXX0XAttributeList Attr = ParseCXX0XAttributes();
1548 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
1551 if (Tok.isNot(tok::kw_catch))
1552 return StmtError(Diag(Tok, diag::err_expected_catch));
1553 while (Tok.is(tok::kw_catch)) {
1554 OwningStmtResult Handler(ParseCXXCatchBlock());
1555 if (!Handler.isInvalid())
1556 Handlers.push_back(Handler.release());
1558 // Don't bother creating the full statement if we don't have any usable
1560 if (Handlers.empty())
1563 return Actions.ActOnCXXTryBlock(TryLoc, move(TryBlock), move_arg(Handlers));
1566 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1569 /// 'catch' '(' exception-declaration ')' compound-statement
1571 /// exception-declaration:
1572 /// type-specifier-seq declarator
1573 /// type-specifier-seq abstract-declarator
1574 /// type-specifier-seq
1577 Parser::OwningStmtResult Parser::ParseCXXCatchBlock() {
1578 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1580 SourceLocation CatchLoc = ConsumeToken();
1582 SourceLocation LParenLoc = Tok.getLocation();
1583 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1587 // The name in a catch exception-declaration is local to the handler and
1588 // shall not be redeclared in the outermost block of the handler.
1589 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1591 // exception-declaration is equivalent to '...' or a parameter-declaration
1592 // without default arguments.
1593 DeclPtrTy ExceptionDecl;
1594 if (Tok.isNot(tok::ellipsis)) {
1596 if (ParseCXXTypeSpecifierSeq(DS))
1598 Declarator ExDecl(DS, Declarator::CXXCatchContext);
1599 ParseDeclarator(ExDecl);
1600 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
1604 if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
1607 if (Tok.isNot(tok::l_brace))
1608 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1610 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1611 OwningStmtResult Block(ParseCompoundStatement(0));
1612 if (Block.isInvalid())
1615 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, move(Block));