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 CXX0XAttributeList Attr;
82 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
83 Attr = ParseCXX0XAttributes();
84 llvm::OwningPtr<AttributeList> AttrList(Attr.AttrList);
86 // Cases in this switch statement should fall through if the parser expects
87 // the token to end in a semicolon (in which case SemiError should be set),
88 // or they directly 'return;' if not.
89 tok::TokenKind Kind = Tok.getKind();
92 case tok::at: // May be a @try or @throw statement
94 AtLoc = ConsumeToken(); // consume @
95 return ParseObjCAtStatement(AtLoc);
98 case tok::code_completion:
99 Actions.CodeCompleteOrdinaryName(CurScope, Action::CCC_Statement);
101 return ParseStatementOrDeclaration(OnlyStatement);
103 case tok::identifier:
104 if (NextToken().is(tok::colon)) { // C99 6.8.1: labeled-statement
105 // identifier ':' statement
106 return ParseLabeledStatement(AttrList.take());
111 if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
112 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
113 AttrList.take(); //Passing 'Attr' to ParseDeclaration transfers ownership.
114 DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext, DeclEnd,
116 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
119 if (Tok.is(tok::r_brace)) {
120 Diag(Tok, diag::err_expected_statement);
124 // FIXME: Use the attributes
125 // expression[opt] ';'
126 OwningExprResult Expr(ParseExpression());
127 if (Expr.isInvalid()) {
128 // If the expression is invalid, skip ahead to the next semicolon or '}'.
129 // Not doing this opens us up to the possibility of infinite loops if
130 // ParseExpression does not consume any tokens.
131 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
132 if (Tok.is(tok::semi))
136 // Otherwise, eat the semicolon.
137 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
138 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr));
141 case tok::kw_case: // C99 6.8.1: labeled-statement
142 return ParseCaseStatement(AttrList.take());
143 case tok::kw_default: // C99 6.8.1: labeled-statement
144 return ParseDefaultStatement(AttrList.take());
146 case tok::l_brace: // C99 6.8.2: compound-statement
147 return ParseCompoundStatement(AttrList.take());
148 case tok::semi: // C99 6.8.3p3: expression[opt] ';'
149 return Actions.ActOnNullStmt(ConsumeToken());
151 case tok::kw_if: // C99 6.8.4.1: if-statement
152 return ParseIfStatement(AttrList.take());
153 case tok::kw_switch: // C99 6.8.4.2: switch-statement
154 return ParseSwitchStatement(AttrList.take());
156 case tok::kw_while: // C99 6.8.5.1: while-statement
157 return ParseWhileStatement(AttrList.take());
158 case tok::kw_do: // C99 6.8.5.2: do-statement
159 Res = ParseDoStatement(AttrList.take());
160 SemiError = "do/while";
162 case tok::kw_for: // C99 6.8.5.3: for-statement
163 return ParseForStatement(AttrList.take());
165 case tok::kw_goto: // C99 6.8.6.1: goto-statement
166 Res = ParseGotoStatement(AttrList.take());
169 case tok::kw_continue: // C99 6.8.6.2: continue-statement
170 Res = ParseContinueStatement(AttrList.take());
171 SemiError = "continue";
173 case tok::kw_break: // C99 6.8.6.3: break-statement
174 Res = ParseBreakStatement(AttrList.take());
177 case tok::kw_return: // C99 6.8.6.4: return-statement
178 Res = ParseReturnStatement(AttrList.take());
179 SemiError = "return";
184 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
187 Res = ParseAsmStatement(msAsm);
188 if (msAsm) return move(Res);
193 case tok::kw_try: // C++ 15: try-block
194 return ParseCXXTryBlock(AttrList.take());
197 // If we reached this code, the statement must end in a semicolon.
198 if (Tok.is(tok::semi)) {
200 } else if (!Res.isInvalid()) {
201 // If the result was valid, then we do want to diagnose this. Use
202 // ExpectAndConsume to emit the diagnostic, even though we know it won't
204 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
205 // Skip until we see a } or ;, but don't eat it.
206 SkipUntil(tok::r_brace, true, true);
212 /// ParseLabeledStatement - We have an identifier and a ':' after it.
214 /// labeled-statement:
215 /// identifier ':' statement
216 /// [GNU] identifier ':' attributes[opt] statement
218 Parser::OwningStmtResult Parser::ParseLabeledStatement(AttributeList *Attr) {
219 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
220 "Not an identifier!");
222 llvm::OwningPtr<AttributeList> AttrList(Attr);
223 Token IdentTok = Tok; // Save the whole token.
224 ConsumeToken(); // eat the identifier.
226 assert(Tok.is(tok::colon) && "Not a label!");
228 // identifier ':' statement
229 SourceLocation ColonLoc = ConsumeToken();
231 // Read label attributes, if present.
232 if (Tok.is(tok::kw___attribute))
233 AttrList.reset(addAttributeLists(AttrList.take(), ParseGNUAttributes()));
235 OwningStmtResult SubStmt(ParseStatement());
237 // Broken substmt shouldn't prevent the label from being added to the AST.
238 if (SubStmt.isInvalid())
239 SubStmt = Actions.ActOnNullStmt(ColonLoc);
241 // FIXME: use attributes?
242 return Actions.ActOnLabelStmt(IdentTok.getLocation(),
243 IdentTok.getIdentifierInfo(),
244 ColonLoc, move(SubStmt));
247 /// ParseCaseStatement
248 /// labeled-statement:
249 /// 'case' constant-expression ':' statement
250 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
252 Parser::OwningStmtResult Parser::ParseCaseStatement(AttributeList *Attr) {
253 assert(Tok.is(tok::kw_case) && "Not a case stmt!");
254 // FIXME: Use attributes?
257 // It is very very common for code to contain many case statements recursively
258 // nested, as in (but usually without indentation):
265 // Parsing this naively works, but is both inefficient and can cause us to run
266 // out of stack space in our recursive descent parser. As a special case,
267 // flatten this recursion into an iterative loop. This is complex and gross,
268 // but all the grossness is constrained to ParseCaseStatement (and some
269 // wierdness in the actions), so this is just local grossness :).
271 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
273 OwningStmtResult TopLevelCase(Actions, true);
275 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
276 // gets updated each time a new case is parsed, and whose body is unset so
277 // far. When parsing 'case 4', this is the 'case 3' node.
278 StmtTy *DeepestParsedCaseStmt = 0;
280 // While we have case statements, eat and stack them.
282 SourceLocation CaseLoc = ConsumeToken(); // eat the 'case'.
284 if (Tok.is(tok::code_completion)) {
285 Actions.CodeCompleteCase(CurScope);
286 ConsumeCodeCompletionToken();
289 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
290 /// Disable this form of error recovery while we're parsing the case
292 ColonProtectionRAIIObject ColonProtection(*this);
294 OwningExprResult LHS(ParseConstantExpression());
295 if (LHS.isInvalid()) {
296 SkipUntil(tok::colon);
300 // GNU case range extension.
301 SourceLocation DotDotDotLoc;
302 OwningExprResult RHS(Actions);
303 if (Tok.is(tok::ellipsis)) {
304 Diag(Tok, diag::ext_gnu_case_range);
305 DotDotDotLoc = ConsumeToken();
307 RHS = ParseConstantExpression();
308 if (RHS.isInvalid()) {
309 SkipUntil(tok::colon);
314 ColonProtection.restore();
316 if (Tok.isNot(tok::colon)) {
317 Diag(Tok, diag::err_expected_colon_after) << "'case'";
318 SkipUntil(tok::colon);
322 SourceLocation ColonLoc = ConsumeToken();
324 OwningStmtResult Case =
325 Actions.ActOnCaseStmt(CaseLoc, move(LHS), DotDotDotLoc,
326 move(RHS), ColonLoc);
328 // If we had a sema error parsing this case, then just ignore it and
329 // continue parsing the sub-stmt.
330 if (Case.isInvalid()) {
331 if (TopLevelCase.isInvalid()) // No parsed case stmts.
332 return ParseStatement();
333 // Otherwise, just don't add it as a nested case.
335 // If this is the first case statement we parsed, it becomes TopLevelCase.
336 // Otherwise we link it into the current chain.
337 StmtTy *NextDeepest = Case.get();
338 if (TopLevelCase.isInvalid())
339 TopLevelCase = move(Case);
341 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, move(Case));
342 DeepestParsedCaseStmt = NextDeepest;
345 // Handle all case statements.
346 } while (Tok.is(tok::kw_case));
348 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
350 // If we found a non-case statement, start by parsing it.
351 OwningStmtResult SubStmt(Actions);
353 if (Tok.isNot(tok::r_brace)) {
354 SubStmt = ParseStatement();
356 // Nicely diagnose the common error "switch (X) { case 4: }", which is
358 // FIXME: add insertion hint.
359 Diag(Tok, diag::err_label_end_of_compound_statement);
363 // Broken sub-stmt shouldn't prevent forming the case statement properly.
364 if (SubStmt.isInvalid())
365 SubStmt = Actions.ActOnNullStmt(SourceLocation());
367 // Install the body into the most deeply-nested case.
368 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, move(SubStmt));
370 // Return the top level parsed statement tree.
371 return move(TopLevelCase);
374 /// ParseDefaultStatement
375 /// labeled-statement:
376 /// 'default' ':' statement
377 /// Note that this does not parse the 'statement' at the end.
379 Parser::OwningStmtResult Parser::ParseDefaultStatement(AttributeList *Attr) {
380 //FIXME: Use attributes?
383 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
384 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
386 if (Tok.isNot(tok::colon)) {
387 Diag(Tok, diag::err_expected_colon_after) << "'default'";
388 SkipUntil(tok::colon);
392 SourceLocation ColonLoc = ConsumeToken();
394 // Diagnose the common error "switch (X) {... default: }", which is not valid.
395 if (Tok.is(tok::r_brace)) {
396 Diag(Tok, diag::err_label_end_of_compound_statement);
400 OwningStmtResult SubStmt(ParseStatement());
401 if (SubStmt.isInvalid())
404 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
405 move(SubStmt), CurScope);
409 /// ParseCompoundStatement - Parse a "{}" block.
411 /// compound-statement: [C99 6.8.2]
412 /// { block-item-list[opt] }
413 /// [GNU] { label-declarations block-item-list } [TODO]
417 /// block-item-list block-item
421 /// [GNU] '__extension__' declaration
423 /// [OMP] openmp-directive [TODO]
425 /// [GNU] label-declarations:
426 /// [GNU] label-declaration
427 /// [GNU] label-declarations label-declaration
429 /// [GNU] label-declaration:
430 /// [GNU] '__label__' identifier-list ';'
432 /// [OMP] openmp-directive: [TODO]
433 /// [OMP] barrier-directive
434 /// [OMP] flush-directive
436 Parser::OwningStmtResult Parser::ParseCompoundStatement(AttributeList *Attr,
438 //FIXME: Use attributes?
441 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
443 // Enter a scope to hold everything within the compound stmt. Compound
444 // statements can always hold declarations.
445 ParseScope CompoundScope(this, Scope::DeclScope);
447 // Parse the statements in the body.
448 return ParseCompoundStatementBody(isStmtExpr);
452 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
453 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
454 /// consume the '}' at the end of the block. It does not manipulate the scope
456 Parser::OwningStmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
457 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
459 "in compound statement ('{}')");
461 SourceLocation LBraceLoc = ConsumeBrace(); // eat the '{'.
463 // TODO: "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
464 // only allowed at the start of a compound stmt regardless of the language.
466 typedef StmtVector StmtsTy;
467 StmtsTy Stmts(Actions);
468 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
469 OwningStmtResult R(Actions);
470 if (Tok.isNot(tok::kw___extension__)) {
471 R = ParseStatementOrDeclaration(false);
473 // __extension__ can start declarations and it can also be a unary
474 // operator for expressions. Consume multiple __extension__ markers here
475 // until we can determine which is which.
476 // FIXME: This loses extension expressions in the AST!
477 SourceLocation ExtLoc = ConsumeToken();
478 while (Tok.is(tok::kw___extension__))
481 CXX0XAttributeList Attr;
482 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
483 Attr = ParseCXX0XAttributes();
485 // If this is the start of a declaration, parse it as such.
486 if (isDeclarationStatement()) {
487 // __extension__ silences extension warnings in the subdeclaration.
488 // FIXME: Save the __extension__ on the decl as a node somehow?
489 ExtensionRAIIObject O(Diags);
491 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
492 DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
494 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
496 // Otherwise this was a unary __extension__ marker.
497 OwningExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
499 if (Res.isInvalid()) {
500 SkipUntil(tok::semi);
504 // FIXME: Use attributes?
505 // Eat the semicolon at the end of stmt and convert the expr into a
507 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
508 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res));
513 Stmts.push_back(R.release());
516 // We broke out of the while loop because we found a '}' or EOF.
517 if (Tok.isNot(tok::r_brace)) {
518 Diag(Tok, diag::err_expected_rbrace);
522 SourceLocation RBraceLoc = ConsumeBrace();
523 return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
527 /// ParseParenExprOrCondition:
528 /// [C ] '(' expression ')'
529 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
531 /// This function parses and performs error recovery on the specified condition
532 /// or expression (depending on whether we're in C++ or C mode). This function
533 /// goes out of its way to recover well. It returns true if there was a parser
534 /// error (the right paren couldn't be found), which indicates that the caller
535 /// should try to recover harder. It returns false if the condition is
536 /// successfully parsed. Note that a successful parse can still have semantic
537 /// errors in the condition.
538 bool Parser::ParseParenExprOrCondition(OwningExprResult &ExprResult,
539 DeclPtrTy &DeclResult,
541 bool ConvertToBoolean) {
542 bool ParseError = false;
544 SourceLocation LParenLoc = ConsumeParen();
545 if (getLang().CPlusPlus)
546 ParseError = ParseCXXCondition(ExprResult, DeclResult, Loc,
549 ExprResult = ParseExpression();
550 DeclResult = DeclPtrTy();
552 // If required, convert to a boolean value.
553 if (!ExprResult.isInvalid() && ConvertToBoolean)
555 = Actions.ActOnBooleanCondition(CurScope, Loc, move(ExprResult));
558 // If the parser was confused by the condition and we don't have a ')', try to
559 // recover by skipping ahead to a semi and bailing out. If condexp is
560 // semantically invalid but we have well formed code, keep going.
561 if (ExprResult.isInvalid() && !DeclResult.get() && Tok.isNot(tok::r_paren)) {
562 SkipUntil(tok::semi);
563 // Skipping may have stopped if it found the containing ')'. If so, we can
564 // continue parsing the if statement.
565 if (Tok.isNot(tok::r_paren))
569 // Otherwise the condition is valid or the rparen is present.
570 MatchRHSPunctuation(tok::r_paren, LParenLoc);
576 /// if-statement: [C99 6.8.4.1]
577 /// 'if' '(' expression ')' statement
578 /// 'if' '(' expression ')' statement 'else' statement
579 /// [C++] 'if' '(' condition ')' statement
580 /// [C++] 'if' '(' condition ')' statement 'else' statement
582 Parser::OwningStmtResult Parser::ParseIfStatement(AttributeList *Attr) {
583 // FIXME: Use attributes?
586 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
587 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
589 if (Tok.isNot(tok::l_paren)) {
590 Diag(Tok, diag::err_expected_lparen_after) << "if";
591 SkipUntil(tok::semi);
595 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
597 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
601 // A name introduced by a declaration in a condition is in scope from its
602 // point of declaration until the end of the substatements controlled by the
605 // Names declared in the for-init-statement, and in the condition of if,
606 // while, for, and switch statements are local to the if, while, for, or
607 // switch statement (including the controlled statement).
609 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
611 // Parse the condition.
612 OwningExprResult CondExp(Actions);
614 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
617 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp));
619 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
620 // there is no compound stmt. C90 does not have this clause. We only do this
621 // if the body isn't a compound statement to avoid push/pop in common cases.
624 // The substatement in a selection-statement (each substatement, in the else
625 // form of the if statement) implicitly defines a local scope.
627 // For C++ we create a scope for the condition and a new scope for
628 // substatements because:
629 // -When the 'then' scope exits, we want the condition declaration to still be
630 // active for the 'else' scope too.
631 // -Sema will detect name clashes by considering declarations of a
632 // 'ControlScope' as part of its direct subscope.
633 // -If we wanted the condition and substatement to be in the same scope, we
634 // would have to notify ParseStatement not to create a new scope. It's
635 // simpler to let it create a new scope.
637 ParseScope InnerScope(this, Scope::DeclScope,
638 C99orCXX && Tok.isNot(tok::l_brace));
640 // Read the 'then' stmt.
641 SourceLocation ThenStmtLoc = Tok.getLocation();
642 OwningStmtResult ThenStmt(ParseStatement());
644 // Pop the 'if' scope if needed.
647 // If it has an else, parse it.
648 SourceLocation ElseLoc;
649 SourceLocation ElseStmtLoc;
650 OwningStmtResult ElseStmt(Actions);
652 if (Tok.is(tok::kw_else)) {
653 ElseLoc = ConsumeToken();
654 ElseStmtLoc = Tok.getLocation();
656 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
657 // there is no compound stmt. C90 does not have this clause. We only do
658 // this if the body isn't a compound statement to avoid push/pop in common
662 // The substatement in a selection-statement (each substatement, in the else
663 // form of the if statement) implicitly defines a local scope.
665 ParseScope InnerScope(this, Scope::DeclScope,
666 C99orCXX && Tok.isNot(tok::l_brace));
668 // Regardless of whether or not InnerScope actually pushed a scope, set the
669 // ElseScope flag for the innermost scope so we can diagnose use of the if
670 // condition variable in C++.
671 unsigned OldFlags = CurScope->getFlags();
672 CurScope->setFlags(OldFlags | Scope::ElseScope);
673 ElseStmt = ParseStatement();
674 CurScope->setFlags(OldFlags);
676 // Pop the 'else' scope if needed.
682 // If the condition was invalid, discard the if statement. We could recover
683 // better by replacing it with a valid expr, but don't do that yet.
684 if (CondExp.isInvalid() && !CondVar.get())
687 // If the then or else stmt is invalid and the other is valid (and present),
688 // make turn the invalid one into a null stmt to avoid dropping the other
689 // part. If both are invalid, return error.
690 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
691 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
692 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
693 // Both invalid, or one is invalid and other is non-present: return error.
697 // Now if either are invalid, replace with a ';'.
698 if (ThenStmt.isInvalid())
699 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
700 if (ElseStmt.isInvalid())
701 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
703 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, move(ThenStmt),
704 ElseLoc, move(ElseStmt));
707 /// ParseSwitchStatement
708 /// switch-statement:
709 /// 'switch' '(' expression ')' statement
710 /// [C++] 'switch' '(' condition ')' statement
711 Parser::OwningStmtResult Parser::ParseSwitchStatement(AttributeList *Attr) {
712 // FIXME: Use attributes?
715 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
716 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
718 if (Tok.isNot(tok::l_paren)) {
719 Diag(Tok, diag::err_expected_lparen_after) << "switch";
720 SkipUntil(tok::semi);
724 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
726 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
727 // not the case for C90. Start the switch scope.
730 // A name introduced by a declaration in a condition is in scope from its
731 // point of declaration until the end of the substatements controlled by the
734 // Names declared in the for-init-statement, and in the condition of if,
735 // while, for, and switch statements are local to the if, while, for, or
736 // switch statement (including the controlled statement).
738 unsigned ScopeFlags = Scope::BreakScope;
740 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
741 ParseScope SwitchScope(this, ScopeFlags);
743 // Parse the condition.
744 OwningExprResult Cond(Actions);
746 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
749 OwningStmtResult Switch
750 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, move(Cond), CondVar);
752 if (Switch.isInvalid()) {
753 // Skip the switch body.
754 // FIXME: This is not optimal recovery, but parsing the body is more
755 // dangerous due to the presence of case and default statements, which
756 // will have no place to connect back with the switch.
757 if (Tok.is(tok::l_brace)) {
759 SkipUntil(tok::r_brace, false, false);
761 SkipUntil(tok::semi);
765 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
766 // there is no compound stmt. C90 does not have this clause. We only do this
767 // if the body isn't a compound statement to avoid push/pop in common cases.
770 // The substatement in a selection-statement (each substatement, in the else
771 // form of the if statement) implicitly defines a local scope.
773 // See comments in ParseIfStatement for why we create a scope for the
774 // condition and a new scope for substatement in C++.
776 ParseScope InnerScope(this, Scope::DeclScope,
777 C99orCXX && Tok.isNot(tok::l_brace));
779 // Read the body statement.
780 OwningStmtResult Body(ParseStatement());
786 if (Body.isInvalid())
787 // FIXME: Remove the case statement list from the Switch statement.
788 Body = Actions.ActOnNullStmt(Tok.getLocation());
790 return Actions.ActOnFinishSwitchStmt(SwitchLoc, move(Switch), move(Body));
793 /// ParseWhileStatement
794 /// while-statement: [C99 6.8.5.1]
795 /// 'while' '(' expression ')' statement
796 /// [C++] 'while' '(' condition ')' statement
797 Parser::OwningStmtResult Parser::ParseWhileStatement(AttributeList *Attr) {
798 // FIXME: Use attributes?
801 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
802 SourceLocation WhileLoc = Tok.getLocation();
803 ConsumeToken(); // eat the 'while'.
805 if (Tok.isNot(tok::l_paren)) {
806 Diag(Tok, diag::err_expected_lparen_after) << "while";
807 SkipUntil(tok::semi);
811 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
813 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
814 // the case for C90. Start the loop scope.
817 // A name introduced by a declaration in a condition is in scope from its
818 // point of declaration until the end of the substatements controlled by the
821 // Names declared in the for-init-statement, and in the condition of if,
822 // while, for, and switch statements are local to the if, while, for, or
823 // switch statement (including the controlled statement).
827 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
828 Scope::DeclScope | Scope::ControlScope;
830 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
831 ParseScope WhileScope(this, ScopeFlags);
833 // Parse the condition.
834 OwningExprResult Cond(Actions);
836 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
839 FullExprArg FullCond(Actions.MakeFullExpr(Cond));
841 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
842 // there is no compound stmt. C90 does not have this clause. We only do this
843 // if the body isn't a compound statement to avoid push/pop in common cases.
846 // The substatement in an iteration-statement implicitly defines a local scope
847 // which is entered and exited each time through the loop.
849 // See comments in ParseIfStatement for why we create a scope for the
850 // condition and a new scope for substatement in C++.
852 ParseScope InnerScope(this, Scope::DeclScope,
853 C99orCXX && Tok.isNot(tok::l_brace));
855 // Read the body statement.
856 OwningStmtResult Body(ParseStatement());
858 // Pop the body scope if needed.
862 if ((Cond.isInvalid() && !CondVar.get()) || Body.isInvalid())
865 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, move(Body));
869 /// do-statement: [C99 6.8.5.2]
870 /// 'do' statement 'while' '(' expression ')' ';'
871 /// Note: this lets the caller parse the end ';'.
872 Parser::OwningStmtResult Parser::ParseDoStatement(AttributeList *Attr) {
873 // FIXME: Use attributes?
876 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
877 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
879 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
880 // the case for C90. Start the loop scope.
883 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
885 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
887 ParseScope DoScope(this, ScopeFlags);
889 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
890 // there is no compound stmt. C90 does not have this clause. We only do this
891 // if the body isn't a compound statement to avoid push/pop in common cases.
894 // The substatement in an iteration-statement implicitly defines a local scope
895 // which is entered and exited each time through the loop.
897 ParseScope InnerScope(this, Scope::DeclScope,
898 (getLang().C99 || getLang().CPlusPlus) &&
899 Tok.isNot(tok::l_brace));
901 // Read the body statement.
902 OwningStmtResult Body(ParseStatement());
904 // Pop the body scope if needed.
907 if (Tok.isNot(tok::kw_while)) {
908 if (!Body.isInvalid()) {
909 Diag(Tok, diag::err_expected_while);
910 Diag(DoLoc, diag::note_matching) << "do";
911 SkipUntil(tok::semi, false, true);
915 SourceLocation WhileLoc = ConsumeToken();
917 if (Tok.isNot(tok::l_paren)) {
918 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
919 SkipUntil(tok::semi, false, true);
923 // Parse the parenthesized condition.
924 SourceLocation LPLoc = ConsumeParen();
925 OwningExprResult Cond = ParseExpression();
926 SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
929 if (Cond.isInvalid() || Body.isInvalid())
932 return Actions.ActOnDoStmt(DoLoc, move(Body), WhileLoc, LPLoc,
936 /// ParseForStatement
937 /// for-statement: [C99 6.8.5.3]
938 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
939 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
940 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
942 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
943 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
945 /// [C++] for-init-statement:
946 /// [C++] expression-statement
947 /// [C++] simple-declaration
949 Parser::OwningStmtResult Parser::ParseForStatement(AttributeList *Attr) {
950 // FIXME: Use attributes?
953 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
954 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
956 if (Tok.isNot(tok::l_paren)) {
957 Diag(Tok, diag::err_expected_lparen_after) << "for";
958 SkipUntil(tok::semi);
962 bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
964 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
965 // the case for C90. Start the loop scope.
968 // A name introduced by a declaration in a condition is in scope from its
969 // point of declaration until the end of the substatements controlled by the
972 // Names declared in the for-init-statement, and in the condition of if,
973 // while, for, and switch statements are local to the if, while, for, or
974 // switch statement (including the controlled statement).
976 // Names declared in the for-init-statement are in the same declarative-region
977 // as those declared in the condition.
981 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
982 Scope::DeclScope | Scope::ControlScope;
984 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
986 ParseScope ForScope(this, ScopeFlags);
988 SourceLocation LParenLoc = ConsumeParen();
989 OwningExprResult Value(Actions);
991 bool ForEach = false;
992 OwningStmtResult FirstPart(Actions);
993 bool SecondPartIsInvalid = false;
994 FullExprArg SecondPart(Actions);
995 OwningExprResult Collection(Actions);
996 FullExprArg ThirdPart(Actions);
999 if (Tok.is(tok::code_completion)) {
1000 Actions.CodeCompleteOrdinaryName(CurScope,
1001 C99orCXXorObjC? Action::CCC_ForInit
1002 : Action::CCC_Expression);
1003 ConsumeCodeCompletionToken();
1006 // Parse the first part of the for specifier.
1007 if (Tok.is(tok::semi)) { // for (;
1008 // no first part, eat the ';'.
1010 } else if (isSimpleDeclaration()) { // for (int X = 4;
1011 // Parse declaration, which eats the ';'.
1012 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1013 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1015 AttributeList *AttrList = 0;
1016 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1017 AttrList = ParseCXX0XAttributes().AttrList;
1019 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1020 DeclGroupPtrTy DG = ParseSimpleDeclaration(Declarator::ForContext, DeclEnd,
1022 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1024 if (Tok.is(tok::semi)) { // for (int x = 4;
1026 } else if ((ForEach = isTokIdentifier_in())) {
1027 Actions.ActOnForEachDeclStmt(DG);
1028 // ObjC: for (id x in expr)
1029 ConsumeToken(); // consume 'in'
1030 Collection = ParseExpression();
1032 Diag(Tok, diag::err_expected_semi_for);
1033 SkipUntil(tok::semi);
1036 Value = ParseExpression();
1038 // Turn the expression into a stmt.
1039 if (!Value.isInvalid())
1040 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value));
1042 if (Tok.is(tok::semi)) {
1044 } else if ((ForEach = isTokIdentifier_in())) {
1045 ConsumeToken(); // consume 'in'
1046 Collection = ParseExpression();
1048 if (!Value.isInvalid()) Diag(Tok, diag::err_expected_semi_for);
1049 SkipUntil(tok::semi);
1053 assert(!SecondPart->get() && "Shouldn't have a second expression yet.");
1054 // Parse the second part of the for specifier.
1055 if (Tok.is(tok::semi)) { // for (...;;
1058 OwningExprResult Second(Actions);
1059 if (getLang().CPlusPlus)
1060 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1062 Second = ParseExpression();
1063 if (!Second.isInvalid())
1064 Second = Actions.ActOnBooleanCondition(CurScope, ForLoc,
1067 SecondPartIsInvalid = Second.isInvalid();
1068 SecondPart = Actions.MakeFullExpr(Second);
1071 if (Tok.is(tok::semi)) {
1074 if (!SecondPartIsInvalid || SecondVar.get())
1075 Diag(Tok, diag::err_expected_semi_for);
1076 SkipUntil(tok::semi);
1079 // Parse the third part of the for specifier.
1080 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1081 OwningExprResult Third = ParseExpression();
1082 ThirdPart = Actions.MakeFullExpr(Third);
1086 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1088 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1089 // there is no compound stmt. C90 does not have this clause. We only do this
1090 // if the body isn't a compound statement to avoid push/pop in common cases.
1093 // The substatement in an iteration-statement implicitly defines a local scope
1094 // which is entered and exited each time through the loop.
1096 // See comments in ParseIfStatement for why we create a scope for
1097 // for-init-statement/condition and a new scope for substatement in C++.
1099 ParseScope InnerScope(this, Scope::DeclScope,
1100 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1102 // Read the body statement.
1103 OwningStmtResult Body(ParseStatement());
1105 // Pop the body scope if needed.
1108 // Leave the for-scope.
1111 if (Body.isInvalid())
1115 return Actions.ActOnForStmt(ForLoc, LParenLoc, move(FirstPart), SecondPart,
1116 SecondVar, ThirdPart, RParenLoc, move(Body));
1118 // FIXME: It isn't clear how to communicate the late destruction of
1119 // C++ temporaries used to create the collection.
1120 return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc, move(FirstPart),
1121 move(Collection), RParenLoc,
1125 /// ParseGotoStatement
1127 /// 'goto' identifier ';'
1128 /// [GNU] 'goto' '*' expression ';'
1130 /// Note: this lets the caller parse the end ';'.
1132 Parser::OwningStmtResult Parser::ParseGotoStatement(AttributeList *Attr) {
1133 // FIXME: Use attributes?
1136 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1137 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1139 OwningStmtResult Res(Actions);
1140 if (Tok.is(tok::identifier)) {
1141 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(),
1142 Tok.getIdentifierInfo());
1144 } else if (Tok.is(tok::star)) {
1145 // GNU indirect goto extension.
1146 Diag(Tok, diag::ext_gnu_indirect_goto);
1147 SourceLocation StarLoc = ConsumeToken();
1148 OwningExprResult R(ParseExpression());
1149 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1150 SkipUntil(tok::semi, false, true);
1153 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, move(R));
1155 Diag(Tok, diag::err_expected_ident);
1162 /// ParseContinueStatement
1166 /// Note: this lets the caller parse the end ';'.
1168 Parser::OwningStmtResult Parser::ParseContinueStatement(AttributeList *Attr) {
1169 // FIXME: Use attributes?
1172 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1173 return Actions.ActOnContinueStmt(ContinueLoc, CurScope);
1176 /// ParseBreakStatement
1180 /// Note: this lets the caller parse the end ';'.
1182 Parser::OwningStmtResult Parser::ParseBreakStatement(AttributeList *Attr) {
1183 // FIXME: Use attributes?
1186 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1187 return Actions.ActOnBreakStmt(BreakLoc, CurScope);
1190 /// ParseReturnStatement
1192 /// 'return' expression[opt] ';'
1193 Parser::OwningStmtResult Parser::ParseReturnStatement(AttributeList *Attr) {
1194 // FIXME: Use attributes?
1197 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1198 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1200 OwningExprResult R(Actions);
1201 if (Tok.isNot(tok::semi)) {
1202 R = ParseExpression();
1203 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1204 SkipUntil(tok::semi, false, true);
1208 return Actions.ActOnReturnStmt(ReturnLoc, move(R));
1211 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1212 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1213 Parser::OwningStmtResult Parser::FuzzyParseMicrosoftAsmStatement() {
1214 if (Tok.is(tok::l_brace)) {
1215 unsigned short savedBraceCount = BraceCount;
1218 } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1220 // From the MS website: If used without braces, the __asm keyword means
1221 // that the rest of the line is an assembly-language statement.
1222 SourceManager &SrcMgr = PP.getSourceManager();
1223 SourceLocation TokLoc = Tok.getLocation();
1224 unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1227 TokLoc = Tok.getLocation();
1228 } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1229 Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1230 Tok.isNot(tok::eof));
1233 t.setKind(tok::string_literal);
1234 t.setLiteralData("\"FIXME: not done\"");
1235 t.clearFlag(Token::NeedsCleaning);
1237 OwningExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1238 ExprVector Constraints(Actions);
1239 ExprVector Exprs(Actions);
1240 ExprVector Clobbers(Actions);
1241 return Actions.ActOnAsmStmt(Tok.getLocation(), true, true, 0, 0, 0,
1242 move_arg(Constraints), move_arg(Exprs),
1243 move(AsmString), move_arg(Clobbers),
1244 Tok.getLocation(), true);
1247 /// ParseAsmStatement - Parse a GNU extended asm statement.
1249 /// gnu-asm-statement
1250 /// ms-asm-statement
1252 /// [GNU] gnu-asm-statement:
1253 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1255 /// [GNU] asm-argument:
1256 /// asm-string-literal
1257 /// asm-string-literal ':' asm-operands[opt]
1258 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1259 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1260 /// ':' asm-clobbers
1262 /// [GNU] asm-clobbers:
1263 /// asm-string-literal
1264 /// asm-clobbers ',' asm-string-literal
1266 /// [MS] ms-asm-statement:
1267 /// '__asm' assembly-instruction ';'[opt]
1268 /// '__asm' '{' assembly-instruction-list '}' ';'[opt]
1270 /// [MS] assembly-instruction-list:
1271 /// assembly-instruction ';'[opt]
1272 /// assembly-instruction-list ';' assembly-instruction ';'[opt]
1274 Parser::OwningStmtResult Parser::ParseAsmStatement(bool &msAsm) {
1275 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1276 SourceLocation AsmLoc = ConsumeToken();
1278 if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1280 return FuzzyParseMicrosoftAsmStatement();
1283 SourceLocation Loc = Tok.getLocation();
1284 ParseTypeQualifierListOpt(DS, true, false);
1286 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1287 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1288 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1289 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1290 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1292 // Remember if this was a volatile asm.
1293 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1294 if (Tok.isNot(tok::l_paren)) {
1295 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1296 SkipUntil(tok::r_paren);
1299 Loc = ConsumeParen();
1301 OwningExprResult AsmString(ParseAsmStringLiteral());
1302 if (AsmString.isInvalid())
1305 llvm::SmallVector<IdentifierInfo *, 4> Names;
1306 ExprVector Constraints(Actions);
1307 ExprVector Exprs(Actions);
1308 ExprVector Clobbers(Actions);
1310 if (Tok.is(tok::r_paren)) {
1311 // We have a simple asm expression like 'asm("foo")'.
1312 SourceLocation RParenLoc = ConsumeParen();
1313 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1314 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1315 move_arg(Constraints), move_arg(Exprs),
1316 move(AsmString), move_arg(Clobbers),
1320 // Parse Outputs, if present.
1321 bool AteExtraColon = false;
1322 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1323 // In C++ mode, parse "::" like ": :".
1324 AteExtraColon = Tok.is(tok::coloncolon);
1327 if (!AteExtraColon &&
1328 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1332 unsigned NumOutputs = Names.size();
1334 // Parse Inputs, if present.
1335 if (AteExtraColon ||
1336 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1337 // In C++ mode, parse "::" like ": :".
1339 AteExtraColon = false;
1341 AteExtraColon = Tok.is(tok::coloncolon);
1345 if (!AteExtraColon &&
1346 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1350 assert(Names.size() == Constraints.size() &&
1351 Constraints.size() == Exprs.size() &&
1352 "Input operand size mismatch!");
1354 unsigned NumInputs = Names.size() - NumOutputs;
1356 // Parse the clobbers, if present.
1357 if (AteExtraColon || Tok.is(tok::colon)) {
1361 // Parse the asm-string list for clobbers.
1363 OwningExprResult Clobber(ParseAsmStringLiteral());
1365 if (Clobber.isInvalid())
1368 Clobbers.push_back(Clobber.release());
1370 if (Tok.isNot(tok::comma)) break;
1375 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1376 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1377 NumOutputs, NumInputs, Names.data(),
1378 move_arg(Constraints), move_arg(Exprs),
1379 move(AsmString), move_arg(Clobbers),
1383 /// ParseAsmOperands - Parse the asm-operands production as used by
1384 /// asm-statement, assuming the leading ':' token was eaten.
1386 /// [GNU] asm-operands:
1388 /// asm-operands ',' asm-operand
1390 /// [GNU] asm-operand:
1391 /// asm-string-literal '(' expression ')'
1392 /// '[' identifier ']' asm-string-literal '(' expression ')'
1395 // FIXME: Avoid unnecessary std::string trashing.
1396 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1397 llvm::SmallVectorImpl<ExprTy *> &Constraints,
1398 llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1399 // 'asm-operands' isn't present?
1400 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1404 // Read the [id] if present.
1405 if (Tok.is(tok::l_square)) {
1406 SourceLocation Loc = ConsumeBracket();
1408 if (Tok.isNot(tok::identifier)) {
1409 Diag(Tok, diag::err_expected_ident);
1410 SkipUntil(tok::r_paren);
1414 IdentifierInfo *II = Tok.getIdentifierInfo();
1417 Names.push_back(II);
1418 MatchRHSPunctuation(tok::r_square, Loc);
1422 OwningExprResult Constraint(ParseAsmStringLiteral());
1423 if (Constraint.isInvalid()) {
1424 SkipUntil(tok::r_paren);
1427 Constraints.push_back(Constraint.release());
1429 if (Tok.isNot(tok::l_paren)) {
1430 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1431 SkipUntil(tok::r_paren);
1435 // Read the parenthesized expression.
1436 SourceLocation OpenLoc = ConsumeParen();
1437 OwningExprResult Res(ParseExpression());
1438 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1439 if (Res.isInvalid()) {
1440 SkipUntil(tok::r_paren);
1443 Exprs.push_back(Res.release());
1444 // Eat the comma and continue parsing if it exists.
1445 if (Tok.isNot(tok::comma)) return false;
1452 Parser::DeclPtrTy Parser::ParseFunctionStatementBody(DeclPtrTy Decl) {
1453 assert(Tok.is(tok::l_brace));
1454 SourceLocation LBraceLoc = Tok.getLocation();
1456 PrettyStackTraceActionsDecl CrashInfo(Decl, LBraceLoc, Actions,
1457 PP.getSourceManager(),
1458 "parsing function body");
1460 // Do not enter a scope for the brace, as the arguments are in the same scope
1461 // (the function body) as the body itself. Instead, just read the statement
1462 // list and put it into a CompoundStmt for safe keeping.
1463 OwningStmtResult FnBody(ParseCompoundStatementBody());
1465 // If the function body could not be parsed, make a bogus compoundstmt.
1466 if (FnBody.isInvalid())
1467 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1468 MultiStmtArg(Actions), false);
1470 return Actions.ActOnFinishFunctionBody(Decl, move(FnBody));
1473 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1475 /// function-try-block:
1476 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1478 Parser::DeclPtrTy Parser::ParseFunctionTryBlock(DeclPtrTy Decl) {
1479 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1480 SourceLocation TryLoc = ConsumeToken();
1482 PrettyStackTraceActionsDecl CrashInfo(Decl, TryLoc, Actions,
1483 PP.getSourceManager(),
1484 "parsing function try block");
1486 // Constructor initializer list?
1487 if (Tok.is(tok::colon))
1488 ParseConstructorInitializer(Decl);
1490 SourceLocation LBraceLoc = Tok.getLocation();
1491 OwningStmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1492 // If we failed to parse the try-catch, we just give the function an empty
1493 // compound statement as the body.
1494 if (FnBody.isInvalid())
1495 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1496 MultiStmtArg(Actions), false);
1498 return Actions.ActOnFinishFunctionBody(Decl, move(FnBody));
1501 /// ParseCXXTryBlock - Parse a C++ try-block.
1504 /// 'try' compound-statement handler-seq
1506 Parser::OwningStmtResult Parser::ParseCXXTryBlock(AttributeList* Attr) {
1507 // FIXME: Add attributes?
1510 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1512 SourceLocation TryLoc = ConsumeToken();
1513 return ParseCXXTryBlockCommon(TryLoc);
1516 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1517 /// function-try-block.
1520 /// 'try' compound-statement handler-seq
1522 /// function-try-block:
1523 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1526 /// handler handler-seq[opt]
1528 Parser::OwningStmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1529 if (Tok.isNot(tok::l_brace))
1530 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1531 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1532 OwningStmtResult TryBlock(ParseCompoundStatement(0));
1533 if (TryBlock.isInvalid())
1534 return move(TryBlock);
1536 StmtVector Handlers(Actions);
1537 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1538 CXX0XAttributeList Attr = ParseCXX0XAttributes();
1539 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
1542 if (Tok.isNot(tok::kw_catch))
1543 return StmtError(Diag(Tok, diag::err_expected_catch));
1544 while (Tok.is(tok::kw_catch)) {
1545 OwningStmtResult Handler(ParseCXXCatchBlock());
1546 if (!Handler.isInvalid())
1547 Handlers.push_back(Handler.release());
1549 // Don't bother creating the full statement if we don't have any usable
1551 if (Handlers.empty())
1554 return Actions.ActOnCXXTryBlock(TryLoc, move(TryBlock), move_arg(Handlers));
1557 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1560 /// 'catch' '(' exception-declaration ')' compound-statement
1562 /// exception-declaration:
1563 /// type-specifier-seq declarator
1564 /// type-specifier-seq abstract-declarator
1565 /// type-specifier-seq
1568 Parser::OwningStmtResult Parser::ParseCXXCatchBlock() {
1569 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1571 SourceLocation CatchLoc = ConsumeToken();
1573 SourceLocation LParenLoc = Tok.getLocation();
1574 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1578 // The name in a catch exception-declaration is local to the handler and
1579 // shall not be redeclared in the outermost block of the handler.
1580 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1582 // exception-declaration is equivalent to '...' or a parameter-declaration
1583 // without default arguments.
1584 DeclPtrTy ExceptionDecl;
1585 if (Tok.isNot(tok::ellipsis)) {
1587 if (ParseCXXTypeSpecifierSeq(DS))
1589 Declarator ExDecl(DS, Declarator::CXXCatchContext);
1590 ParseDeclarator(ExDecl);
1591 ExceptionDecl = Actions.ActOnExceptionDeclarator(CurScope, ExDecl);
1595 if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
1598 if (Tok.isNot(tok::l_brace))
1599 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1601 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1602 OwningStmtResult Block(ParseCompoundStatement(0));
1603 if (Block.isInvalid())
1606 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, move(Block));