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