Don't skip past the '}' if an expression has error and is not followed by ';'.
[clang.git] / lib / Parse / ParseStmt.cpp
blobb752b48cfd49fc0a410d6fb433db5aaa64114a5e
1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Statement and Block portions of the Parser
11 // interface.
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:
30 /// statement
31 /// declaration
32 ///
33 /// statement:
34 /// labeled-statement
35 /// compound-statement
36 /// expression-statement
37 /// selection-statement
38 /// iteration-statement
39 /// jump-statement
40 /// [C++] declaration-statement
41 /// [C++] try-block
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]
47 ///
48 /// labeled-statement:
49 /// identifier ':' statement
50 /// 'case' constant-expression ':' statement
51 /// 'default' ':' statement
52 ///
53 /// selection-statement:
54 /// if-statement
55 /// switch-statement
56 ///
57 /// iteration-statement:
58 /// while-statement
59 /// do-statement
60 /// for-statement
61 ///
62 /// expression-statement:
63 /// expression[opt] ';'
64 ///
65 /// jump-statement:
66 /// 'goto' identifier ';'
67 /// 'continue' ';'
68 /// 'break' ';'
69 /// 'return' expression[opt] ';'
70 /// [GNU] 'goto' '*' expression ';'
71 ///
72 /// [OBC] objc-throw-statement:
73 /// [OBC] '@' 'throw' expression ';'
74 /// [OBC] '@' 'throw' ';'
75 ///
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();
90 SourceLocation AtLoc;
91 switch (Kind) {
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);
100 ConsumeToken();
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());
108 // PASS THROUGH.
110 default: {
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,
115 Attr);
116 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
119 if (Tok.is(tok::r_brace)) {
120 Diag(Tok, diag::err_expected_statement);
121 return StmtError();
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))
133 ConsumeToken();
134 return StmtError();
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";
161 break;
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());
167 SemiError = "goto";
168 break;
169 case tok::kw_continue: // C99 6.8.6.2: continue-statement
170 Res = ParseContinueStatement(AttrList.take());
171 SemiError = "continue";
172 break;
173 case tok::kw_break: // C99 6.8.6.3: break-statement
174 Res = ParseBreakStatement(AttrList.take());
175 SemiError = "break";
176 break;
177 case tok::kw_return: // C99 6.8.6.4: return-statement
178 Res = ParseReturnStatement(AttrList.take());
179 SemiError = "return";
180 break;
182 case tok::kw_asm: {
183 if (Attr.HasAttr)
184 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
185 << Attr.Range;
186 bool msAsm = false;
187 Res = ParseAsmStatement(msAsm);
188 if (msAsm) return move(Res);
189 SemiError = "asm";
190 break;
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)) {
199 ConsumeToken();
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
203 // succeed.
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);
209 return move(Res);
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?
255 delete Attr;
257 // It is very very common for code to contain many case statements recursively
258 // nested, as in (but usually without indentation):
259 // case 1:
260 // case 2:
261 // case 3:
262 // case 4:
263 // case 5: etc.
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
272 // example above.
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.
281 do {
282 SourceLocation CaseLoc = ConsumeToken(); // eat the 'case'.
284 if (Tok.is(tok::code_completion)) {
285 Actions.CodeCompleteCase(CurScope);
286 ConsumeToken();
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
291 /// expression.
292 ColonProtectionRAIIObject ColonProtection(*this);
294 OwningExprResult LHS(ParseConstantExpression());
295 if (LHS.isInvalid()) {
296 SkipUntil(tok::colon);
297 return StmtError();
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);
310 return StmtError();
314 ColonProtection.restore();
316 if (Tok.isNot(tok::colon)) {
317 Diag(Tok, diag::err_expected_colon_after) << "'case'";
318 SkipUntil(tok::colon);
319 return StmtError();
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.
334 } else {
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);
340 else
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();
355 } else {
356 // Nicely diagnose the common error "switch (X) { case 4: }", which is
357 // not valid.
358 // FIXME: add insertion hint.
359 Diag(Tok, diag::err_label_end_of_compound_statement);
360 SubStmt = true;
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?
381 delete Attr;
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);
389 return StmtError();
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);
397 return StmtError();
400 OwningStmtResult SubStmt(ParseStatement());
401 if (SubStmt.isInvalid())
402 return StmtError();
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]
415 /// block-item-list:
416 /// block-item
417 /// block-item-list block-item
419 /// block-item:
420 /// declaration
421 /// [GNU] '__extension__' declaration
422 /// statement
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,
437 bool isStmtExpr) {
438 //FIXME: Use attributes?
439 delete Attr;
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
455 /// stack.
456 Parser::OwningStmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
457 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
458 Tok.getLocation(),
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);
472 } else {
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__))
479 ConsumeToken();
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,
493 Attr);
494 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
495 } else {
496 // Otherwise this was a unary __extension__ marker.
497 OwningExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
499 if (Res.isInvalid()) {
500 SkipUntil(tok::semi);
501 continue;
504 // FIXME: Use attributes?
505 // Eat the semicolon at the end of stmt and convert the expr into a
506 // statement.
507 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
508 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res));
512 if (R.isUsable())
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);
519 return StmtError();
522 SourceLocation RBraceLoc = ConsumeBrace();
523 return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
524 isStmtExpr);
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) {
540 bool ParseError = false;
542 SourceLocation LParenLoc = ConsumeParen();
543 if (getLang().CPlusPlus)
544 ParseError = ParseCXXCondition(ExprResult, DeclResult);
545 else {
546 ExprResult = ParseExpression();
547 DeclResult = DeclPtrTy();
550 // If the parser was confused by the condition and we don't have a ')', try to
551 // recover by skipping ahead to a semi and bailing out. If condexp is
552 // semantically invalid but we have well formed code, keep going.
553 if (ExprResult.isInvalid() && !DeclResult.get() && Tok.isNot(tok::r_paren)) {
554 SkipUntil(tok::semi);
555 // Skipping may have stopped if it found the containing ')'. If so, we can
556 // continue parsing the if statement.
557 if (Tok.isNot(tok::r_paren))
558 return true;
561 // Otherwise the condition is valid or the rparen is present.
562 MatchRHSPunctuation(tok::r_paren, LParenLoc);
563 return false;
567 /// ParseIfStatement
568 /// if-statement: [C99 6.8.4.1]
569 /// 'if' '(' expression ')' statement
570 /// 'if' '(' expression ')' statement 'else' statement
571 /// [C++] 'if' '(' condition ')' statement
572 /// [C++] 'if' '(' condition ')' statement 'else' statement
574 Parser::OwningStmtResult Parser::ParseIfStatement(AttributeList *Attr) {
575 // FIXME: Use attributes?
576 delete Attr;
578 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
579 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
581 if (Tok.isNot(tok::l_paren)) {
582 Diag(Tok, diag::err_expected_lparen_after) << "if";
583 SkipUntil(tok::semi);
584 return StmtError();
587 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
589 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
590 // the case for C90.
592 // C++ 6.4p3:
593 // A name introduced by a declaration in a condition is in scope from its
594 // point of declaration until the end of the substatements controlled by the
595 // condition.
596 // C++ 3.3.2p4:
597 // Names declared in the for-init-statement, and in the condition of if,
598 // while, for, and switch statements are local to the if, while, for, or
599 // switch statement (including the controlled statement).
601 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
603 // Parse the condition.
604 OwningExprResult CondExp(Actions);
605 DeclPtrTy CondVar;
606 if (ParseParenExprOrCondition(CondExp, CondVar))
607 return StmtError();
609 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp));
611 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
612 // there is no compound stmt. C90 does not have this clause. We only do this
613 // if the body isn't a compound statement to avoid push/pop in common cases.
615 // C++ 6.4p1:
616 // The substatement in a selection-statement (each substatement, in the else
617 // form of the if statement) implicitly defines a local scope.
619 // For C++ we create a scope for the condition and a new scope for
620 // substatements because:
621 // -When the 'then' scope exits, we want the condition declaration to still be
622 // active for the 'else' scope too.
623 // -Sema will detect name clashes by considering declarations of a
624 // 'ControlScope' as part of its direct subscope.
625 // -If we wanted the condition and substatement to be in the same scope, we
626 // would have to notify ParseStatement not to create a new scope. It's
627 // simpler to let it create a new scope.
629 ParseScope InnerScope(this, Scope::DeclScope,
630 C99orCXX && Tok.isNot(tok::l_brace));
632 // Read the 'then' stmt.
633 SourceLocation ThenStmtLoc = Tok.getLocation();
634 OwningStmtResult ThenStmt(ParseStatement());
636 // Pop the 'if' scope if needed.
637 InnerScope.Exit();
639 // If it has an else, parse it.
640 SourceLocation ElseLoc;
641 SourceLocation ElseStmtLoc;
642 OwningStmtResult ElseStmt(Actions);
644 if (Tok.is(tok::kw_else)) {
645 ElseLoc = ConsumeToken();
647 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
648 // there is no compound stmt. C90 does not have this clause. We only do
649 // this if the body isn't a compound statement to avoid push/pop in common
650 // cases.
652 // C++ 6.4p1:
653 // The substatement in a selection-statement (each substatement, in the else
654 // form of the if statement) implicitly defines a local scope.
656 ParseScope InnerScope(this, Scope::DeclScope,
657 C99orCXX && Tok.isNot(tok::l_brace));
659 bool WithinElse = CurScope->isWithinElse();
660 CurScope->setWithinElse(true);
661 ElseStmtLoc = Tok.getLocation();
662 ElseStmt = ParseStatement();
663 CurScope->setWithinElse(WithinElse);
665 // Pop the 'else' scope if needed.
666 InnerScope.Exit();
669 IfScope.Exit();
671 // If the condition was invalid, discard the if statement. We could recover
672 // better by replacing it with a valid expr, but don't do that yet.
673 if (CondExp.isInvalid() && !CondVar.get())
674 return StmtError();
676 // If the then or else stmt is invalid and the other is valid (and present),
677 // make turn the invalid one into a null stmt to avoid dropping the other
678 // part. If both are invalid, return error.
679 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
680 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
681 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
682 // Both invalid, or one is invalid and other is non-present: return error.
683 return StmtError();
686 // Now if either are invalid, replace with a ';'.
687 if (ThenStmt.isInvalid())
688 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
689 if (ElseStmt.isInvalid())
690 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
692 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, move(ThenStmt),
693 ElseLoc, move(ElseStmt));
696 /// ParseSwitchStatement
697 /// switch-statement:
698 /// 'switch' '(' expression ')' statement
699 /// [C++] 'switch' '(' condition ')' statement
700 Parser::OwningStmtResult Parser::ParseSwitchStatement(AttributeList *Attr) {
701 // FIXME: Use attributes?
702 delete Attr;
704 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
705 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
707 if (Tok.isNot(tok::l_paren)) {
708 Diag(Tok, diag::err_expected_lparen_after) << "switch";
709 SkipUntil(tok::semi);
710 return StmtError();
713 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
715 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
716 // not the case for C90. Start the switch scope.
718 // C++ 6.4p3:
719 // A name introduced by a declaration in a condition is in scope from its
720 // point of declaration until the end of the substatements controlled by the
721 // condition.
722 // C++ 3.3.2p4:
723 // Names declared in the for-init-statement, and in the condition of if,
724 // while, for, and switch statements are local to the if, while, for, or
725 // switch statement (including the controlled statement).
727 unsigned ScopeFlags = Scope::BreakScope;
728 if (C99orCXX)
729 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
730 ParseScope SwitchScope(this, ScopeFlags);
732 // Parse the condition.
733 OwningExprResult Cond(Actions);
734 DeclPtrTy CondVar;
735 if (ParseParenExprOrCondition(Cond, CondVar))
736 return StmtError();
738 FullExprArg FullCond(Actions.MakeFullExpr(Cond));
740 OwningStmtResult Switch = Actions.ActOnStartOfSwitchStmt(FullCond, CondVar);
742 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
743 // there is no compound stmt. C90 does not have this clause. We only do this
744 // if the body isn't a compound statement to avoid push/pop in common cases.
746 // C++ 6.4p1:
747 // The substatement in a selection-statement (each substatement, in the else
748 // form of the if statement) implicitly defines a local scope.
750 // See comments in ParseIfStatement for why we create a scope for the
751 // condition and a new scope for substatement in C++.
753 ParseScope InnerScope(this, Scope::DeclScope,
754 C99orCXX && Tok.isNot(tok::l_brace));
756 // Read the body statement.
757 OwningStmtResult Body(ParseStatement());
759 // Pop the scopes.
760 InnerScope.Exit();
761 SwitchScope.Exit();
763 if (Cond.isInvalid() && !CondVar.get()) {
764 Actions.ActOnSwitchBodyError(SwitchLoc, move(Switch), move(Body));
765 return StmtError();
768 if (Body.isInvalid())
769 // FIXME: Remove the case statement list from the Switch statement.
770 Body = Actions.ActOnNullStmt(Tok.getLocation());
772 return Actions.ActOnFinishSwitchStmt(SwitchLoc, move(Switch), move(Body));
775 /// ParseWhileStatement
776 /// while-statement: [C99 6.8.5.1]
777 /// 'while' '(' expression ')' statement
778 /// [C++] 'while' '(' condition ')' statement
779 Parser::OwningStmtResult Parser::ParseWhileStatement(AttributeList *Attr) {
780 // FIXME: Use attributes?
781 delete Attr;
783 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
784 SourceLocation WhileLoc = Tok.getLocation();
785 ConsumeToken(); // eat the 'while'.
787 if (Tok.isNot(tok::l_paren)) {
788 Diag(Tok, diag::err_expected_lparen_after) << "while";
789 SkipUntil(tok::semi);
790 return StmtError();
793 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
795 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
796 // the case for C90. Start the loop scope.
798 // C++ 6.4p3:
799 // A name introduced by a declaration in a condition is in scope from its
800 // point of declaration until the end of the substatements controlled by the
801 // condition.
802 // C++ 3.3.2p4:
803 // Names declared in the for-init-statement, and in the condition of if,
804 // while, for, and switch statements are local to the if, while, for, or
805 // switch statement (including the controlled statement).
807 unsigned ScopeFlags;
808 if (C99orCXX)
809 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
810 Scope::DeclScope | Scope::ControlScope;
811 else
812 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
813 ParseScope WhileScope(this, ScopeFlags);
815 // Parse the condition.
816 OwningExprResult Cond(Actions);
817 DeclPtrTy CondVar;
818 if (ParseParenExprOrCondition(Cond, CondVar))
819 return StmtError();
821 FullExprArg FullCond(Actions.MakeFullExpr(Cond));
823 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
824 // there is no compound stmt. C90 does not have this clause. We only do this
825 // if the body isn't a compound statement to avoid push/pop in common cases.
827 // C++ 6.5p2:
828 // The substatement in an iteration-statement implicitly defines a local scope
829 // which is entered and exited each time through the loop.
831 // See comments in ParseIfStatement for why we create a scope for the
832 // condition and a new scope for substatement in C++.
834 ParseScope InnerScope(this, Scope::DeclScope,
835 C99orCXX && Tok.isNot(tok::l_brace));
837 // Read the body statement.
838 OwningStmtResult Body(ParseStatement());
840 // Pop the body scope if needed.
841 InnerScope.Exit();
842 WhileScope.Exit();
844 if ((Cond.isInvalid() && !CondVar.get()) || Body.isInvalid())
845 return StmtError();
847 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, move(Body));
850 /// ParseDoStatement
851 /// do-statement: [C99 6.8.5.2]
852 /// 'do' statement 'while' '(' expression ')' ';'
853 /// Note: this lets the caller parse the end ';'.
854 Parser::OwningStmtResult Parser::ParseDoStatement(AttributeList *Attr) {
855 // FIXME: Use attributes?
856 delete Attr;
858 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
859 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
861 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
862 // the case for C90. Start the loop scope.
863 unsigned ScopeFlags;
864 if (getLang().C99)
865 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
866 else
867 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
869 ParseScope DoScope(this, ScopeFlags);
871 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
872 // there is no compound stmt. C90 does not have this clause. We only do this
873 // if the body isn't a compound statement to avoid push/pop in common cases.
875 // C++ 6.5p2:
876 // The substatement in an iteration-statement implicitly defines a local scope
877 // which is entered and exited each time through the loop.
879 ParseScope InnerScope(this, Scope::DeclScope,
880 (getLang().C99 || getLang().CPlusPlus) &&
881 Tok.isNot(tok::l_brace));
883 // Read the body statement.
884 OwningStmtResult Body(ParseStatement());
886 // Pop the body scope if needed.
887 InnerScope.Exit();
889 if (Tok.isNot(tok::kw_while)) {
890 if (!Body.isInvalid()) {
891 Diag(Tok, diag::err_expected_while);
892 Diag(DoLoc, diag::note_matching) << "do";
893 SkipUntil(tok::semi, false, true);
895 return StmtError();
897 SourceLocation WhileLoc = ConsumeToken();
899 if (Tok.isNot(tok::l_paren)) {
900 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
901 SkipUntil(tok::semi, false, true);
902 return StmtError();
905 // Parse the parenthesized condition.
906 SourceLocation LPLoc = ConsumeParen();
907 OwningExprResult Cond = ParseExpression();
908 SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
909 DoScope.Exit();
911 if (Cond.isInvalid() || Body.isInvalid())
912 return StmtError();
914 return Actions.ActOnDoStmt(DoLoc, move(Body), WhileLoc, LPLoc,
915 move(Cond), RPLoc);
918 /// ParseForStatement
919 /// for-statement: [C99 6.8.5.3]
920 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
921 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
922 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
923 /// [C++] statement
924 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
925 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
927 /// [C++] for-init-statement:
928 /// [C++] expression-statement
929 /// [C++] simple-declaration
931 Parser::OwningStmtResult Parser::ParseForStatement(AttributeList *Attr) {
932 // FIXME: Use attributes?
933 delete Attr;
935 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
936 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
938 if (Tok.isNot(tok::l_paren)) {
939 Diag(Tok, diag::err_expected_lparen_after) << "for";
940 SkipUntil(tok::semi);
941 return StmtError();
944 bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
946 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
947 // the case for C90. Start the loop scope.
949 // C++ 6.4p3:
950 // A name introduced by a declaration in a condition is in scope from its
951 // point of declaration until the end of the substatements controlled by the
952 // condition.
953 // C++ 3.3.2p4:
954 // Names declared in the for-init-statement, and in the condition of if,
955 // while, for, and switch statements are local to the if, while, for, or
956 // switch statement (including the controlled statement).
957 // C++ 6.5.3p1:
958 // Names declared in the for-init-statement are in the same declarative-region
959 // as those declared in the condition.
961 unsigned ScopeFlags;
962 if (C99orCXXorObjC)
963 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
964 Scope::DeclScope | Scope::ControlScope;
965 else
966 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
968 ParseScope ForScope(this, ScopeFlags);
970 SourceLocation LParenLoc = ConsumeParen();
971 OwningExprResult Value(Actions);
973 bool ForEach = false;
974 OwningStmtResult FirstPart(Actions);
975 OwningExprResult SecondPart(Actions), ThirdPart(Actions);
976 DeclPtrTy SecondVar;
978 if (Tok.is(tok::code_completion)) {
979 Actions.CodeCompleteOrdinaryName(CurScope,
980 C99orCXXorObjC? Action::CCC_ForInit
981 : Action::CCC_Expression);
982 ConsumeToken();
985 // Parse the first part of the for specifier.
986 if (Tok.is(tok::semi)) { // for (;
987 // no first part, eat the ';'.
988 ConsumeToken();
989 } else if (isSimpleDeclaration()) { // for (int X = 4;
990 // Parse declaration, which eats the ';'.
991 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
992 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
994 AttributeList *AttrList = 0;
995 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
996 AttrList = ParseCXX0XAttributes().AttrList;
998 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
999 DeclGroupPtrTy DG = ParseSimpleDeclaration(Declarator::ForContext, DeclEnd,
1000 AttrList);
1001 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1003 if (Tok.is(tok::semi)) { // for (int x = 4;
1004 ConsumeToken();
1005 } else if ((ForEach = isTokIdentifier_in())) {
1006 Actions.ActOnForEachDeclStmt(DG);
1007 // ObjC: for (id x in expr)
1008 ConsumeToken(); // consume 'in'
1009 SecondPart = ParseExpression();
1010 } else {
1011 Diag(Tok, diag::err_expected_semi_for);
1012 SkipUntil(tok::semi);
1014 } else {
1015 Value = ParseExpression();
1017 // Turn the expression into a stmt.
1018 if (!Value.isInvalid())
1019 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value));
1021 if (Tok.is(tok::semi)) {
1022 ConsumeToken();
1023 } else if ((ForEach = isTokIdentifier_in())) {
1024 ConsumeToken(); // consume 'in'
1025 SecondPart = ParseExpression();
1026 } else {
1027 if (!Value.isInvalid()) Diag(Tok, diag::err_expected_semi_for);
1028 SkipUntil(tok::semi);
1031 if (!ForEach) {
1032 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1033 // Parse the second part of the for specifier.
1034 if (Tok.is(tok::semi)) { // for (...;;
1035 // no second part.
1036 } else {
1037 if (getLang().CPlusPlus)
1038 ParseCXXCondition(SecondPart, SecondVar);
1039 else
1040 SecondPart = ParseExpression();
1043 if (Tok.is(tok::semi)) {
1044 ConsumeToken();
1045 } else {
1046 if (!SecondPart.isInvalid() || SecondVar.get())
1047 Diag(Tok, diag::err_expected_semi_for);
1048 SkipUntil(tok::semi);
1051 // Parse the third part of the for specifier.
1052 if (Tok.isNot(tok::r_paren)) // for (...;...;)
1053 ThirdPart = ParseExpression();
1055 // Match the ')'.
1056 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1058 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1059 // there is no compound stmt. C90 does not have this clause. We only do this
1060 // if the body isn't a compound statement to avoid push/pop in common cases.
1062 // C++ 6.5p2:
1063 // The substatement in an iteration-statement implicitly defines a local scope
1064 // which is entered and exited each time through the loop.
1066 // See comments in ParseIfStatement for why we create a scope for
1067 // for-init-statement/condition and a new scope for substatement in C++.
1069 ParseScope InnerScope(this, Scope::DeclScope,
1070 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1072 // Read the body statement.
1073 OwningStmtResult Body(ParseStatement());
1075 // Pop the body scope if needed.
1076 InnerScope.Exit();
1078 // Leave the for-scope.
1079 ForScope.Exit();
1081 if (Body.isInvalid())
1082 return StmtError();
1084 if (!ForEach)
1085 return Actions.ActOnForStmt(ForLoc, LParenLoc, move(FirstPart),
1086 Actions.MakeFullExpr(SecondPart), SecondVar,
1087 Actions.MakeFullExpr(ThirdPart), RParenLoc,
1088 move(Body));
1090 return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc,
1091 move(FirstPart),
1092 move(SecondPart),
1093 RParenLoc, move(Body));
1096 /// ParseGotoStatement
1097 /// jump-statement:
1098 /// 'goto' identifier ';'
1099 /// [GNU] 'goto' '*' expression ';'
1101 /// Note: this lets the caller parse the end ';'.
1103 Parser::OwningStmtResult Parser::ParseGotoStatement(AttributeList *Attr) {
1104 // FIXME: Use attributes?
1105 delete Attr;
1107 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1108 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1110 OwningStmtResult Res(Actions);
1111 if (Tok.is(tok::identifier)) {
1112 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(),
1113 Tok.getIdentifierInfo());
1114 ConsumeToken();
1115 } else if (Tok.is(tok::star)) {
1116 // GNU indirect goto extension.
1117 Diag(Tok, diag::ext_gnu_indirect_goto);
1118 SourceLocation StarLoc = ConsumeToken();
1119 OwningExprResult R(ParseExpression());
1120 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1121 SkipUntil(tok::semi, false, true);
1122 return StmtError();
1124 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, move(R));
1125 } else {
1126 Diag(Tok, diag::err_expected_ident);
1127 return StmtError();
1130 return move(Res);
1133 /// ParseContinueStatement
1134 /// jump-statement:
1135 /// 'continue' ';'
1137 /// Note: this lets the caller parse the end ';'.
1139 Parser::OwningStmtResult Parser::ParseContinueStatement(AttributeList *Attr) {
1140 // FIXME: Use attributes?
1141 delete Attr;
1143 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1144 return Actions.ActOnContinueStmt(ContinueLoc, CurScope);
1147 /// ParseBreakStatement
1148 /// jump-statement:
1149 /// 'break' ';'
1151 /// Note: this lets the caller parse the end ';'.
1153 Parser::OwningStmtResult Parser::ParseBreakStatement(AttributeList *Attr) {
1154 // FIXME: Use attributes?
1155 delete Attr;
1157 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1158 return Actions.ActOnBreakStmt(BreakLoc, CurScope);
1161 /// ParseReturnStatement
1162 /// jump-statement:
1163 /// 'return' expression[opt] ';'
1164 Parser::OwningStmtResult Parser::ParseReturnStatement(AttributeList *Attr) {
1165 // FIXME: Use attributes?
1166 delete Attr;
1168 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1169 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1171 OwningExprResult R(Actions);
1172 if (Tok.isNot(tok::semi)) {
1173 R = ParseExpression();
1174 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1175 SkipUntil(tok::semi, false, true);
1176 return StmtError();
1179 return Actions.ActOnReturnStmt(ReturnLoc, move(R));
1182 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1183 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1184 Parser::OwningStmtResult Parser::FuzzyParseMicrosoftAsmStatement() {
1185 if (Tok.is(tok::l_brace)) {
1186 unsigned short savedBraceCount = BraceCount;
1187 do {
1188 ConsumeAnyToken();
1189 } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1190 } else {
1191 // From the MS website: If used without braces, the __asm keyword means
1192 // that the rest of the line is an assembly-language statement.
1193 SourceManager &SrcMgr = PP.getSourceManager();
1194 SourceLocation TokLoc = Tok.getLocation();
1195 unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1196 do {
1197 ConsumeAnyToken();
1198 TokLoc = Tok.getLocation();
1199 } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1200 Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1201 Tok.isNot(tok::eof));
1203 Token t;
1204 t.setKind(tok::string_literal);
1205 t.setLiteralData("\"FIXME: not done\"");
1206 t.clearFlag(Token::NeedsCleaning);
1207 t.setLength(17);
1208 OwningExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1209 ExprVector Constraints(Actions);
1210 ExprVector Exprs(Actions);
1211 ExprVector Clobbers(Actions);
1212 return Actions.ActOnAsmStmt(Tok.getLocation(), true, true, 0, 0, 0,
1213 move_arg(Constraints), move_arg(Exprs),
1214 move(AsmString), move_arg(Clobbers),
1215 Tok.getLocation(), true);
1218 /// ParseAsmStatement - Parse a GNU extended asm statement.
1219 /// asm-statement:
1220 /// gnu-asm-statement
1221 /// ms-asm-statement
1223 /// [GNU] gnu-asm-statement:
1224 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1226 /// [GNU] asm-argument:
1227 /// asm-string-literal
1228 /// asm-string-literal ':' asm-operands[opt]
1229 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1230 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1231 /// ':' asm-clobbers
1233 /// [GNU] asm-clobbers:
1234 /// asm-string-literal
1235 /// asm-clobbers ',' asm-string-literal
1237 /// [MS] ms-asm-statement:
1238 /// '__asm' assembly-instruction ';'[opt]
1239 /// '__asm' '{' assembly-instruction-list '}' ';'[opt]
1241 /// [MS] assembly-instruction-list:
1242 /// assembly-instruction ';'[opt]
1243 /// assembly-instruction-list ';' assembly-instruction ';'[opt]
1245 Parser::OwningStmtResult Parser::ParseAsmStatement(bool &msAsm) {
1246 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1247 SourceLocation AsmLoc = ConsumeToken();
1249 if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1250 msAsm = true;
1251 return FuzzyParseMicrosoftAsmStatement();
1253 DeclSpec DS;
1254 SourceLocation Loc = Tok.getLocation();
1255 ParseTypeQualifierListOpt(DS, true, false);
1257 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1258 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1259 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1260 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1261 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1263 // Remember if this was a volatile asm.
1264 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1265 if (Tok.isNot(tok::l_paren)) {
1266 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1267 SkipUntil(tok::r_paren);
1268 return StmtError();
1270 Loc = ConsumeParen();
1272 OwningExprResult AsmString(ParseAsmStringLiteral());
1273 if (AsmString.isInvalid())
1274 return StmtError();
1276 llvm::SmallVector<IdentifierInfo *, 4> Names;
1277 ExprVector Constraints(Actions);
1278 ExprVector Exprs(Actions);
1279 ExprVector Clobbers(Actions);
1281 if (Tok.is(tok::r_paren)) {
1282 // We have a simple asm expression like 'asm("foo")'.
1283 SourceLocation RParenLoc = ConsumeParen();
1284 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1285 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1286 move_arg(Constraints), move_arg(Exprs),
1287 move(AsmString), move_arg(Clobbers),
1288 RParenLoc);
1291 // Parse Outputs, if present.
1292 bool AteExtraColon = false;
1293 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1294 // In C++ mode, parse "::" like ": :".
1295 AteExtraColon = Tok.is(tok::coloncolon);
1296 ConsumeToken();
1298 if (!AteExtraColon &&
1299 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1300 return StmtError();
1303 unsigned NumOutputs = Names.size();
1305 // Parse Inputs, if present.
1306 if (AteExtraColon ||
1307 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1308 // In C++ mode, parse "::" like ": :".
1309 if (AteExtraColon)
1310 AteExtraColon = false;
1311 else {
1312 AteExtraColon = Tok.is(tok::coloncolon);
1313 ConsumeToken();
1316 if (!AteExtraColon &&
1317 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1318 return StmtError();
1321 assert(Names.size() == Constraints.size() &&
1322 Constraints.size() == Exprs.size() &&
1323 "Input operand size mismatch!");
1325 unsigned NumInputs = Names.size() - NumOutputs;
1327 // Parse the clobbers, if present.
1328 if (AteExtraColon || Tok.is(tok::colon)) {
1329 if (!AteExtraColon)
1330 ConsumeToken();
1332 // Parse the asm-string list for clobbers.
1333 while (1) {
1334 OwningExprResult Clobber(ParseAsmStringLiteral());
1336 if (Clobber.isInvalid())
1337 break;
1339 Clobbers.push_back(Clobber.release());
1341 if (Tok.isNot(tok::comma)) break;
1342 ConsumeToken();
1346 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1347 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1348 NumOutputs, NumInputs, Names.data(),
1349 move_arg(Constraints), move_arg(Exprs),
1350 move(AsmString), move_arg(Clobbers),
1351 RParenLoc);
1354 /// ParseAsmOperands - Parse the asm-operands production as used by
1355 /// asm-statement, assuming the leading ':' token was eaten.
1357 /// [GNU] asm-operands:
1358 /// asm-operand
1359 /// asm-operands ',' asm-operand
1361 /// [GNU] asm-operand:
1362 /// asm-string-literal '(' expression ')'
1363 /// '[' identifier ']' asm-string-literal '(' expression ')'
1366 // FIXME: Avoid unnecessary std::string trashing.
1367 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1368 llvm::SmallVectorImpl<ExprTy *> &Constraints,
1369 llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1370 // 'asm-operands' isn't present?
1371 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1372 return false;
1374 while (1) {
1375 // Read the [id] if present.
1376 if (Tok.is(tok::l_square)) {
1377 SourceLocation Loc = ConsumeBracket();
1379 if (Tok.isNot(tok::identifier)) {
1380 Diag(Tok, diag::err_expected_ident);
1381 SkipUntil(tok::r_paren);
1382 return true;
1385 IdentifierInfo *II = Tok.getIdentifierInfo();
1386 ConsumeToken();
1388 Names.push_back(II);
1389 MatchRHSPunctuation(tok::r_square, Loc);
1390 } else
1391 Names.push_back(0);
1393 OwningExprResult Constraint(ParseAsmStringLiteral());
1394 if (Constraint.isInvalid()) {
1395 SkipUntil(tok::r_paren);
1396 return true;
1398 Constraints.push_back(Constraint.release());
1400 if (Tok.isNot(tok::l_paren)) {
1401 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1402 SkipUntil(tok::r_paren);
1403 return true;
1406 // Read the parenthesized expression.
1407 SourceLocation OpenLoc = ConsumeParen();
1408 OwningExprResult Res(ParseExpression());
1409 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1410 if (Res.isInvalid()) {
1411 SkipUntil(tok::r_paren);
1412 return true;
1414 Exprs.push_back(Res.release());
1415 // Eat the comma and continue parsing if it exists.
1416 if (Tok.isNot(tok::comma)) return false;
1417 ConsumeToken();
1420 return true;
1423 Parser::DeclPtrTy Parser::ParseFunctionStatementBody(DeclPtrTy Decl) {
1424 assert(Tok.is(tok::l_brace));
1425 SourceLocation LBraceLoc = Tok.getLocation();
1427 PrettyStackTraceActionsDecl CrashInfo(Decl, LBraceLoc, Actions,
1428 PP.getSourceManager(),
1429 "parsing function body");
1431 // Do not enter a scope for the brace, as the arguments are in the same scope
1432 // (the function body) as the body itself. Instead, just read the statement
1433 // list and put it into a CompoundStmt for safe keeping.
1434 OwningStmtResult FnBody(ParseCompoundStatementBody());
1436 // If the function body could not be parsed, make a bogus compoundstmt.
1437 if (FnBody.isInvalid())
1438 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1439 MultiStmtArg(Actions), false);
1441 return Actions.ActOnFinishFunctionBody(Decl, move(FnBody));
1444 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1446 /// function-try-block:
1447 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1449 Parser::DeclPtrTy Parser::ParseFunctionTryBlock(DeclPtrTy Decl) {
1450 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1451 SourceLocation TryLoc = ConsumeToken();
1453 PrettyStackTraceActionsDecl CrashInfo(Decl, TryLoc, Actions,
1454 PP.getSourceManager(),
1455 "parsing function try block");
1457 // Constructor initializer list?
1458 if (Tok.is(tok::colon))
1459 ParseConstructorInitializer(Decl);
1461 SourceLocation LBraceLoc = Tok.getLocation();
1462 OwningStmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1463 // If we failed to parse the try-catch, we just give the function an empty
1464 // compound statement as the body.
1465 if (FnBody.isInvalid())
1466 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1467 MultiStmtArg(Actions), false);
1469 return Actions.ActOnFinishFunctionBody(Decl, move(FnBody));
1472 /// ParseCXXTryBlock - Parse a C++ try-block.
1474 /// try-block:
1475 /// 'try' compound-statement handler-seq
1477 Parser::OwningStmtResult Parser::ParseCXXTryBlock(AttributeList* Attr) {
1478 // FIXME: Add attributes?
1479 delete Attr;
1481 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1483 SourceLocation TryLoc = ConsumeToken();
1484 return ParseCXXTryBlockCommon(TryLoc);
1487 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1488 /// function-try-block.
1490 /// try-block:
1491 /// 'try' compound-statement handler-seq
1493 /// function-try-block:
1494 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1496 /// handler-seq:
1497 /// handler handler-seq[opt]
1499 Parser::OwningStmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1500 if (Tok.isNot(tok::l_brace))
1501 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1502 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1503 OwningStmtResult TryBlock(ParseCompoundStatement(0));
1504 if (TryBlock.isInvalid())
1505 return move(TryBlock);
1507 StmtVector Handlers(Actions);
1508 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1509 CXX0XAttributeList Attr = ParseCXX0XAttributes();
1510 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
1511 << Attr.Range;
1513 if (Tok.isNot(tok::kw_catch))
1514 return StmtError(Diag(Tok, diag::err_expected_catch));
1515 while (Tok.is(tok::kw_catch)) {
1516 OwningStmtResult Handler(ParseCXXCatchBlock());
1517 if (!Handler.isInvalid())
1518 Handlers.push_back(Handler.release());
1520 // Don't bother creating the full statement if we don't have any usable
1521 // handlers.
1522 if (Handlers.empty())
1523 return StmtError();
1525 return Actions.ActOnCXXTryBlock(TryLoc, move(TryBlock), move_arg(Handlers));
1528 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1530 /// handler:
1531 /// 'catch' '(' exception-declaration ')' compound-statement
1533 /// exception-declaration:
1534 /// type-specifier-seq declarator
1535 /// type-specifier-seq abstract-declarator
1536 /// type-specifier-seq
1537 /// '...'
1539 Parser::OwningStmtResult Parser::ParseCXXCatchBlock() {
1540 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1542 SourceLocation CatchLoc = ConsumeToken();
1544 SourceLocation LParenLoc = Tok.getLocation();
1545 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1546 return StmtError();
1548 // C++ 3.3.2p3:
1549 // The name in a catch exception-declaration is local to the handler and
1550 // shall not be redeclared in the outermost block of the handler.
1551 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1553 // exception-declaration is equivalent to '...' or a parameter-declaration
1554 // without default arguments.
1555 DeclPtrTy ExceptionDecl;
1556 if (Tok.isNot(tok::ellipsis)) {
1557 DeclSpec DS;
1558 if (ParseCXXTypeSpecifierSeq(DS))
1559 return StmtError();
1560 Declarator ExDecl(DS, Declarator::CXXCatchContext);
1561 ParseDeclarator(ExDecl);
1562 ExceptionDecl = Actions.ActOnExceptionDeclarator(CurScope, ExDecl);
1563 } else
1564 ConsumeToken();
1566 if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
1567 return StmtError();
1569 if (Tok.isNot(tok::l_brace))
1570 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1572 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1573 OwningStmtResult Block(ParseCompoundStatement(0));
1574 if (Block.isInvalid())
1575 return move(Block);
1577 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, move(Block));