]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseStmt.cpp
Merge OpenSSL 0.9.8q into head.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Parse / ParseStmt.cpp
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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/Sema/DeclSpec.h"
18 #include "clang/Sema/PrettyDeclStackTrace.h"
19 #include "clang/Sema/Scope.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/PrettyStackTrace.h"
22 #include "clang/Basic/SourceManager.h"
23 using namespace clang;
24
25 //===----------------------------------------------------------------------===//
26 // C99 6.8: Statements and Blocks.
27 //===----------------------------------------------------------------------===//
28
29 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
30 ///       StatementOrDeclaration:
31 ///         statement
32 ///         declaration
33 ///
34 ///       statement:
35 ///         labeled-statement
36 ///         compound-statement
37 ///         expression-statement
38 ///         selection-statement
39 ///         iteration-statement
40 ///         jump-statement
41 /// [C++]   declaration-statement
42 /// [C++]   try-block
43 /// [OBC]   objc-throw-statement
44 /// [OBC]   objc-try-catch-statement
45 /// [OBC]   objc-synchronized-statement
46 /// [GNU]   asm-statement
47 /// [OMP]   openmp-construct             [TODO]
48 ///
49 ///       labeled-statement:
50 ///         identifier ':' statement
51 ///         'case' constant-expression ':' statement
52 ///         'default' ':' statement
53 ///
54 ///       selection-statement:
55 ///         if-statement
56 ///         switch-statement
57 ///
58 ///       iteration-statement:
59 ///         while-statement
60 ///         do-statement
61 ///         for-statement
62 ///
63 ///       expression-statement:
64 ///         expression[opt] ';'
65 ///
66 ///       jump-statement:
67 ///         'goto' identifier ';'
68 ///         'continue' ';'
69 ///         'break' ';'
70 ///         'return' expression[opt] ';'
71 /// [GNU]   'goto' '*' expression ';'
72 ///
73 /// [OBC] objc-throw-statement:
74 /// [OBC]   '@' 'throw' expression ';'
75 /// [OBC]   '@' 'throw' ';'
76 ///
77 StmtResult
78 Parser::ParseStatementOrDeclaration(bool OnlyStatement) {
79   const char *SemiError = 0;
80   StmtResult Res;
81   
82   ParenBraceBracketBalancer BalancerRAIIObj(*this);
83
84   CXX0XAttributeList Attr;
85   if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
86     Attr = ParseCXX0XAttributes();
87   llvm::OwningPtr<AttributeList> AttrList(Attr.AttrList);
88
89   // Cases in this switch statement should fall through if the parser expects
90   // the token to end in a semicolon (in which case SemiError should be set),
91   // or they directly 'return;' if not.
92   tok::TokenKind Kind  = Tok.getKind();
93   SourceLocation AtLoc;
94   switch (Kind) {
95   case tok::at: // May be a @try or @throw statement
96     {
97       AtLoc = ConsumeToken();  // consume @
98       return ParseObjCAtStatement(AtLoc);
99     }
100
101   case tok::code_completion:
102     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
103     ConsumeCodeCompletionToken();
104     return ParseStatementOrDeclaration(OnlyStatement);
105       
106   case tok::identifier:
107     if (NextToken().is(tok::colon)) { // C99 6.8.1: labeled-statement
108       // identifier ':' statement
109       return ParseLabeledStatement(AttrList.take());
110     }
111     // PASS THROUGH.
112
113   default: {
114     if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
115       SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
116       AttrList.take(); //Passing 'Attr' to ParseDeclaration transfers ownership.
117       DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext, DeclEnd,
118                                              Attr);
119       return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
120     }
121
122     if (Tok.is(tok::r_brace)) {
123       Diag(Tok, diag::err_expected_statement);
124       return StmtError();
125     }
126
127     // FIXME: Use the attributes
128     // expression[opt] ';'
129     ExprResult Expr(ParseExpression());
130     if (Expr.isInvalid()) {
131       // If the expression is invalid, skip ahead to the next semicolon or '}'.
132       // Not doing this opens us up to the possibility of infinite loops if
133       // ParseExpression does not consume any tokens.
134       SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
135       if (Tok.is(tok::semi))
136         ConsumeToken();
137       return StmtError();
138     }
139     // Otherwise, eat the semicolon.
140     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
141     return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
142   }
143
144   case tok::kw_case:                // C99 6.8.1: labeled-statement
145     return ParseCaseStatement(AttrList.take());
146   case tok::kw_default:             // C99 6.8.1: labeled-statement
147     return ParseDefaultStatement(AttrList.take());
148
149   case tok::l_brace:                // C99 6.8.2: compound-statement
150     return ParseCompoundStatement(AttrList.take());
151   case tok::semi:                   // C99 6.8.3p3: expression[opt] ';'
152     return Actions.ActOnNullStmt(ConsumeToken());
153
154   case tok::kw_if:                  // C99 6.8.4.1: if-statement
155     return ParseIfStatement(AttrList.take());
156   case tok::kw_switch:              // C99 6.8.4.2: switch-statement
157     return ParseSwitchStatement(AttrList.take());
158
159   case tok::kw_while:               // C99 6.8.5.1: while-statement
160     return ParseWhileStatement(AttrList.take());
161   case tok::kw_do:                  // C99 6.8.5.2: do-statement
162     Res = ParseDoStatement(AttrList.take());
163     SemiError = "do/while";
164     break;
165   case tok::kw_for:                 // C99 6.8.5.3: for-statement
166     return ParseForStatement(AttrList.take());
167
168   case tok::kw_goto:                // C99 6.8.6.1: goto-statement
169     Res = ParseGotoStatement(AttrList.take());
170     SemiError = "goto";
171     break;
172   case tok::kw_continue:            // C99 6.8.6.2: continue-statement
173     Res = ParseContinueStatement(AttrList.take());
174     SemiError = "continue";
175     break;
176   case tok::kw_break:               // C99 6.8.6.3: break-statement
177     Res = ParseBreakStatement(AttrList.take());
178     SemiError = "break";
179     break;
180   case tok::kw_return:              // C99 6.8.6.4: return-statement
181     Res = ParseReturnStatement(AttrList.take());
182     SemiError = "return";
183     break;
184
185   case tok::kw_asm: {
186     if (Attr.HasAttr)
187       Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
188         << Attr.Range;
189     bool msAsm = false;
190     Res = ParseAsmStatement(msAsm);
191     if (msAsm) return move(Res);
192     SemiError = "asm";
193     break;
194   }
195
196   case tok::kw_try:                 // C++ 15: try-block
197     return ParseCXXTryBlock(AttrList.take());
198   }
199
200   // If we reached this code, the statement must end in a semicolon.
201   if (Tok.is(tok::semi)) {
202     ConsumeToken();
203   } else if (!Res.isInvalid()) {
204     // If the result was valid, then we do want to diagnose this.  Use
205     // ExpectAndConsume to emit the diagnostic, even though we know it won't
206     // succeed.
207     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
208     // Skip until we see a } or ;, but don't eat it.
209     SkipUntil(tok::r_brace, true, true);
210   }
211
212   return move(Res);
213 }
214
215 /// ParseLabeledStatement - We have an identifier and a ':' after it.
216 ///
217 ///       labeled-statement:
218 ///         identifier ':' statement
219 /// [GNU]   identifier ':' attributes[opt] statement
220 ///
221 StmtResult Parser::ParseLabeledStatement(AttributeList *Attr) {
222   assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
223          "Not an identifier!");
224
225   llvm::OwningPtr<AttributeList> AttrList(Attr);
226   Token IdentTok = Tok;  // Save the whole token.
227   ConsumeToken();  // eat the identifier.
228
229   assert(Tok.is(tok::colon) && "Not a label!");
230
231   // identifier ':' statement
232   SourceLocation ColonLoc = ConsumeToken();
233
234   // Read label attributes, if present.
235   if (Tok.is(tok::kw___attribute))
236     AttrList.reset(addAttributeLists(AttrList.take(), ParseGNUAttributes()));
237
238   StmtResult SubStmt(ParseStatement());
239
240   // Broken substmt shouldn't prevent the label from being added to the AST.
241   if (SubStmt.isInvalid())
242     SubStmt = Actions.ActOnNullStmt(ColonLoc);
243
244   // FIXME: use attributes?
245   return Actions.ActOnLabelStmt(IdentTok.getLocation(),
246                                 IdentTok.getIdentifierInfo(),
247                                 ColonLoc, SubStmt.get());
248 }
249
250 /// ParseCaseStatement
251 ///       labeled-statement:
252 ///         'case' constant-expression ':' statement
253 /// [GNU]   'case' constant-expression '...' constant-expression ':' statement
254 ///
255 StmtResult Parser::ParseCaseStatement(AttributeList *Attr) {
256   assert(Tok.is(tok::kw_case) && "Not a case stmt!");
257   // FIXME: Use attributes?
258   delete Attr;
259
260   // It is very very common for code to contain many case statements recursively
261   // nested, as in (but usually without indentation):
262   //  case 1:
263   //    case 2:
264   //      case 3:
265   //         case 4:
266   //           case 5: etc.
267   //
268   // Parsing this naively works, but is both inefficient and can cause us to run
269   // out of stack space in our recursive descent parser.  As a special case,
270   // flatten this recursion into an iterative loop.  This is complex and gross,
271   // but all the grossness is constrained to ParseCaseStatement (and some
272   // wierdness in the actions), so this is just local grossness :).
273
274   // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
275   // example above.
276   StmtResult TopLevelCase(true);
277
278   // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
279   // gets updated each time a new case is parsed, and whose body is unset so
280   // far.  When parsing 'case 4', this is the 'case 3' node.
281   StmtTy *DeepestParsedCaseStmt = 0;
282
283   // While we have case statements, eat and stack them.
284   do {
285     SourceLocation CaseLoc = ConsumeToken();  // eat the 'case'.
286
287     if (Tok.is(tok::code_completion)) {
288       Actions.CodeCompleteCase(getCurScope());
289       ConsumeCodeCompletionToken();
290     }
291     
292     /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
293     /// Disable this form of error recovery while we're parsing the case
294     /// expression.
295     ColonProtectionRAIIObject ColonProtection(*this);
296     
297     ExprResult LHS(ParseConstantExpression());
298     if (LHS.isInvalid()) {
299       SkipUntil(tok::colon);
300       return StmtError();
301     }
302
303     // GNU case range extension.
304     SourceLocation DotDotDotLoc;
305     ExprResult RHS;
306     if (Tok.is(tok::ellipsis)) {
307       Diag(Tok, diag::ext_gnu_case_range);
308       DotDotDotLoc = ConsumeToken();
309
310       RHS = ParseConstantExpression();
311       if (RHS.isInvalid()) {
312         SkipUntil(tok::colon);
313         return StmtError();
314       }
315     }
316     
317     ColonProtection.restore();
318
319     if (Tok.isNot(tok::colon)) {
320       Diag(Tok, diag::err_expected_colon_after) << "'case'";
321       SkipUntil(tok::colon);
322       return StmtError();
323     }
324
325     SourceLocation ColonLoc = ConsumeToken();
326
327     StmtResult Case =
328       Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
329                             RHS.get(), ColonLoc);
330
331     // If we had a sema error parsing this case, then just ignore it and
332     // continue parsing the sub-stmt.
333     if (Case.isInvalid()) {
334       if (TopLevelCase.isInvalid())  // No parsed case stmts.
335         return ParseStatement();
336       // Otherwise, just don't add it as a nested case.
337     } else {
338       // If this is the first case statement we parsed, it becomes TopLevelCase.
339       // Otherwise we link it into the current chain.
340       Stmt *NextDeepest = Case.get();
341       if (TopLevelCase.isInvalid())
342         TopLevelCase = move(Case);
343       else
344         Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
345       DeepestParsedCaseStmt = NextDeepest;
346     }
347
348     // Handle all case statements.
349   } while (Tok.is(tok::kw_case));
350
351   assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
352
353   // If we found a non-case statement, start by parsing it.
354   StmtResult SubStmt;
355
356   if (Tok.isNot(tok::r_brace)) {
357     SubStmt = ParseStatement();
358   } else {
359     // Nicely diagnose the common error "switch (X) { case 4: }", which is
360     // not valid.
361     // FIXME: add insertion hint.
362     Diag(Tok, diag::err_label_end_of_compound_statement);
363     SubStmt = true;
364   }
365
366   // Broken sub-stmt shouldn't prevent forming the case statement properly.
367   if (SubStmt.isInvalid())
368     SubStmt = Actions.ActOnNullStmt(SourceLocation());
369
370   // Install the body into the most deeply-nested case.
371   Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
372
373   // Return the top level parsed statement tree.
374   return move(TopLevelCase);
375 }
376
377 /// ParseDefaultStatement
378 ///       labeled-statement:
379 ///         'default' ':' statement
380 /// Note that this does not parse the 'statement' at the end.
381 ///
382 StmtResult Parser::ParseDefaultStatement(AttributeList *Attr) {
383   //FIXME: Use attributes?
384   delete Attr;
385
386   assert(Tok.is(tok::kw_default) && "Not a default stmt!");
387   SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
388
389   if (Tok.isNot(tok::colon)) {
390     Diag(Tok, diag::err_expected_colon_after) << "'default'";
391     SkipUntil(tok::colon);
392     return StmtError();
393   }
394
395   SourceLocation ColonLoc = ConsumeToken();
396
397   // Diagnose the common error "switch (X) {... default: }", which is not valid.
398   if (Tok.is(tok::r_brace)) {
399     Diag(Tok, diag::err_label_end_of_compound_statement);
400     return StmtError();
401   }
402
403   StmtResult SubStmt(ParseStatement());
404   if (SubStmt.isInvalid())
405     return StmtError();
406
407   return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
408                                   SubStmt.get(), getCurScope());
409 }
410
411
412 /// ParseCompoundStatement - Parse a "{}" block.
413 ///
414 ///       compound-statement: [C99 6.8.2]
415 ///         { block-item-list[opt] }
416 /// [GNU]   { label-declarations block-item-list } [TODO]
417 ///
418 ///       block-item-list:
419 ///         block-item
420 ///         block-item-list block-item
421 ///
422 ///       block-item:
423 ///         declaration
424 /// [GNU]   '__extension__' declaration
425 ///         statement
426 /// [OMP]   openmp-directive            [TODO]
427 ///
428 /// [GNU] label-declarations:
429 /// [GNU]   label-declaration
430 /// [GNU]   label-declarations label-declaration
431 ///
432 /// [GNU] label-declaration:
433 /// [GNU]   '__label__' identifier-list ';'
434 ///
435 /// [OMP] openmp-directive:             [TODO]
436 /// [OMP]   barrier-directive
437 /// [OMP]   flush-directive
438 ///
439 StmtResult Parser::ParseCompoundStatement(AttributeList *Attr,
440                                                         bool isStmtExpr) {
441   //FIXME: Use attributes?
442   delete Attr;
443
444   assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
445
446   // Enter a scope to hold everything within the compound stmt.  Compound
447   // statements can always hold declarations.
448   ParseScope CompoundScope(this, Scope::DeclScope);
449
450   // Parse the statements in the body.
451   return ParseCompoundStatementBody(isStmtExpr);
452 }
453
454
455 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
456 /// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
457 /// consume the '}' at the end of the block.  It does not manipulate the scope
458 /// stack.
459 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
460   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
461                                 Tok.getLocation(),
462                                 "in compound statement ('{}')");
463
464   SourceLocation LBraceLoc = ConsumeBrace();  // eat the '{'.
465
466   // TODO: "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
467   // only allowed at the start of a compound stmt regardless of the language.
468
469   typedef StmtVector StmtsTy;
470   StmtsTy Stmts(Actions);
471   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
472     StmtResult R;
473     if (Tok.isNot(tok::kw___extension__)) {
474       R = ParseStatementOrDeclaration(false);
475     } else {
476       // __extension__ can start declarations and it can also be a unary
477       // operator for expressions.  Consume multiple __extension__ markers here
478       // until we can determine which is which.
479       // FIXME: This loses extension expressions in the AST!
480       SourceLocation ExtLoc = ConsumeToken();
481       while (Tok.is(tok::kw___extension__))
482         ConsumeToken();
483
484       CXX0XAttributeList Attr;
485       if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
486         Attr = ParseCXX0XAttributes();
487
488       // If this is the start of a declaration, parse it as such.
489       if (isDeclarationStatement()) {
490         // __extension__ silences extension warnings in the subdeclaration.
491         // FIXME: Save the __extension__ on the decl as a node somehow?
492         ExtensionRAIIObject O(Diags);
493
494         SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
495         DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd,
496                                               Attr);
497         R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
498       } else {
499         // Otherwise this was a unary __extension__ marker.
500         ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
501
502         if (Res.isInvalid()) {
503           SkipUntil(tok::semi);
504           continue;
505         }
506
507         // FIXME: Use attributes?
508         // Eat the semicolon at the end of stmt and convert the expr into a
509         // statement.
510         ExpectAndConsume(tok::semi, diag::err_expected_semi_after_expr);
511         R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
512       }
513     }
514
515     if (R.isUsable())
516       Stmts.push_back(R.release());
517   }
518
519   // We broke out of the while loop because we found a '}' or EOF.
520   if (Tok.isNot(tok::r_brace)) {
521     Diag(Tok, diag::err_expected_rbrace);
522     Diag(LBraceLoc, diag::note_matching) << "{";
523     return StmtError();
524   }
525
526   SourceLocation RBraceLoc = ConsumeBrace();
527   return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
528                                    isStmtExpr);
529 }
530
531 /// ParseParenExprOrCondition:
532 /// [C  ]     '(' expression ')'
533 /// [C++]     '(' condition ')'       [not allowed if OnlyAllowCondition=true]
534 ///
535 /// This function parses and performs error recovery on the specified condition
536 /// or expression (depending on whether we're in C++ or C mode).  This function
537 /// goes out of its way to recover well.  It returns true if there was a parser
538 /// error (the right paren couldn't be found), which indicates that the caller
539 /// should try to recover harder.  It returns false if the condition is
540 /// successfully parsed.  Note that a successful parse can still have semantic
541 /// errors in the condition.
542 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
543                                        Decl *&DeclResult,
544                                        SourceLocation Loc,
545                                        bool ConvertToBoolean) {
546   bool ParseError = false;
547   
548   SourceLocation LParenLoc = ConsumeParen();
549   if (getLang().CPlusPlus) 
550     ParseError = ParseCXXCondition(ExprResult, DeclResult, Loc, 
551                                    ConvertToBoolean);
552   else {
553     ExprResult = ParseExpression();
554     DeclResult = 0;
555     
556     // If required, convert to a boolean value.
557     if (!ExprResult.isInvalid() && ConvertToBoolean)
558       ExprResult
559         = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
560   }
561
562   // If the parser was confused by the condition and we don't have a ')', try to
563   // recover by skipping ahead to a semi and bailing out.  If condexp is
564   // semantically invalid but we have well formed code, keep going.
565   if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
566     SkipUntil(tok::semi);
567     // Skipping may have stopped if it found the containing ')'.  If so, we can
568     // continue parsing the if statement.
569     if (Tok.isNot(tok::r_paren))
570       return true;
571   }
572
573   // Otherwise the condition is valid or the rparen is present.
574   MatchRHSPunctuation(tok::r_paren, LParenLoc);
575   return false;
576 }
577
578
579 /// ParseIfStatement
580 ///       if-statement: [C99 6.8.4.1]
581 ///         'if' '(' expression ')' statement
582 ///         'if' '(' expression ')' statement 'else' statement
583 /// [C++]   'if' '(' condition ')' statement
584 /// [C++]   'if' '(' condition ')' statement 'else' statement
585 ///
586 StmtResult Parser::ParseIfStatement(AttributeList *Attr) {
587   // FIXME: Use attributes?
588   delete Attr;
589
590   assert(Tok.is(tok::kw_if) && "Not an if stmt!");
591   SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
592
593   if (Tok.isNot(tok::l_paren)) {
594     Diag(Tok, diag::err_expected_lparen_after) << "if";
595     SkipUntil(tok::semi);
596     return StmtError();
597   }
598
599   bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
600
601   // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
602   // the case for C90.
603   //
604   // C++ 6.4p3:
605   // A name introduced by a declaration in a condition is in scope from its
606   // point of declaration until the end of the substatements controlled by the
607   // condition.
608   // C++ 3.3.2p4:
609   // Names declared in the for-init-statement, and in the condition of if,
610   // while, for, and switch statements are local to the if, while, for, or
611   // switch statement (including the controlled statement).
612   //
613   ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
614
615   // Parse the condition.
616   ExprResult CondExp;
617   Decl *CondVar = 0;
618   if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
619     return StmtError();
620
621   FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
622
623   // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
624   // there is no compound stmt.  C90 does not have this clause.  We only do this
625   // if the body isn't a compound statement to avoid push/pop in common cases.
626   //
627   // C++ 6.4p1:
628   // The substatement in a selection-statement (each substatement, in the else
629   // form of the if statement) implicitly defines a local scope.
630   //
631   // For C++ we create a scope for the condition and a new scope for
632   // substatements because:
633   // -When the 'then' scope exits, we want the condition declaration to still be
634   //    active for the 'else' scope too.
635   // -Sema will detect name clashes by considering declarations of a
636   //    'ControlScope' as part of its direct subscope.
637   // -If we wanted the condition and substatement to be in the same scope, we
638   //    would have to notify ParseStatement not to create a new scope. It's
639   //    simpler to let it create a new scope.
640   //
641   ParseScope InnerScope(this, Scope::DeclScope,
642                         C99orCXX && Tok.isNot(tok::l_brace));
643
644   // Read the 'then' stmt.
645   SourceLocation ThenStmtLoc = Tok.getLocation();
646   StmtResult ThenStmt(ParseStatement());
647
648   // Pop the 'if' scope if needed.
649   InnerScope.Exit();
650
651   // If it has an else, parse it.
652   SourceLocation ElseLoc;
653   SourceLocation ElseStmtLoc;
654   StmtResult ElseStmt;
655
656   if (Tok.is(tok::kw_else)) {
657     ElseLoc = ConsumeToken();
658     ElseStmtLoc = Tok.getLocation();
659
660     // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
661     // there is no compound stmt.  C90 does not have this clause.  We only do
662     // this if the body isn't a compound statement to avoid push/pop in common
663     // cases.
664     //
665     // C++ 6.4p1:
666     // The substatement in a selection-statement (each substatement, in the else
667     // form of the if statement) implicitly defines a local scope.
668     //
669     ParseScope InnerScope(this, Scope::DeclScope,
670                           C99orCXX && Tok.isNot(tok::l_brace));
671
672     ElseStmt = ParseStatement();
673     
674     // Pop the 'else' scope if needed.
675     InnerScope.Exit();
676   }
677
678   IfScope.Exit();
679
680   // If the condition was invalid, discard the if statement.  We could recover
681   // better by replacing it with a valid expr, but don't do that yet.
682   if (CondExp.isInvalid() && !CondVar)
683     return StmtError();
684
685   // If the then or else stmt is invalid and the other is valid (and present),
686   // make turn the invalid one into a null stmt to avoid dropping the other
687   // part.  If both are invalid, return error.
688   if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
689       (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
690       (ThenStmt.get() == 0  && ElseStmt.isInvalid())) {
691     // Both invalid, or one is invalid and other is non-present: return error.
692     return StmtError();
693   }
694
695   // Now if either are invalid, replace with a ';'.
696   if (ThenStmt.isInvalid())
697     ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
698   if (ElseStmt.isInvalid())
699     ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
700
701   return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
702                              ElseLoc, ElseStmt.get());
703 }
704
705 /// ParseSwitchStatement
706 ///       switch-statement:
707 ///         'switch' '(' expression ')' statement
708 /// [C++]   'switch' '(' condition ')' statement
709 StmtResult Parser::ParseSwitchStatement(AttributeList *Attr) {
710   // FIXME: Use attributes?
711   delete Attr;
712
713   assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
714   SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
715
716   if (Tok.isNot(tok::l_paren)) {
717     Diag(Tok, diag::err_expected_lparen_after) << "switch";
718     SkipUntil(tok::semi);
719     return StmtError();
720   }
721
722   bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
723
724   // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
725   // not the case for C90.  Start the switch scope.
726   //
727   // C++ 6.4p3:
728   // A name introduced by a declaration in a condition is in scope from its
729   // point of declaration until the end of the substatements controlled by the
730   // condition.
731   // C++ 3.3.2p4:
732   // Names declared in the for-init-statement, and in the condition of if,
733   // while, for, and switch statements are local to the if, while, for, or
734   // switch statement (including the controlled statement).
735   //
736   unsigned ScopeFlags = Scope::BreakScope;
737   if (C99orCXX)
738     ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
739   ParseScope SwitchScope(this, ScopeFlags);
740
741   // Parse the condition.
742   ExprResult Cond;
743   Decl *CondVar = 0;
744   if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
745     return StmtError();
746
747   StmtResult Switch
748     = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
749
750   if (Switch.isInvalid()) {
751     // Skip the switch body. 
752     // FIXME: This is not optimal recovery, but parsing the body is more
753     // dangerous due to the presence of case and default statements, which
754     // will have no place to connect back with the switch.
755     if (Tok.is(tok::l_brace)) {
756       ConsumeBrace();
757       SkipUntil(tok::r_brace, false, false);
758     } else
759       SkipUntil(tok::semi);
760     return move(Switch);
761   }
762   
763   // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
764   // there is no compound stmt.  C90 does not have this clause.  We only do this
765   // if the body isn't a compound statement to avoid push/pop in common cases.
766   //
767   // C++ 6.4p1:
768   // The substatement in a selection-statement (each substatement, in the else
769   // form of the if statement) implicitly defines a local scope.
770   //
771   // See comments in ParseIfStatement for why we create a scope for the
772   // condition and a new scope for substatement in C++.
773   //
774   ParseScope InnerScope(this, Scope::DeclScope,
775                         C99orCXX && Tok.isNot(tok::l_brace));
776
777   // Read the body statement.
778   StmtResult Body(ParseStatement());
779
780   // Pop the scopes.
781   InnerScope.Exit();
782   SwitchScope.Exit();
783
784   if (Body.isInvalid())
785     // FIXME: Remove the case statement list from the Switch statement.
786     Body = Actions.ActOnNullStmt(Tok.getLocation());
787   
788   return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
789 }
790
791 /// ParseWhileStatement
792 ///       while-statement: [C99 6.8.5.1]
793 ///         'while' '(' expression ')' statement
794 /// [C++]   'while' '(' condition ')' statement
795 StmtResult Parser::ParseWhileStatement(AttributeList *Attr) {
796   // FIXME: Use attributes?
797   delete Attr;
798
799   assert(Tok.is(tok::kw_while) && "Not a while stmt!");
800   SourceLocation WhileLoc = Tok.getLocation();
801   ConsumeToken();  // eat the 'while'.
802
803   if (Tok.isNot(tok::l_paren)) {
804     Diag(Tok, diag::err_expected_lparen_after) << "while";
805     SkipUntil(tok::semi);
806     return StmtError();
807   }
808
809   bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
810
811   // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
812   // the case for C90.  Start the loop scope.
813   //
814   // C++ 6.4p3:
815   // A name introduced by a declaration in a condition is in scope from its
816   // point of declaration until the end of the substatements controlled by the
817   // condition.
818   // C++ 3.3.2p4:
819   // Names declared in the for-init-statement, and in the condition of if,
820   // while, for, and switch statements are local to the if, while, for, or
821   // switch statement (including the controlled statement).
822   //
823   unsigned ScopeFlags;
824   if (C99orCXX)
825     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
826                  Scope::DeclScope  | Scope::ControlScope;
827   else
828     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
829   ParseScope WhileScope(this, ScopeFlags);
830
831   // Parse the condition.
832   ExprResult Cond;
833   Decl *CondVar = 0;
834   if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
835     return StmtError();
836
837   FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
838
839   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
840   // there is no compound stmt.  C90 does not have this clause.  We only do this
841   // if the body isn't a compound statement to avoid push/pop in common cases.
842   //
843   // C++ 6.5p2:
844   // The substatement in an iteration-statement implicitly defines a local scope
845   // which is entered and exited each time through the loop.
846   //
847   // See comments in ParseIfStatement for why we create a scope for the
848   // condition and a new scope for substatement in C++.
849   //
850   ParseScope InnerScope(this, Scope::DeclScope,
851                         C99orCXX && Tok.isNot(tok::l_brace));
852
853   // Read the body statement.
854   StmtResult Body(ParseStatement());
855
856   // Pop the body scope if needed.
857   InnerScope.Exit();
858   WhileScope.Exit();
859
860   if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
861     return StmtError();
862
863   return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
864 }
865
866 /// ParseDoStatement
867 ///       do-statement: [C99 6.8.5.2]
868 ///         'do' statement 'while' '(' expression ')' ';'
869 /// Note: this lets the caller parse the end ';'.
870 StmtResult Parser::ParseDoStatement(AttributeList *Attr) {
871   // FIXME: Use attributes?
872   delete Attr;
873
874   assert(Tok.is(tok::kw_do) && "Not a do stmt!");
875   SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
876
877   // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
878   // the case for C90.  Start the loop scope.
879   unsigned ScopeFlags;
880   if (getLang().C99)
881     ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
882   else
883     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
884
885   ParseScope DoScope(this, ScopeFlags);
886
887   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
888   // there is no compound stmt.  C90 does not have this clause. We only do this
889   // if the body isn't a compound statement to avoid push/pop in common cases.
890   //
891   // C++ 6.5p2:
892   // The substatement in an iteration-statement implicitly defines a local scope
893   // which is entered and exited each time through the loop.
894   //
895   ParseScope InnerScope(this, Scope::DeclScope,
896                         (getLang().C99 || getLang().CPlusPlus) &&
897                         Tok.isNot(tok::l_brace));
898
899   // Read the body statement.
900   StmtResult Body(ParseStatement());
901
902   // Pop the body scope if needed.
903   InnerScope.Exit();
904
905   if (Tok.isNot(tok::kw_while)) {
906     if (!Body.isInvalid()) {
907       Diag(Tok, diag::err_expected_while);
908       Diag(DoLoc, diag::note_matching) << "do";
909       SkipUntil(tok::semi, false, true);
910     }
911     return StmtError();
912   }
913   SourceLocation WhileLoc = ConsumeToken();
914
915   if (Tok.isNot(tok::l_paren)) {
916     Diag(Tok, diag::err_expected_lparen_after) << "do/while";
917     SkipUntil(tok::semi, false, true);
918     return StmtError();
919   }
920
921   // Parse the parenthesized condition.
922   SourceLocation LPLoc = ConsumeParen();
923   ExprResult Cond = ParseExpression();
924   SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
925   DoScope.Exit();
926
927   if (Cond.isInvalid() || Body.isInvalid())
928     return StmtError();
929
930   return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, LPLoc,
931                              Cond.get(), RPLoc);
932 }
933
934 /// ParseForStatement
935 ///       for-statement: [C99 6.8.5.3]
936 ///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
937 ///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
938 /// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
939 /// [C++]       statement
940 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
941 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
942 ///
943 /// [C++] for-init-statement:
944 /// [C++]   expression-statement
945 /// [C++]   simple-declaration
946 ///
947 StmtResult Parser::ParseForStatement(AttributeList *Attr) {
948   // FIXME: Use attributes?
949   delete Attr;
950
951   assert(Tok.is(tok::kw_for) && "Not a for stmt!");
952   SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
953
954   if (Tok.isNot(tok::l_paren)) {
955     Diag(Tok, diag::err_expected_lparen_after) << "for";
956     SkipUntil(tok::semi);
957     return StmtError();
958   }
959
960   bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
961
962   // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
963   // the case for C90.  Start the loop scope.
964   //
965   // C++ 6.4p3:
966   // A name introduced by a declaration in a condition is in scope from its
967   // point of declaration until the end of the substatements controlled by the
968   // condition.
969   // C++ 3.3.2p4:
970   // Names declared in the for-init-statement, and in the condition of if,
971   // while, for, and switch statements are local to the if, while, for, or
972   // switch statement (including the controlled statement).
973   // C++ 6.5.3p1:
974   // Names declared in the for-init-statement are in the same declarative-region
975   // as those declared in the condition.
976   //
977   unsigned ScopeFlags;
978   if (C99orCXXorObjC)
979     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
980                  Scope::DeclScope  | Scope::ControlScope;
981   else
982     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
983
984   ParseScope ForScope(this, ScopeFlags);
985
986   SourceLocation LParenLoc = ConsumeParen();
987   ExprResult Value;
988
989   bool ForEach = false;
990   StmtResult FirstPart;
991   bool SecondPartIsInvalid = false;
992   FullExprArg SecondPart(Actions);
993   ExprResult Collection;
994   FullExprArg ThirdPart(Actions);
995   Decl *SecondVar = 0;
996   
997   if (Tok.is(tok::code_completion)) {
998     Actions.CodeCompleteOrdinaryName(getCurScope(), 
999                                      C99orCXXorObjC? Sema::PCC_ForInit
1000                                                    : Sema::PCC_Expression);
1001     ConsumeCodeCompletionToken();
1002   }
1003   
1004   // Parse the first part of the for specifier.
1005   if (Tok.is(tok::semi)) {  // for (;
1006     // no first part, eat the ';'.
1007     ConsumeToken();
1008   } else if (isSimpleDeclaration()) {  // for (int X = 4;
1009     // Parse declaration, which eats the ';'.
1010     if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
1011       Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1012
1013     AttributeList *AttrList = 0;
1014     if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1015       AttrList = ParseCXX0XAttributes().AttrList;
1016
1017     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1018     DeclGroupPtrTy DG = ParseSimpleDeclaration(Declarator::ForContext, DeclEnd,
1019                                                AttrList, false);
1020     FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1021
1022     if (Tok.is(tok::semi)) {  // for (int x = 4;
1023       ConsumeToken();
1024     } else if ((ForEach = isTokIdentifier_in())) {
1025       Actions.ActOnForEachDeclStmt(DG);
1026       // ObjC: for (id x in expr)
1027       ConsumeToken(); // consume 'in'
1028       
1029       if (Tok.is(tok::code_completion)) {
1030         Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1031         ConsumeCodeCompletionToken();
1032       }
1033       Collection = ParseExpression();
1034     } else {
1035       Diag(Tok, diag::err_expected_semi_for);
1036       SkipUntil(tok::semi);
1037     }
1038   } else {
1039     Value = ParseExpression();
1040
1041     // Turn the expression into a stmt.
1042     if (!Value.isInvalid())
1043       FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1044
1045     if (Tok.is(tok::semi)) {
1046       ConsumeToken();
1047     } else if ((ForEach = isTokIdentifier_in())) {
1048       ConsumeToken(); // consume 'in'
1049       
1050       if (Tok.is(tok::code_completion)) {
1051         Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1052         ConsumeCodeCompletionToken();
1053       }
1054       Collection = ParseExpression();
1055     } else {
1056       if (!Value.isInvalid()) Diag(Tok, diag::err_expected_semi_for);
1057       SkipUntil(tok::semi);
1058     }
1059   }
1060   if (!ForEach) {
1061     assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1062     // Parse the second part of the for specifier.
1063     if (Tok.is(tok::semi)) {  // for (...;;
1064       // no second part.
1065     } else {
1066       ExprResult Second;
1067       if (getLang().CPlusPlus)
1068         ParseCXXCondition(Second, SecondVar, ForLoc, true);
1069       else {
1070         Second = ParseExpression();
1071         if (!Second.isInvalid())
1072           Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc, 
1073                                                  Second.get());
1074       }
1075       SecondPartIsInvalid = Second.isInvalid();
1076       SecondPart = Actions.MakeFullExpr(Second.get());
1077     }
1078
1079     if (Tok.is(tok::semi)) {
1080       ConsumeToken();
1081     } else {
1082       if (!SecondPartIsInvalid || SecondVar) 
1083         Diag(Tok, diag::err_expected_semi_for);
1084       SkipUntil(tok::semi);
1085     }
1086
1087     // Parse the third part of the for specifier.
1088     if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
1089       ExprResult Third = ParseExpression();
1090       ThirdPart = Actions.MakeFullExpr(Third.take());
1091     }
1092   }
1093   // Match the ')'.
1094   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1095
1096   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1097   // there is no compound stmt.  C90 does not have this clause.  We only do this
1098   // if the body isn't a compound statement to avoid push/pop in common cases.
1099   //
1100   // C++ 6.5p2:
1101   // The substatement in an iteration-statement implicitly defines a local scope
1102   // which is entered and exited each time through the loop.
1103   //
1104   // See comments in ParseIfStatement for why we create a scope for
1105   // for-init-statement/condition and a new scope for substatement in C++.
1106   //
1107   ParseScope InnerScope(this, Scope::DeclScope,
1108                         C99orCXXorObjC && Tok.isNot(tok::l_brace));
1109
1110   // Read the body statement.
1111   StmtResult Body(ParseStatement());
1112
1113   // Pop the body scope if needed.
1114   InnerScope.Exit();
1115
1116   // Leave the for-scope.
1117   ForScope.Exit();
1118
1119   if (Body.isInvalid())
1120     return StmtError();
1121
1122   if (!ForEach)
1123     return Actions.ActOnForStmt(ForLoc, LParenLoc, FirstPart.take(), SecondPart,
1124                                 SecondVar, ThirdPart, RParenLoc, Body.take());
1125
1126   // FIXME: It isn't clear how to communicate the late destruction of 
1127   // C++ temporaries used to create the collection.
1128   return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc, FirstPart.take(), 
1129                                             Collection.take(), RParenLoc, 
1130                                             Body.take());
1131 }
1132
1133 /// ParseGotoStatement
1134 ///       jump-statement:
1135 ///         'goto' identifier ';'
1136 /// [GNU]   'goto' '*' expression ';'
1137 ///
1138 /// Note: this lets the caller parse the end ';'.
1139 ///
1140 StmtResult Parser::ParseGotoStatement(AttributeList *Attr) {
1141   // FIXME: Use attributes?
1142   delete Attr;
1143
1144   assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1145   SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
1146
1147   StmtResult Res;
1148   if (Tok.is(tok::identifier)) {
1149     Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(),
1150                                 Tok.getIdentifierInfo());
1151     ConsumeToken();
1152   } else if (Tok.is(tok::star)) {
1153     // GNU indirect goto extension.
1154     Diag(Tok, diag::ext_gnu_indirect_goto);
1155     SourceLocation StarLoc = ConsumeToken();
1156     ExprResult R(ParseExpression());
1157     if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1158       SkipUntil(tok::semi, false, true);
1159       return StmtError();
1160     }
1161     Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1162   } else {
1163     Diag(Tok, diag::err_expected_ident);
1164     return StmtError();
1165   }
1166
1167   return move(Res);
1168 }
1169
1170 /// ParseContinueStatement
1171 ///       jump-statement:
1172 ///         'continue' ';'
1173 ///
1174 /// Note: this lets the caller parse the end ';'.
1175 ///
1176 StmtResult Parser::ParseContinueStatement(AttributeList *Attr) {
1177   // FIXME: Use attributes?
1178   delete Attr;
1179
1180   SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
1181   return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1182 }
1183
1184 /// ParseBreakStatement
1185 ///       jump-statement:
1186 ///         'break' ';'
1187 ///
1188 /// Note: this lets the caller parse the end ';'.
1189 ///
1190 StmtResult Parser::ParseBreakStatement(AttributeList *Attr) {
1191   // FIXME: Use attributes?
1192   delete Attr;
1193
1194   SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
1195   return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1196 }
1197
1198 /// ParseReturnStatement
1199 ///       jump-statement:
1200 ///         'return' expression[opt] ';'
1201 StmtResult Parser::ParseReturnStatement(AttributeList *Attr) {
1202   // FIXME: Use attributes?
1203   delete Attr;
1204
1205   assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1206   SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
1207
1208   ExprResult R;
1209   if (Tok.isNot(tok::semi)) {
1210     if (Tok.is(tok::code_completion)) {
1211       Actions.CodeCompleteReturn(getCurScope());
1212       ConsumeCodeCompletionToken();
1213       SkipUntil(tok::semi, false, true);
1214       return StmtError();
1215     }
1216         
1217     R = ParseExpression();
1218     if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1219       SkipUntil(tok::semi, false, true);
1220       return StmtError();
1221     }
1222   }
1223   return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1224 }
1225
1226 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1227 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1228 StmtResult Parser::FuzzyParseMicrosoftAsmStatement() {
1229   if (Tok.is(tok::l_brace)) {
1230     unsigned short savedBraceCount = BraceCount;
1231     do {
1232       ConsumeAnyToken();
1233     } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1234   } else {
1235     // From the MS website: If used without braces, the __asm keyword means
1236     // that the rest of the line is an assembly-language statement.
1237     SourceManager &SrcMgr = PP.getSourceManager();
1238     SourceLocation TokLoc = Tok.getLocation();
1239     unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1240     do {
1241       ConsumeAnyToken();
1242       TokLoc = Tok.getLocation();
1243     } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1244              Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1245              Tok.isNot(tok::eof));
1246   }
1247   Token t;
1248   t.setKind(tok::string_literal);
1249   t.setLiteralData("\"/*FIXME: not done*/\"");
1250   t.clearFlag(Token::NeedsCleaning);
1251   t.setLength(21);
1252   ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1253   ExprVector Constraints(Actions);
1254   ExprVector Exprs(Actions);
1255   ExprVector Clobbers(Actions);
1256   return Actions.ActOnAsmStmt(Tok.getLocation(), true, true, 0, 0, 0,
1257                               move_arg(Constraints), move_arg(Exprs),
1258                               AsmString.take(), move_arg(Clobbers),
1259                               Tok.getLocation(), true);
1260 }
1261
1262 /// ParseAsmStatement - Parse a GNU extended asm statement.
1263 ///       asm-statement:
1264 ///         gnu-asm-statement
1265 ///         ms-asm-statement
1266 ///
1267 /// [GNU] gnu-asm-statement:
1268 ///         'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1269 ///
1270 /// [GNU] asm-argument:
1271 ///         asm-string-literal
1272 ///         asm-string-literal ':' asm-operands[opt]
1273 ///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1274 ///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1275 ///                 ':' asm-clobbers
1276 ///
1277 /// [GNU] asm-clobbers:
1278 ///         asm-string-literal
1279 ///         asm-clobbers ',' asm-string-literal
1280 ///
1281 /// [MS]  ms-asm-statement:
1282 ///         '__asm' assembly-instruction ';'[opt]
1283 ///         '__asm' '{' assembly-instruction-list '}' ';'[opt]
1284 ///
1285 /// [MS]  assembly-instruction-list:
1286 ///         assembly-instruction ';'[opt]
1287 ///         assembly-instruction-list ';' assembly-instruction ';'[opt]
1288 ///
1289 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
1290   assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1291   SourceLocation AsmLoc = ConsumeToken();
1292
1293   if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1294     msAsm = true;
1295     return FuzzyParseMicrosoftAsmStatement();
1296   }
1297   DeclSpec DS;
1298   SourceLocation Loc = Tok.getLocation();
1299   ParseTypeQualifierListOpt(DS, true, false);
1300
1301   // GNU asms accept, but warn, about type-qualifiers other than volatile.
1302   if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1303     Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1304   if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1305     Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1306
1307   // Remember if this was a volatile asm.
1308   bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1309   if (Tok.isNot(tok::l_paren)) {
1310     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1311     SkipUntil(tok::r_paren);
1312     return StmtError();
1313   }
1314   Loc = ConsumeParen();
1315
1316   ExprResult AsmString(ParseAsmStringLiteral());
1317   if (AsmString.isInvalid())
1318     return StmtError();
1319
1320   llvm::SmallVector<IdentifierInfo *, 4> Names;
1321   ExprVector Constraints(Actions);
1322   ExprVector Exprs(Actions);
1323   ExprVector Clobbers(Actions);
1324
1325   if (Tok.is(tok::r_paren)) {
1326     // We have a simple asm expression like 'asm("foo")'.
1327     SourceLocation RParenLoc = ConsumeParen();
1328     return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1329                                 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0, 
1330                                 move_arg(Constraints), move_arg(Exprs),
1331                                 AsmString.take(), move_arg(Clobbers),
1332                                 RParenLoc);
1333   }
1334
1335   // Parse Outputs, if present.
1336   bool AteExtraColon = false;
1337   if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1338     // In C++ mode, parse "::" like ": :".
1339     AteExtraColon = Tok.is(tok::coloncolon);
1340     ConsumeToken();
1341   
1342     if (!AteExtraColon &&
1343         ParseAsmOperandsOpt(Names, Constraints, Exprs))
1344       return StmtError();
1345   }
1346   
1347   unsigned NumOutputs = Names.size();
1348
1349   // Parse Inputs, if present.
1350   if (AteExtraColon ||
1351       Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1352     // In C++ mode, parse "::" like ": :".
1353     if (AteExtraColon)
1354       AteExtraColon = false;
1355     else {
1356       AteExtraColon = Tok.is(tok::coloncolon);
1357       ConsumeToken();
1358     }
1359     
1360     if (!AteExtraColon &&
1361         ParseAsmOperandsOpt(Names, Constraints, Exprs))
1362       return StmtError();
1363   }
1364
1365   assert(Names.size() == Constraints.size() &&
1366          Constraints.size() == Exprs.size() &&
1367          "Input operand size mismatch!");
1368
1369   unsigned NumInputs = Names.size() - NumOutputs;
1370
1371   // Parse the clobbers, if present.
1372   if (AteExtraColon || Tok.is(tok::colon)) {
1373     if (!AteExtraColon)
1374       ConsumeToken();
1375
1376     // Parse the asm-string list for clobbers if present.
1377     if (Tok.isNot(tok::r_paren)) {
1378       while (1) {
1379         ExprResult Clobber(ParseAsmStringLiteral());
1380
1381         if (Clobber.isInvalid())
1382           break;
1383
1384         Clobbers.push_back(Clobber.release());
1385
1386         if (Tok.isNot(tok::comma)) break;
1387         ConsumeToken();
1388       }
1389     }
1390   }
1391
1392   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1393   return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1394                               NumOutputs, NumInputs, Names.data(),
1395                               move_arg(Constraints), move_arg(Exprs),
1396                               AsmString.take(), move_arg(Clobbers),
1397                               RParenLoc);
1398 }
1399
1400 /// ParseAsmOperands - Parse the asm-operands production as used by
1401 /// asm-statement, assuming the leading ':' token was eaten.
1402 ///
1403 /// [GNU] asm-operands:
1404 ///         asm-operand
1405 ///         asm-operands ',' asm-operand
1406 ///
1407 /// [GNU] asm-operand:
1408 ///         asm-string-literal '(' expression ')'
1409 ///         '[' identifier ']' asm-string-literal '(' expression ')'
1410 ///
1411 //
1412 // FIXME: Avoid unnecessary std::string trashing.
1413 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1414                                  llvm::SmallVectorImpl<ExprTy *> &Constraints,
1415                                  llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1416   // 'asm-operands' isn't present?
1417   if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1418     return false;
1419
1420   while (1) {
1421     // Read the [id] if present.
1422     if (Tok.is(tok::l_square)) {
1423       SourceLocation Loc = ConsumeBracket();
1424
1425       if (Tok.isNot(tok::identifier)) {
1426         Diag(Tok, diag::err_expected_ident);
1427         SkipUntil(tok::r_paren);
1428         return true;
1429       }
1430
1431       IdentifierInfo *II = Tok.getIdentifierInfo();
1432       ConsumeToken();
1433
1434       Names.push_back(II);
1435       MatchRHSPunctuation(tok::r_square, Loc);
1436     } else
1437       Names.push_back(0);
1438
1439     ExprResult Constraint(ParseAsmStringLiteral());
1440     if (Constraint.isInvalid()) {
1441         SkipUntil(tok::r_paren);
1442         return true;
1443     }
1444     Constraints.push_back(Constraint.release());
1445
1446     if (Tok.isNot(tok::l_paren)) {
1447       Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1448       SkipUntil(tok::r_paren);
1449       return true;
1450     }
1451
1452     // Read the parenthesized expression.
1453     SourceLocation OpenLoc = ConsumeParen();
1454     ExprResult Res(ParseExpression());
1455     MatchRHSPunctuation(tok::r_paren, OpenLoc);
1456     if (Res.isInvalid()) {
1457       SkipUntil(tok::r_paren);
1458       return true;
1459     }
1460     Exprs.push_back(Res.release());
1461     // Eat the comma and continue parsing if it exists.
1462     if (Tok.isNot(tok::comma)) return false;
1463     ConsumeToken();
1464   }
1465
1466   return true;
1467 }
1468
1469 Decl *Parser::ParseFunctionStatementBody(Decl *Decl) {
1470   assert(Tok.is(tok::l_brace));
1471   SourceLocation LBraceLoc = Tok.getLocation();
1472
1473   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1474                                       "parsing function body");
1475
1476   // Do not enter a scope for the brace, as the arguments are in the same scope
1477   // (the function body) as the body itself.  Instead, just read the statement
1478   // list and put it into a CompoundStmt for safe keeping.
1479   StmtResult FnBody(ParseCompoundStatementBody());
1480
1481   // If the function body could not be parsed, make a bogus compoundstmt.
1482   if (FnBody.isInvalid())
1483     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1484                                        MultiStmtArg(Actions), false);
1485
1486   return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1487 }
1488
1489 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1490 ///
1491 ///       function-try-block:
1492 ///         'try' ctor-initializer[opt] compound-statement handler-seq
1493 ///
1494 Decl *Parser::ParseFunctionTryBlock(Decl *Decl) {
1495   assert(Tok.is(tok::kw_try) && "Expected 'try'");
1496   SourceLocation TryLoc = ConsumeToken();
1497
1498   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1499                                       "parsing function try block");
1500
1501   // Constructor initializer list?
1502   if (Tok.is(tok::colon))
1503     ParseConstructorInitializer(Decl);
1504
1505   SourceLocation LBraceLoc = Tok.getLocation();
1506   StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1507   // If we failed to parse the try-catch, we just give the function an empty
1508   // compound statement as the body.
1509   if (FnBody.isInvalid())
1510     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1511                                        MultiStmtArg(Actions), false);
1512
1513   return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1514 }
1515
1516 /// ParseCXXTryBlock - Parse a C++ try-block.
1517 ///
1518 ///       try-block:
1519 ///         'try' compound-statement handler-seq
1520 ///
1521 StmtResult Parser::ParseCXXTryBlock(AttributeList* Attr) {
1522   // FIXME: Add attributes?
1523   delete Attr;
1524
1525   assert(Tok.is(tok::kw_try) && "Expected 'try'");
1526
1527   SourceLocation TryLoc = ConsumeToken();
1528   return ParseCXXTryBlockCommon(TryLoc);
1529 }
1530
1531 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1532 /// function-try-block.
1533 ///
1534 ///       try-block:
1535 ///         'try' compound-statement handler-seq
1536 ///
1537 ///       function-try-block:
1538 ///         'try' ctor-initializer[opt] compound-statement handler-seq
1539 ///
1540 ///       handler-seq:
1541 ///         handler handler-seq[opt]
1542 ///
1543 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1544   if (Tok.isNot(tok::l_brace))
1545     return StmtError(Diag(Tok, diag::err_expected_lbrace));
1546   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1547   StmtResult TryBlock(ParseCompoundStatement(0));
1548   if (TryBlock.isInvalid())
1549     return move(TryBlock);
1550
1551   StmtVector Handlers(Actions);
1552   if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1553     CXX0XAttributeList Attr = ParseCXX0XAttributes();
1554     Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
1555       << Attr.Range;
1556   }
1557   if (Tok.isNot(tok::kw_catch))
1558     return StmtError(Diag(Tok, diag::err_expected_catch));
1559   while (Tok.is(tok::kw_catch)) {
1560     StmtResult Handler(ParseCXXCatchBlock());
1561     if (!Handler.isInvalid())
1562       Handlers.push_back(Handler.release());
1563   }
1564   // Don't bother creating the full statement if we don't have any usable
1565   // handlers.
1566   if (Handlers.empty())
1567     return StmtError();
1568
1569   return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
1570 }
1571
1572 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1573 ///
1574 ///       handler:
1575 ///         'catch' '(' exception-declaration ')' compound-statement
1576 ///
1577 ///       exception-declaration:
1578 ///         type-specifier-seq declarator
1579 ///         type-specifier-seq abstract-declarator
1580 ///         type-specifier-seq
1581 ///         '...'
1582 ///
1583 StmtResult Parser::ParseCXXCatchBlock() {
1584   assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1585
1586   SourceLocation CatchLoc = ConsumeToken();
1587
1588   SourceLocation LParenLoc = Tok.getLocation();
1589   if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1590     return StmtError();
1591
1592   // C++ 3.3.2p3:
1593   // The name in a catch exception-declaration is local to the handler and
1594   // shall not be redeclared in the outermost block of the handler.
1595   ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1596
1597   // exception-declaration is equivalent to '...' or a parameter-declaration
1598   // without default arguments.
1599   Decl *ExceptionDecl = 0;
1600   if (Tok.isNot(tok::ellipsis)) {
1601     DeclSpec DS;
1602     if (ParseCXXTypeSpecifierSeq(DS))
1603       return StmtError();
1604     Declarator ExDecl(DS, Declarator::CXXCatchContext);
1605     ParseDeclarator(ExDecl);
1606     ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
1607   } else
1608     ConsumeToken();
1609
1610   if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
1611     return StmtError();
1612
1613   if (Tok.isNot(tok::l_brace))
1614     return StmtError(Diag(Tok, diag::err_expected_lbrace));
1615
1616   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1617   StmtResult Block(ParseCompoundStatement(0));
1618   if (Block.isInvalid())
1619     return move(Block);
1620
1621   return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
1622 }