]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseStmt.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.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 /// [MS]    seh-try-block
44 /// [OBC]   objc-throw-statement
45 /// [OBC]   objc-try-catch-statement
46 /// [OBC]   objc-synchronized-statement
47 /// [GNU]   asm-statement
48 /// [OMP]   openmp-construct             [TODO]
49 ///
50 ///       labeled-statement:
51 ///         identifier ':' statement
52 ///         'case' constant-expression ':' statement
53 ///         'default' ':' statement
54 ///
55 ///       selection-statement:
56 ///         if-statement
57 ///         switch-statement
58 ///
59 ///       iteration-statement:
60 ///         while-statement
61 ///         do-statement
62 ///         for-statement
63 ///
64 ///       expression-statement:
65 ///         expression[opt] ';'
66 ///
67 ///       jump-statement:
68 ///         'goto' identifier ';'
69 ///         'continue' ';'
70 ///         'break' ';'
71 ///         'return' expression[opt] ';'
72 /// [GNU]   'goto' '*' expression ';'
73 ///
74 /// [OBC] objc-throw-statement:
75 /// [OBC]   '@' 'throw' expression ';'
76 /// [OBC]   '@' 'throw' ';'
77 ///
78 StmtResult
79 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement) {
80   const char *SemiError = 0;
81   StmtResult Res;
82   
83   ParenBraceBracketBalancer BalancerRAIIObj(*this);
84
85   ParsedAttributesWithRange attrs(AttrFactory);
86   MaybeParseCXX0XAttributes(attrs);
87
88   // Cases in this switch statement should fall through if the parser expects
89   // the token to end in a semicolon (in which case SemiError should be set),
90   // or they directly 'return;' if not.
91 Retry:
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(Stmts, OnlyStatement);
105       
106   case tok::identifier: {
107     Token Next = NextToken();
108     if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
109       // identifier ':' statement
110       return ParseLabeledStatement(attrs);
111     }
112     
113     if (Next.isNot(tok::coloncolon)) {
114       CXXScopeSpec SS;
115       IdentifierInfo *Name = Tok.getIdentifierInfo();
116       SourceLocation NameLoc = Tok.getLocation();
117       Sema::NameClassification Classification
118         = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next);
119       switch (Classification.getKind()) {
120       case Sema::NC_Keyword:
121         // The identifier was corrected to a keyword. Update the token
122         // to this keyword, and try again.
123         if (Name->getTokenID() != tok::identifier) {
124           Tok.setIdentifierInfo(Name);
125           Tok.setKind(Name->getTokenID());
126           goto Retry;
127         }
128           
129         // Fall through via the normal error path.
130         // FIXME: This seems like it could only happen for context-sensitive
131         // keywords.
132           
133       case Sema::NC_Error:
134         // Handle errors here by skipping up to the next semicolon or '}', and
135         // eat the semicolon if that's what stopped us.
136         SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
137         if (Tok.is(tok::semi))
138           ConsumeToken();
139         return StmtError();
140                      
141       case Sema::NC_Unknown:
142         // Either we don't know anything about this identifier, or we know that
143         // we're in a syntactic context we haven't handled yet. 
144         break;     
145           
146       case Sema::NC_Type:
147         Tok.setKind(tok::annot_typename);
148         setTypeAnnotation(Tok, Classification.getType());
149         Tok.setAnnotationEndLoc(NameLoc);
150         PP.AnnotateCachedTokens(Tok);
151         break;
152           
153       case Sema::NC_Expression:
154         Tok.setKind(tok::annot_primary_expr);
155         setExprAnnotation(Tok, Classification.getExpression());
156         Tok.setAnnotationEndLoc(NameLoc);
157         PP.AnnotateCachedTokens(Tok);
158         break;
159           
160       case Sema::NC_TypeTemplate:
161       case Sema::NC_FunctionTemplate: {
162         ConsumeToken(); // the identifier
163         UnqualifiedId Id;
164         Id.setIdentifier(Name, NameLoc);
165         if (AnnotateTemplateIdToken(
166                             TemplateTy::make(Classification.getTemplateName()), 
167                                     Classification.getTemplateNameKind(),
168                                     SS, Id, SourceLocation(),
169                                     /*AllowTypeAnnotation=*/false)) {
170           // Handle errors here by skipping up to the next semicolon or '}', and
171           // eat the semicolon if that's what stopped us.
172           SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
173           if (Tok.is(tok::semi))
174             ConsumeToken();
175           return StmtError();        
176         }
177         
178         // If the next token is '::', jump right into parsing a 
179         // nested-name-specifier. We don't want to leave the template-id
180         // hanging.
181         if (NextToken().is(tok::coloncolon) && TryAnnotateCXXScopeToken(false)){
182           // Handle errors here by skipping up to the next semicolon or '}', and
183           // eat the semicolon if that's what stopped us.
184           SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
185           if (Tok.is(tok::semi))
186             ConsumeToken();
187           return StmtError();        
188         }
189         
190         // We've annotated a template-id, so try again now.
191         goto Retry;
192       }
193        
194       case Sema::NC_NestedNameSpecifier:
195         // FIXME: Implement this!
196         break;
197       }
198     }
199     
200     // Fall through
201   }
202       
203   default: {
204     if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
205       SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
206       DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
207                                              DeclEnd, attrs);
208       return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
209     }
210
211     if (Tok.is(tok::r_brace)) {
212       Diag(Tok, diag::err_expected_statement);
213       return StmtError();
214     }
215
216     return ParseExprStatement(attrs);
217   }
218
219   case tok::kw_case:                // C99 6.8.1: labeled-statement
220     return ParseCaseStatement(attrs);
221   case tok::kw_default:             // C99 6.8.1: labeled-statement
222     return ParseDefaultStatement(attrs);
223
224   case tok::l_brace:                // C99 6.8.2: compound-statement
225     return ParseCompoundStatement(attrs);
226   case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
227     SourceLocation LeadingEmptyMacroLoc;
228     if (Tok.hasLeadingEmptyMacro())
229       LeadingEmptyMacroLoc = PP.getLastEmptyMacroExpansionLoc();
230     return Actions.ActOnNullStmt(ConsumeToken(), LeadingEmptyMacroLoc);
231   }
232
233   case tok::kw_if:                  // C99 6.8.4.1: if-statement
234     return ParseIfStatement(attrs);
235   case tok::kw_switch:              // C99 6.8.4.2: switch-statement
236     return ParseSwitchStatement(attrs);
237
238   case tok::kw_while:               // C99 6.8.5.1: while-statement
239     return ParseWhileStatement(attrs);
240   case tok::kw_do:                  // C99 6.8.5.2: do-statement
241     Res = ParseDoStatement(attrs);
242     SemiError = "do/while";
243     break;
244   case tok::kw_for:                 // C99 6.8.5.3: for-statement
245     return ParseForStatement(attrs);
246
247   case tok::kw_goto:                // C99 6.8.6.1: goto-statement
248     Res = ParseGotoStatement(attrs);
249     SemiError = "goto";
250     break;
251   case tok::kw_continue:            // C99 6.8.6.2: continue-statement
252     Res = ParseContinueStatement(attrs);
253     SemiError = "continue";
254     break;
255   case tok::kw_break:               // C99 6.8.6.3: break-statement
256     Res = ParseBreakStatement(attrs);
257     SemiError = "break";
258     break;
259   case tok::kw_return:              // C99 6.8.6.4: return-statement
260     Res = ParseReturnStatement(attrs);
261     SemiError = "return";
262     break;
263
264   case tok::kw_asm: {
265     ProhibitAttributes(attrs);
266     bool msAsm = false;
267     Res = ParseAsmStatement(msAsm);
268     Res = Actions.ActOnFinishFullStmt(Res.get());
269     if (msAsm) return move(Res);
270     SemiError = "asm";
271     break;
272   }
273
274   case tok::kw_try:                 // C++ 15: try-block
275     return ParseCXXTryBlock(attrs);
276
277   case tok::kw___try:
278     return ParseSEHTryBlock(attrs);
279   }
280
281   // If we reached this code, the statement must end in a semicolon.
282   if (Tok.is(tok::semi)) {
283     ConsumeToken();
284   } else if (!Res.isInvalid()) {
285     // If the result was valid, then we do want to diagnose this.  Use
286     // ExpectAndConsume to emit the diagnostic, even though we know it won't
287     // succeed.
288     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
289     // Skip until we see a } or ;, but don't eat it.
290     SkipUntil(tok::r_brace, true, true);
291   }
292
293   return move(Res);
294 }
295
296 /// \brief Parse an expression statement.
297 StmtResult Parser::ParseExprStatement(ParsedAttributes &Attrs) {
298   // If a case keyword is missing, this is where it should be inserted.
299   Token OldToken = Tok;
300   
301   // FIXME: Use the attributes
302   // expression[opt] ';'
303   ExprResult Expr(ParseExpression());
304   if (Expr.isInvalid()) {
305     // If the expression is invalid, skip ahead to the next semicolon or '}'.
306     // Not doing this opens us up to the possibility of infinite loops if
307     // ParseExpression does not consume any tokens.
308     SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
309     if (Tok.is(tok::semi))
310       ConsumeToken();
311     return StmtError();
312   }
313   
314   if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
315       Actions.CheckCaseExpression(Expr.get())) {
316     // If a constant expression is followed by a colon inside a switch block,
317     // suggest a missing case keyword.
318     Diag(OldToken, diag::err_expected_case_before_expression)
319       << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
320     
321     // Recover parsing as a case statement.
322     return ParseCaseStatement(Attrs, /*MissingCase=*/true, Expr);
323   }
324   
325   // Otherwise, eat the semicolon.
326   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
327   return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
328 }
329
330 StmtResult Parser::ParseSEHTryBlock(ParsedAttributes & Attrs) {
331   assert(Tok.is(tok::kw___try) && "Expected '__try'");
332   SourceLocation Loc = ConsumeToken();
333   return ParseSEHTryBlockCommon(Loc);
334 }
335
336 /// ParseSEHTryBlockCommon
337 ///
338 /// seh-try-block:
339 ///   '__try' compound-statement seh-handler
340 ///
341 /// seh-handler:
342 ///   seh-except-block
343 ///   seh-finally-block
344 ///
345 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
346   if(Tok.isNot(tok::l_brace))
347     return StmtError(Diag(Tok,diag::err_expected_lbrace));
348
349   ParsedAttributesWithRange attrs(AttrFactory);
350   StmtResult TryBlock(ParseCompoundStatement(attrs));
351   if(TryBlock.isInvalid())
352     return move(TryBlock);
353
354   StmtResult Handler;
355   if(Tok.is(tok::kw___except)) {
356     SourceLocation Loc = ConsumeToken();
357     Handler = ParseSEHExceptBlock(Loc);
358   } else if (Tok.is(tok::kw___finally)) {
359     SourceLocation Loc = ConsumeToken();
360     Handler = ParseSEHFinallyBlock(Loc);
361   } else {
362     return StmtError(Diag(Tok,diag::err_seh_expected_handler));
363   }
364
365   if(Handler.isInvalid())
366     return move(Handler);
367
368   return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
369                                   TryLoc,
370                                   TryBlock.take(),
371                                   Handler.take());
372 }
373
374 /// ParseSEHExceptBlock - Handle __except
375 ///
376 /// seh-except-block:
377 ///   '__except' '(' seh-filter-expression ')' compound-statement
378 ///
379 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
380   PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
381     raii2(Ident___exception_code, false),
382     raii3(Ident_GetExceptionCode, false);
383
384   if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
385     return StmtError();
386
387   ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
388
389   if (getLang().Borland) {
390     Ident__exception_info->setIsPoisoned(false);
391     Ident___exception_info->setIsPoisoned(false);
392     Ident_GetExceptionInfo->setIsPoisoned(false);
393   }
394   ExprResult FilterExpr(ParseExpression());
395
396   if (getLang().Borland) {
397     Ident__exception_info->setIsPoisoned(true);
398     Ident___exception_info->setIsPoisoned(true);
399     Ident_GetExceptionInfo->setIsPoisoned(true);
400   }
401
402   if(FilterExpr.isInvalid())
403     return StmtError();
404
405   if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
406     return StmtError();
407
408   ParsedAttributesWithRange attrs(AttrFactory);
409   StmtResult Block(ParseCompoundStatement(attrs));
410
411   if(Block.isInvalid())
412     return move(Block);
413
414   return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
415 }
416
417 /// ParseSEHFinallyBlock - Handle __finally
418 ///
419 /// seh-finally-block:
420 ///   '__finally' compound-statement
421 ///
422 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
423   PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
424     raii2(Ident___abnormal_termination, false),
425     raii3(Ident_AbnormalTermination, false);
426
427   ParsedAttributesWithRange attrs(AttrFactory);
428   StmtResult Block(ParseCompoundStatement(attrs));
429   if(Block.isInvalid())
430     return move(Block);
431
432   return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
433 }
434
435 /// ParseLabeledStatement - We have an identifier and a ':' after it.
436 ///
437 ///       labeled-statement:
438 ///         identifier ':' statement
439 /// [GNU]   identifier ':' attributes[opt] statement
440 ///
441 StmtResult Parser::ParseLabeledStatement(ParsedAttributes &attrs) {
442   assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
443          "Not an identifier!");
444
445   Token IdentTok = Tok;  // Save the whole token.
446   ConsumeToken();  // eat the identifier.
447
448   assert(Tok.is(tok::colon) && "Not a label!");
449
450   // identifier ':' statement
451   SourceLocation ColonLoc = ConsumeToken();
452
453   // Read label attributes, if present.
454   MaybeParseGNUAttributes(attrs);
455
456   StmtResult SubStmt(ParseStatement());
457
458   // Broken substmt shouldn't prevent the label from being added to the AST.
459   if (SubStmt.isInvalid())
460     SubStmt = Actions.ActOnNullStmt(ColonLoc);
461   
462   LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
463                                               IdentTok.getLocation());
464   if (AttributeList *Attrs = attrs.getList())
465     Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
466   
467   return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
468                                 SubStmt.get());
469 }
470
471 /// ParseCaseStatement
472 ///       labeled-statement:
473 ///         'case' constant-expression ':' statement
474 /// [GNU]   'case' constant-expression '...' constant-expression ':' statement
475 ///
476 StmtResult Parser::ParseCaseStatement(ParsedAttributes &attrs, bool MissingCase,
477                                       ExprResult Expr) {
478   assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
479   // FIXME: Use attributes?
480
481   // It is very very common for code to contain many case statements recursively
482   // nested, as in (but usually without indentation):
483   //  case 1:
484   //    case 2:
485   //      case 3:
486   //         case 4:
487   //           case 5: etc.
488   //
489   // Parsing this naively works, but is both inefficient and can cause us to run
490   // out of stack space in our recursive descent parser.  As a special case,
491   // flatten this recursion into an iterative loop.  This is complex and gross,
492   // but all the grossness is constrained to ParseCaseStatement (and some
493   // wierdness in the actions), so this is just local grossness :).
494
495   // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
496   // example above.
497   StmtResult TopLevelCase(true);
498
499   // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
500   // gets updated each time a new case is parsed, and whose body is unset so
501   // far.  When parsing 'case 4', this is the 'case 3' node.
502   StmtTy *DeepestParsedCaseStmt = 0;
503
504   // While we have case statements, eat and stack them.
505   SourceLocation ColonLoc;
506   do {
507     SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
508                                            ConsumeToken();  // eat the 'case'.
509
510     if (Tok.is(tok::code_completion)) {
511       Actions.CodeCompleteCase(getCurScope());
512       ConsumeCodeCompletionToken();
513     }
514     
515     /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
516     /// Disable this form of error recovery while we're parsing the case
517     /// expression.
518     ColonProtectionRAIIObject ColonProtection(*this);
519     
520     ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
521     MissingCase = false;
522     if (LHS.isInvalid()) {
523       SkipUntil(tok::colon);
524       return StmtError();
525     }
526
527     // GNU case range extension.
528     SourceLocation DotDotDotLoc;
529     ExprResult RHS;
530     if (Tok.is(tok::ellipsis)) {
531       Diag(Tok, diag::ext_gnu_case_range);
532       DotDotDotLoc = ConsumeToken();
533
534       RHS = ParseConstantExpression();
535       if (RHS.isInvalid()) {
536         SkipUntil(tok::colon);
537         return StmtError();
538       }
539     }
540     
541     ColonProtection.restore();
542
543     if (Tok.is(tok::colon)) {
544       ColonLoc = ConsumeToken();
545
546     // Treat "case blah;" as a typo for "case blah:".
547     } else if (Tok.is(tok::semi)) {
548       ColonLoc = ConsumeToken();
549       Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
550         << FixItHint::CreateReplacement(ColonLoc, ":");
551     } else {
552       SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
553       Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
554         << FixItHint::CreateInsertion(ExpectedLoc, ":");
555       ColonLoc = ExpectedLoc;
556     }
557     
558     StmtResult Case =
559       Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
560                             RHS.get(), ColonLoc);
561
562     // If we had a sema error parsing this case, then just ignore it and
563     // continue parsing the sub-stmt.
564     if (Case.isInvalid()) {
565       if (TopLevelCase.isInvalid())  // No parsed case stmts.
566         return ParseStatement();
567       // Otherwise, just don't add it as a nested case.
568     } else {
569       // If this is the first case statement we parsed, it becomes TopLevelCase.
570       // Otherwise we link it into the current chain.
571       Stmt *NextDeepest = Case.get();
572       if (TopLevelCase.isInvalid())
573         TopLevelCase = move(Case);
574       else
575         Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
576       DeepestParsedCaseStmt = NextDeepest;
577     }
578
579     // Handle all case statements.
580   } while (Tok.is(tok::kw_case));
581
582   assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
583
584   // If we found a non-case statement, start by parsing it.
585   StmtResult SubStmt;
586
587   if (Tok.isNot(tok::r_brace)) {
588     SubStmt = ParseStatement();
589   } else {
590     // Nicely diagnose the common error "switch (X) { case 4: }", which is
591     // not valid.
592     SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
593     Diag(AfterColonLoc, diag::err_label_end_of_compound_statement);
594     SubStmt = true;
595   }
596
597   // Broken sub-stmt shouldn't prevent forming the case statement properly.
598   if (SubStmt.isInvalid())
599     SubStmt = Actions.ActOnNullStmt(SourceLocation());
600
601   // Install the body into the most deeply-nested case.
602   Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
603
604   // Return the top level parsed statement tree.
605   return move(TopLevelCase);
606 }
607
608 /// ParseDefaultStatement
609 ///       labeled-statement:
610 ///         'default' ':' statement
611 /// Note that this does not parse the 'statement' at the end.
612 ///
613 StmtResult Parser::ParseDefaultStatement(ParsedAttributes &attrs) {
614   //FIXME: Use attributes?
615
616   assert(Tok.is(tok::kw_default) && "Not a default stmt!");
617   SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
618
619   SourceLocation ColonLoc;
620   if (Tok.is(tok::colon)) {
621     ColonLoc = ConsumeToken();
622
623   // Treat "default;" as a typo for "default:".
624   } else if (Tok.is(tok::semi)) {
625     ColonLoc = ConsumeToken();
626     Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
627       << FixItHint::CreateReplacement(ColonLoc, ":");
628   } else {
629     SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
630     Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
631       << FixItHint::CreateInsertion(ExpectedLoc, ":");
632     ColonLoc = ExpectedLoc;
633   }
634   
635   // Diagnose the common error "switch (X) {... default: }", which is not valid.
636   if (Tok.is(tok::r_brace)) {
637     SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
638     Diag(AfterColonLoc, diag::err_label_end_of_compound_statement);
639     return StmtError();
640   }
641
642   StmtResult SubStmt(ParseStatement());
643   if (SubStmt.isInvalid())
644     return StmtError();
645
646   return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
647                                   SubStmt.get(), getCurScope());
648 }
649
650 StmtResult Parser::ParseCompoundStatement(ParsedAttributes &Attr,
651                                           bool isStmtExpr) {
652   return ParseCompoundStatement(Attr, isStmtExpr, Scope::DeclScope);
653 }
654
655 /// ParseCompoundStatement - Parse a "{}" block.
656 ///
657 ///       compound-statement: [C99 6.8.2]
658 ///         { block-item-list[opt] }
659 /// [GNU]   { label-declarations block-item-list } [TODO]
660 ///
661 ///       block-item-list:
662 ///         block-item
663 ///         block-item-list block-item
664 ///
665 ///       block-item:
666 ///         declaration
667 /// [GNU]   '__extension__' declaration
668 ///         statement
669 /// [OMP]   openmp-directive            [TODO]
670 ///
671 /// [GNU] label-declarations:
672 /// [GNU]   label-declaration
673 /// [GNU]   label-declarations label-declaration
674 ///
675 /// [GNU] label-declaration:
676 /// [GNU]   '__label__' identifier-list ';'
677 ///
678 /// [OMP] openmp-directive:             [TODO]
679 /// [OMP]   barrier-directive
680 /// [OMP]   flush-directive
681 ///
682 StmtResult Parser::ParseCompoundStatement(ParsedAttributes &attrs,
683                                           bool isStmtExpr,
684                                           unsigned ScopeFlags) {
685   //FIXME: Use attributes?
686
687   assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
688
689   // Enter a scope to hold everything within the compound stmt.  Compound
690   // statements can always hold declarations.
691   ParseScope CompoundScope(this, ScopeFlags);
692
693   // Parse the statements in the body.
694   return ParseCompoundStatementBody(isStmtExpr);
695 }
696
697
698 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
699 /// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
700 /// consume the '}' at the end of the block.  It does not manipulate the scope
701 /// stack.
702 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
703   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
704                                 Tok.getLocation(),
705                                 "in compound statement ('{}')");
706   InMessageExpressionRAIIObject InMessage(*this, false);
707   
708   SourceLocation LBraceLoc = ConsumeBrace();  // eat the '{'.
709
710   StmtVector Stmts(Actions);
711
712   // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
713   // only allowed at the start of a compound stmt regardless of the language.
714   while (Tok.is(tok::kw___label__)) {
715     SourceLocation LabelLoc = ConsumeToken();
716     Diag(LabelLoc, diag::ext_gnu_local_label);
717     
718     llvm::SmallVector<Decl *, 8> DeclsInGroup;
719     while (1) {
720       if (Tok.isNot(tok::identifier)) {
721         Diag(Tok, diag::err_expected_ident);
722         break;
723       }
724       
725       IdentifierInfo *II = Tok.getIdentifierInfo();
726       SourceLocation IdLoc = ConsumeToken();
727       DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
728       
729       if (!Tok.is(tok::comma))
730         break;
731       ConsumeToken();
732     }
733     
734     DeclSpec DS(AttrFactory);
735     DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
736                                       DeclsInGroup.data(), DeclsInGroup.size());
737     StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
738     
739     ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
740     if (R.isUsable())
741       Stmts.push_back(R.release());
742   }
743   
744   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
745     if (Tok.is(tok::annot_pragma_unused)) {
746       HandlePragmaUnused();
747       continue;
748     }
749
750     if (getLang().Microsoft && (Tok.is(tok::kw___if_exists) ||
751         Tok.is(tok::kw___if_not_exists))) {
752       ParseMicrosoftIfExistsStatement(Stmts);
753       continue;
754     }
755
756     StmtResult R;
757     if (Tok.isNot(tok::kw___extension__)) {
758       R = ParseStatementOrDeclaration(Stmts, false);
759     } else {
760       // __extension__ can start declarations and it can also be a unary
761       // operator for expressions.  Consume multiple __extension__ markers here
762       // until we can determine which is which.
763       // FIXME: This loses extension expressions in the AST!
764       SourceLocation ExtLoc = ConsumeToken();
765       while (Tok.is(tok::kw___extension__))
766         ConsumeToken();
767
768       ParsedAttributesWithRange attrs(AttrFactory);
769       MaybeParseCXX0XAttributes(attrs);
770
771       // If this is the start of a declaration, parse it as such.
772       if (isDeclarationStatement()) {
773         // __extension__ silences extension warnings in the subdeclaration.
774         // FIXME: Save the __extension__ on the decl as a node somehow?
775         ExtensionRAIIObject O(Diags);
776
777         SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
778         DeclGroupPtrTy Res = ParseDeclaration(Stmts,
779                                               Declarator::BlockContext, DeclEnd,
780                                               attrs);
781         R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
782       } else {
783         // Otherwise this was a unary __extension__ marker.
784         ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
785
786         if (Res.isInvalid()) {
787           SkipUntil(tok::semi);
788           continue;
789         }
790
791         // FIXME: Use attributes?
792         // Eat the semicolon at the end of stmt and convert the expr into a
793         // statement.
794         ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
795         R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
796       }
797     }
798
799     if (R.isUsable())
800       Stmts.push_back(R.release());
801   }
802
803   // We broke out of the while loop because we found a '}' or EOF.
804   if (Tok.isNot(tok::r_brace)) {
805     Diag(Tok, diag::err_expected_rbrace);
806     Diag(LBraceLoc, diag::note_matching) << "{";
807     return StmtError();
808   }
809
810   SourceLocation RBraceLoc = ConsumeBrace();
811   return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
812                                    isStmtExpr);
813 }
814
815 /// ParseParenExprOrCondition:
816 /// [C  ]     '(' expression ')'
817 /// [C++]     '(' condition ')'       [not allowed if OnlyAllowCondition=true]
818 ///
819 /// This function parses and performs error recovery on the specified condition
820 /// or expression (depending on whether we're in C++ or C mode).  This function
821 /// goes out of its way to recover well.  It returns true if there was a parser
822 /// error (the right paren couldn't be found), which indicates that the caller
823 /// should try to recover harder.  It returns false if the condition is
824 /// successfully parsed.  Note that a successful parse can still have semantic
825 /// errors in the condition.
826 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
827                                        Decl *&DeclResult,
828                                        SourceLocation Loc,
829                                        bool ConvertToBoolean) {
830   SourceLocation LParenLoc = ConsumeParen();
831   if (getLang().CPlusPlus) 
832     ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
833   else {
834     ExprResult = ParseExpression();
835     DeclResult = 0;
836     
837     // If required, convert to a boolean value.
838     if (!ExprResult.isInvalid() && ConvertToBoolean)
839       ExprResult
840         = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
841   }
842
843   // If the parser was confused by the condition and we don't have a ')', try to
844   // recover by skipping ahead to a semi and bailing out.  If condexp is
845   // semantically invalid but we have well formed code, keep going.
846   if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
847     SkipUntil(tok::semi);
848     // Skipping may have stopped if it found the containing ')'.  If so, we can
849     // continue parsing the if statement.
850     if (Tok.isNot(tok::r_paren))
851       return true;
852   }
853
854   // Otherwise the condition is valid or the rparen is present.
855   MatchRHSPunctuation(tok::r_paren, LParenLoc);
856   return false;
857 }
858
859
860 /// ParseIfStatement
861 ///       if-statement: [C99 6.8.4.1]
862 ///         'if' '(' expression ')' statement
863 ///         'if' '(' expression ')' statement 'else' statement
864 /// [C++]   'if' '(' condition ')' statement
865 /// [C++]   'if' '(' condition ')' statement 'else' statement
866 ///
867 StmtResult Parser::ParseIfStatement(ParsedAttributes &attrs) {
868   // FIXME: Use attributes?
869
870   assert(Tok.is(tok::kw_if) && "Not an if stmt!");
871   SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
872
873   if (Tok.isNot(tok::l_paren)) {
874     Diag(Tok, diag::err_expected_lparen_after) << "if";
875     SkipUntil(tok::semi);
876     return StmtError();
877   }
878
879   bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
880
881   // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
882   // the case for C90.
883   //
884   // C++ 6.4p3:
885   // A name introduced by a declaration in a condition is in scope from its
886   // point of declaration until the end of the substatements controlled by the
887   // condition.
888   // C++ 3.3.2p4:
889   // Names declared in the for-init-statement, and in the condition of if,
890   // while, for, and switch statements are local to the if, while, for, or
891   // switch statement (including the controlled statement).
892   //
893   ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
894
895   // Parse the condition.
896   ExprResult CondExp;
897   Decl *CondVar = 0;
898   if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
899     return StmtError();
900
901   FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
902
903   // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
904   // there is no compound stmt.  C90 does not have this clause.  We only do this
905   // if the body isn't a compound statement to avoid push/pop in common cases.
906   //
907   // C++ 6.4p1:
908   // The substatement in a selection-statement (each substatement, in the else
909   // form of the if statement) implicitly defines a local scope.
910   //
911   // For C++ we create a scope for the condition and a new scope for
912   // substatements because:
913   // -When the 'then' scope exits, we want the condition declaration to still be
914   //    active for the 'else' scope too.
915   // -Sema will detect name clashes by considering declarations of a
916   //    'ControlScope' as part of its direct subscope.
917   // -If we wanted the condition and substatement to be in the same scope, we
918   //    would have to notify ParseStatement not to create a new scope. It's
919   //    simpler to let it create a new scope.
920   //
921   ParseScope InnerScope(this, Scope::DeclScope,
922                         C99orCXX && Tok.isNot(tok::l_brace));
923
924   // Read the 'then' stmt.
925   SourceLocation ThenStmtLoc = Tok.getLocation();
926   StmtResult ThenStmt(ParseStatement());
927
928   // Pop the 'if' scope if needed.
929   InnerScope.Exit();
930
931   // If it has an else, parse it.
932   SourceLocation ElseLoc;
933   SourceLocation ElseStmtLoc;
934   StmtResult ElseStmt;
935
936   if (Tok.is(tok::kw_else)) {
937     ElseLoc = ConsumeToken();
938     ElseStmtLoc = Tok.getLocation();
939
940     // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
941     // there is no compound stmt.  C90 does not have this clause.  We only do
942     // this if the body isn't a compound statement to avoid push/pop in common
943     // cases.
944     //
945     // C++ 6.4p1:
946     // The substatement in a selection-statement (each substatement, in the else
947     // form of the if statement) implicitly defines a local scope.
948     //
949     ParseScope InnerScope(this, Scope::DeclScope,
950                           C99orCXX && Tok.isNot(tok::l_brace));
951
952     ElseStmt = ParseStatement();
953     
954     // Pop the 'else' scope if needed.
955     InnerScope.Exit();
956   }
957
958   IfScope.Exit();
959
960   // If the condition was invalid, discard the if statement.  We could recover
961   // better by replacing it with a valid expr, but don't do that yet.
962   if (CondExp.isInvalid() && !CondVar)
963     return StmtError();
964
965   // If the then or else stmt is invalid and the other is valid (and present),
966   // make turn the invalid one into a null stmt to avoid dropping the other
967   // part.  If both are invalid, return error.
968   if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
969       (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
970       (ThenStmt.get() == 0  && ElseStmt.isInvalid())) {
971     // Both invalid, or one is invalid and other is non-present: return error.
972     return StmtError();
973   }
974
975   // Now if either are invalid, replace with a ';'.
976   if (ThenStmt.isInvalid())
977     ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
978   if (ElseStmt.isInvalid())
979     ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
980
981   return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
982                              ElseLoc, ElseStmt.get());
983 }
984
985 /// ParseSwitchStatement
986 ///       switch-statement:
987 ///         'switch' '(' expression ')' statement
988 /// [C++]   'switch' '(' condition ')' statement
989 StmtResult Parser::ParseSwitchStatement(ParsedAttributes &attrs) {
990   // FIXME: Use attributes?
991
992   assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
993   SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
994
995   if (Tok.isNot(tok::l_paren)) {
996     Diag(Tok, diag::err_expected_lparen_after) << "switch";
997     SkipUntil(tok::semi);
998     return StmtError();
999   }
1000
1001   bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
1002
1003   // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
1004   // not the case for C90.  Start the switch scope.
1005   //
1006   // C++ 6.4p3:
1007   // A name introduced by a declaration in a condition is in scope from its
1008   // point of declaration until the end of the substatements controlled by the
1009   // condition.
1010   // C++ 3.3.2p4:
1011   // Names declared in the for-init-statement, and in the condition of if,
1012   // while, for, and switch statements are local to the if, while, for, or
1013   // switch statement (including the controlled statement).
1014   //
1015   unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
1016   if (C99orCXX)
1017     ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1018   ParseScope SwitchScope(this, ScopeFlags);
1019
1020   // Parse the condition.
1021   ExprResult Cond;
1022   Decl *CondVar = 0;
1023   if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1024     return StmtError();
1025
1026   StmtResult Switch
1027     = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1028
1029   if (Switch.isInvalid()) {
1030     // Skip the switch body. 
1031     // FIXME: This is not optimal recovery, but parsing the body is more
1032     // dangerous due to the presence of case and default statements, which
1033     // will have no place to connect back with the switch.
1034     if (Tok.is(tok::l_brace)) {
1035       ConsumeBrace();
1036       SkipUntil(tok::r_brace, false, false);
1037     } else
1038       SkipUntil(tok::semi);
1039     return move(Switch);
1040   }
1041   
1042   // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1043   // there is no compound stmt.  C90 does not have this clause.  We only do this
1044   // if the body isn't a compound statement to avoid push/pop in common cases.
1045   //
1046   // C++ 6.4p1:
1047   // The substatement in a selection-statement (each substatement, in the else
1048   // form of the if statement) implicitly defines a local scope.
1049   //
1050   // See comments in ParseIfStatement for why we create a scope for the
1051   // condition and a new scope for substatement in C++.
1052   //
1053   ParseScope InnerScope(this, Scope::DeclScope,
1054                         C99orCXX && Tok.isNot(tok::l_brace));
1055
1056   // Read the body statement.
1057   StmtResult Body(ParseStatement());
1058
1059   // Pop the scopes.
1060   InnerScope.Exit();
1061   SwitchScope.Exit();
1062
1063   if (Body.isInvalid())
1064     // FIXME: Remove the case statement list from the Switch statement.
1065     Body = Actions.ActOnNullStmt(Tok.getLocation());
1066   
1067   return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1068 }
1069
1070 /// ParseWhileStatement
1071 ///       while-statement: [C99 6.8.5.1]
1072 ///         'while' '(' expression ')' statement
1073 /// [C++]   'while' '(' condition ')' statement
1074 StmtResult Parser::ParseWhileStatement(ParsedAttributes &attrs) {
1075   // FIXME: Use attributes?
1076
1077   assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1078   SourceLocation WhileLoc = Tok.getLocation();
1079   ConsumeToken();  // eat the 'while'.
1080
1081   if (Tok.isNot(tok::l_paren)) {
1082     Diag(Tok, diag::err_expected_lparen_after) << "while";
1083     SkipUntil(tok::semi);
1084     return StmtError();
1085   }
1086
1087   bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
1088
1089   // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
1090   // the case for C90.  Start the loop scope.
1091   //
1092   // C++ 6.4p3:
1093   // A name introduced by a declaration in a condition is in scope from its
1094   // point of declaration until the end of the substatements controlled by the
1095   // condition.
1096   // C++ 3.3.2p4:
1097   // Names declared in the for-init-statement, and in the condition of if,
1098   // while, for, and switch statements are local to the if, while, for, or
1099   // switch statement (including the controlled statement).
1100   //
1101   unsigned ScopeFlags;
1102   if (C99orCXX)
1103     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1104                  Scope::DeclScope  | Scope::ControlScope;
1105   else
1106     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1107   ParseScope WhileScope(this, ScopeFlags);
1108
1109   // Parse the condition.
1110   ExprResult Cond;
1111   Decl *CondVar = 0;
1112   if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1113     return StmtError();
1114
1115   FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
1116
1117   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1118   // there is no compound stmt.  C90 does not have this clause.  We only do this
1119   // if the body isn't a compound statement to avoid push/pop in common cases.
1120   //
1121   // C++ 6.5p2:
1122   // The substatement in an iteration-statement implicitly defines a local scope
1123   // which is entered and exited each time through the loop.
1124   //
1125   // See comments in ParseIfStatement for why we create a scope for the
1126   // condition and a new scope for substatement in C++.
1127   //
1128   ParseScope InnerScope(this, Scope::DeclScope,
1129                         C99orCXX && Tok.isNot(tok::l_brace));
1130
1131   // Read the body statement.
1132   StmtResult Body(ParseStatement());
1133
1134   // Pop the body scope if needed.
1135   InnerScope.Exit();
1136   WhileScope.Exit();
1137
1138   if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1139     return StmtError();
1140
1141   return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1142 }
1143
1144 /// ParseDoStatement
1145 ///       do-statement: [C99 6.8.5.2]
1146 ///         'do' statement 'while' '(' expression ')' ';'
1147 /// Note: this lets the caller parse the end ';'.
1148 StmtResult Parser::ParseDoStatement(ParsedAttributes &attrs) {
1149   // FIXME: Use attributes?
1150
1151   assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1152   SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
1153
1154   // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
1155   // the case for C90.  Start the loop scope.
1156   unsigned ScopeFlags;
1157   if (getLang().C99)
1158     ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1159   else
1160     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1161
1162   ParseScope DoScope(this, ScopeFlags);
1163
1164   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1165   // there is no compound stmt.  C90 does not have this clause. We only do this
1166   // if the body isn't a compound statement to avoid push/pop in common cases.
1167   //
1168   // C++ 6.5p2:
1169   // The substatement in an iteration-statement implicitly defines a local scope
1170   // which is entered and exited each time through the loop.
1171   //
1172   ParseScope InnerScope(this, Scope::DeclScope,
1173                         (getLang().C99 || getLang().CPlusPlus) &&
1174                         Tok.isNot(tok::l_brace));
1175
1176   // Read the body statement.
1177   StmtResult Body(ParseStatement());
1178
1179   // Pop the body scope if needed.
1180   InnerScope.Exit();
1181
1182   if (Tok.isNot(tok::kw_while)) {
1183     if (!Body.isInvalid()) {
1184       Diag(Tok, diag::err_expected_while);
1185       Diag(DoLoc, diag::note_matching) << "do";
1186       SkipUntil(tok::semi, false, true);
1187     }
1188     return StmtError();
1189   }
1190   SourceLocation WhileLoc = ConsumeToken();
1191
1192   if (Tok.isNot(tok::l_paren)) {
1193     Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1194     SkipUntil(tok::semi, false, true);
1195     return StmtError();
1196   }
1197
1198   // Parse the parenthesized condition.
1199   SourceLocation LPLoc = ConsumeParen();
1200   ExprResult Cond = ParseExpression();
1201   SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
1202   DoScope.Exit();
1203
1204   if (Cond.isInvalid() || Body.isInvalid())
1205     return StmtError();
1206
1207   return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, LPLoc,
1208                              Cond.get(), RPLoc);
1209 }
1210
1211 /// ParseForStatement
1212 ///       for-statement: [C99 6.8.5.3]
1213 ///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1214 ///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1215 /// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1216 /// [C++]       statement
1217 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
1218 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1219 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1220 ///
1221 /// [C++] for-init-statement:
1222 /// [C++]   expression-statement
1223 /// [C++]   simple-declaration
1224 ///
1225 /// [C++0x] for-range-declaration:
1226 /// [C++0x]   attribute-specifier-seq[opt] type-specifier-seq declarator
1227 /// [C++0x] for-range-initializer:
1228 /// [C++0x]   expression
1229 /// [C++0x]   braced-init-list            [TODO]
1230 StmtResult Parser::ParseForStatement(ParsedAttributes &attrs) {
1231   // FIXME: Use attributes?
1232
1233   assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1234   SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
1235
1236   if (Tok.isNot(tok::l_paren)) {
1237     Diag(Tok, diag::err_expected_lparen_after) << "for";
1238     SkipUntil(tok::semi);
1239     return StmtError();
1240   }
1241
1242   bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
1243
1244   // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
1245   // the case for C90.  Start the loop scope.
1246   //
1247   // C++ 6.4p3:
1248   // A name introduced by a declaration in a condition is in scope from its
1249   // point of declaration until the end of the substatements controlled by the
1250   // condition.
1251   // C++ 3.3.2p4:
1252   // Names declared in the for-init-statement, and in the condition of if,
1253   // while, for, and switch statements are local to the if, while, for, or
1254   // switch statement (including the controlled statement).
1255   // C++ 6.5.3p1:
1256   // Names declared in the for-init-statement are in the same declarative-region
1257   // as those declared in the condition.
1258   //
1259   unsigned ScopeFlags;
1260   if (C99orCXXorObjC)
1261     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1262                  Scope::DeclScope  | Scope::ControlScope;
1263   else
1264     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1265
1266   ParseScope ForScope(this, ScopeFlags);
1267
1268   SourceLocation LParenLoc = ConsumeParen();
1269   ExprResult Value;
1270
1271   bool ForEach = false, ForRange = false;
1272   StmtResult FirstPart;
1273   bool SecondPartIsInvalid = false;
1274   FullExprArg SecondPart(Actions);
1275   ExprResult Collection;
1276   ForRangeInit ForRangeInit;
1277   FullExprArg ThirdPart(Actions);
1278   Decl *SecondVar = 0;
1279   
1280   if (Tok.is(tok::code_completion)) {
1281     Actions.CodeCompleteOrdinaryName(getCurScope(), 
1282                                      C99orCXXorObjC? Sema::PCC_ForInit
1283                                                    : Sema::PCC_Expression);
1284     ConsumeCodeCompletionToken();
1285   }
1286   
1287   // Parse the first part of the for specifier.
1288   if (Tok.is(tok::semi)) {  // for (;
1289     // no first part, eat the ';'.
1290     ConsumeToken();
1291   } else if (isSimpleDeclaration()) {  // for (int X = 4;
1292     // Parse declaration, which eats the ';'.
1293     if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
1294       Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1295
1296     ParsedAttributesWithRange attrs(AttrFactory);
1297     MaybeParseCXX0XAttributes(attrs);
1298
1299     // In C++0x, "for (T NS:a" might not be a typo for ::
1300     bool MightBeForRangeStmt = getLang().CPlusPlus;
1301     ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1302
1303     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1304     StmtVector Stmts(Actions);
1305     DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext, 
1306                                                DeclEnd, attrs, false,
1307                                                MightBeForRangeStmt ?
1308                                                  &ForRangeInit : 0);
1309     FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1310
1311     if (ForRangeInit.ParsedForRangeDecl()) {
1312       ForRange = true;
1313     } else if (Tok.is(tok::semi)) {  // for (int x = 4;
1314       ConsumeToken();
1315     } else if ((ForEach = isTokIdentifier_in())) {
1316       Actions.ActOnForEachDeclStmt(DG);
1317       // ObjC: for (id x in expr)
1318       ConsumeToken(); // consume 'in'
1319       
1320       if (Tok.is(tok::code_completion)) {
1321         Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1322         ConsumeCodeCompletionToken();
1323       }
1324       Collection = ParseExpression();
1325     } else {
1326       Diag(Tok, diag::err_expected_semi_for);
1327     }
1328   } else {
1329     Value = ParseExpression();
1330
1331     ForEach = isTokIdentifier_in();
1332
1333     // Turn the expression into a stmt.
1334     if (!Value.isInvalid()) {
1335       if (ForEach)
1336         FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1337       else
1338         FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1339     }
1340
1341     if (Tok.is(tok::semi)) {
1342       ConsumeToken();
1343     } else if (ForEach) {
1344       ConsumeToken(); // consume 'in'
1345       
1346       if (Tok.is(tok::code_completion)) {
1347         Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1348         ConsumeCodeCompletionToken();
1349       }
1350       Collection = ParseExpression();
1351     } else {
1352       if (!Value.isInvalid()) {
1353         Diag(Tok, diag::err_expected_semi_for);
1354       } else {
1355         // Skip until semicolon or rparen, don't consume it.
1356         SkipUntil(tok::r_paren, true, true);
1357         if (Tok.is(tok::semi))
1358           ConsumeToken();
1359       }
1360     }
1361   }
1362   if (!ForEach && !ForRange) {
1363     assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1364     // Parse the second part of the for specifier.
1365     if (Tok.is(tok::semi)) {  // for (...;;
1366       // no second part.
1367     } else if (Tok.is(tok::r_paren)) {
1368       // missing both semicolons.
1369     } else {
1370       ExprResult Second;
1371       if (getLang().CPlusPlus)
1372         ParseCXXCondition(Second, SecondVar, ForLoc, true);
1373       else {
1374         Second = ParseExpression();
1375         if (!Second.isInvalid())
1376           Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc, 
1377                                                  Second.get());
1378       }
1379       SecondPartIsInvalid = Second.isInvalid();
1380       SecondPart = Actions.MakeFullExpr(Second.get());
1381     }
1382
1383     if (Tok.isNot(tok::semi)) {
1384       if (!SecondPartIsInvalid || SecondVar)
1385         Diag(Tok, diag::err_expected_semi_for);
1386       else
1387         // Skip until semicolon or rparen, don't consume it.
1388         SkipUntil(tok::r_paren, true, true);
1389     }
1390
1391     if (Tok.is(tok::semi)) {
1392       ConsumeToken();
1393     }
1394
1395     // Parse the third part of the for specifier.
1396     if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
1397       ExprResult Third = ParseExpression();
1398       ThirdPart = Actions.MakeFullExpr(Third.take());
1399     }
1400   }
1401   // Match the ')'.
1402   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1403
1404   // We need to perform most of the semantic analysis for a C++0x for-range
1405   // statememt before parsing the body, in order to be able to deduce the type
1406   // of an auto-typed loop variable.
1407   StmtResult ForRangeStmt;
1408   if (ForRange)
1409     ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, LParenLoc,
1410                                                 FirstPart.take(),
1411                                                 ForRangeInit.ColonLoc,
1412                                                 ForRangeInit.RangeExpr.get(),
1413                                                 RParenLoc);
1414
1415   // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1416   // there is no compound stmt.  C90 does not have this clause.  We only do this
1417   // if the body isn't a compound statement to avoid push/pop in common cases.
1418   //
1419   // C++ 6.5p2:
1420   // The substatement in an iteration-statement implicitly defines a local scope
1421   // which is entered and exited each time through the loop.
1422   //
1423   // See comments in ParseIfStatement for why we create a scope for
1424   // for-init-statement/condition and a new scope for substatement in C++.
1425   //
1426   ParseScope InnerScope(this, Scope::DeclScope,
1427                         C99orCXXorObjC && Tok.isNot(tok::l_brace));
1428
1429   // Read the body statement.
1430   StmtResult Body(ParseStatement());
1431
1432   // Pop the body scope if needed.
1433   InnerScope.Exit();
1434
1435   // Leave the for-scope.
1436   ForScope.Exit();
1437
1438   if (Body.isInvalid())
1439     return StmtError();
1440
1441   if (ForEach)
1442     // FIXME: It isn't clear how to communicate the late destruction of 
1443     // C++ temporaries used to create the collection.
1444     return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc,
1445                                               FirstPart.take(),
1446                                               Collection.take(), RParenLoc, 
1447                                               Body.take());
1448
1449   if (ForRange)
1450     return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1451
1452   return Actions.ActOnForStmt(ForLoc, LParenLoc, FirstPart.take(), SecondPart,
1453                               SecondVar, ThirdPart, RParenLoc, Body.take());
1454 }
1455
1456 /// ParseGotoStatement
1457 ///       jump-statement:
1458 ///         'goto' identifier ';'
1459 /// [GNU]   'goto' '*' expression ';'
1460 ///
1461 /// Note: this lets the caller parse the end ';'.
1462 ///
1463 StmtResult Parser::ParseGotoStatement(ParsedAttributes &attrs) {
1464   // FIXME: Use attributes?
1465
1466   assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1467   SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
1468
1469   StmtResult Res;
1470   if (Tok.is(tok::identifier)) {
1471     LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1472                                                 Tok.getLocation());
1473     Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1474     ConsumeToken();
1475   } else if (Tok.is(tok::star)) {
1476     // GNU indirect goto extension.
1477     Diag(Tok, diag::ext_gnu_indirect_goto);
1478     SourceLocation StarLoc = ConsumeToken();
1479     ExprResult R(ParseExpression());
1480     if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1481       SkipUntil(tok::semi, false, true);
1482       return StmtError();
1483     }
1484     Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1485   } else {
1486     Diag(Tok, diag::err_expected_ident);
1487     return StmtError();
1488   }
1489
1490   return move(Res);
1491 }
1492
1493 /// ParseContinueStatement
1494 ///       jump-statement:
1495 ///         'continue' ';'
1496 ///
1497 /// Note: this lets the caller parse the end ';'.
1498 ///
1499 StmtResult Parser::ParseContinueStatement(ParsedAttributes &attrs) {
1500   // FIXME: Use attributes?
1501
1502   SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
1503   return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1504 }
1505
1506 /// ParseBreakStatement
1507 ///       jump-statement:
1508 ///         'break' ';'
1509 ///
1510 /// Note: this lets the caller parse the end ';'.
1511 ///
1512 StmtResult Parser::ParseBreakStatement(ParsedAttributes &attrs) {
1513   // FIXME: Use attributes?
1514
1515   SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
1516   return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1517 }
1518
1519 /// ParseReturnStatement
1520 ///       jump-statement:
1521 ///         'return' expression[opt] ';'
1522 StmtResult Parser::ParseReturnStatement(ParsedAttributes &attrs) {
1523   // FIXME: Use attributes?
1524
1525   assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1526   SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
1527
1528   ExprResult R;
1529   if (Tok.isNot(tok::semi)) {
1530     if (Tok.is(tok::code_completion)) {
1531       Actions.CodeCompleteReturn(getCurScope());
1532       ConsumeCodeCompletionToken();
1533       SkipUntil(tok::semi, false, true);
1534       return StmtError();
1535     }
1536         
1537     // FIXME: This is a hack to allow something like C++0x's generalized
1538     // initializer lists, but only enough of this feature to allow Clang to
1539     // parse libstdc++ 4.5's headers.
1540     if (Tok.is(tok::l_brace) && getLang().CPlusPlus) {
1541       R = ParseInitializer();
1542       if (R.isUsable() && !getLang().CPlusPlus0x)
1543         Diag(R.get()->getLocStart(), diag::ext_generalized_initializer_lists)
1544           << R.get()->getSourceRange();
1545     } else
1546         R = ParseExpression();
1547     if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
1548       SkipUntil(tok::semi, false, true);
1549       return StmtError();
1550     }
1551   }
1552   return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1553 }
1554
1555 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1556 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1557 StmtResult Parser::FuzzyParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
1558   SourceLocation EndLoc;
1559   if (Tok.is(tok::l_brace)) {
1560     unsigned short savedBraceCount = BraceCount;
1561     do {
1562       EndLoc = Tok.getLocation();
1563       ConsumeAnyToken();
1564     } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1565   } else {
1566     // From the MS website: If used without braces, the __asm keyword means
1567     // that the rest of the line is an assembly-language statement.
1568     SourceManager &SrcMgr = PP.getSourceManager();
1569     SourceLocation TokLoc = Tok.getLocation();
1570     unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1571     do {
1572       EndLoc = TokLoc;
1573       ConsumeAnyToken();
1574       TokLoc = Tok.getLocation();
1575     } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1576              Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1577              Tok.isNot(tok::eof));
1578   }
1579   Token t;
1580   t.setKind(tok::string_literal);
1581   t.setLiteralData("\"/*FIXME: not done*/\"");
1582   t.clearFlag(Token::NeedsCleaning);
1583   t.setLength(21);
1584   ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1585   ExprVector Constraints(Actions);
1586   ExprVector Exprs(Actions);
1587   ExprVector Clobbers(Actions);
1588   return Actions.ActOnAsmStmt(AsmLoc, true, true, 0, 0, 0,
1589                               move_arg(Constraints), move_arg(Exprs),
1590                               AsmString.take(), move_arg(Clobbers),
1591                               EndLoc, true);
1592 }
1593
1594 /// ParseAsmStatement - Parse a GNU extended asm statement.
1595 ///       asm-statement:
1596 ///         gnu-asm-statement
1597 ///         ms-asm-statement
1598 ///
1599 /// [GNU] gnu-asm-statement:
1600 ///         'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1601 ///
1602 /// [GNU] asm-argument:
1603 ///         asm-string-literal
1604 ///         asm-string-literal ':' asm-operands[opt]
1605 ///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1606 ///         asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1607 ///                 ':' asm-clobbers
1608 ///
1609 /// [GNU] asm-clobbers:
1610 ///         asm-string-literal
1611 ///         asm-clobbers ',' asm-string-literal
1612 ///
1613 /// [MS]  ms-asm-statement:
1614 ///         '__asm' assembly-instruction ';'[opt]
1615 ///         '__asm' '{' assembly-instruction-list '}' ';'[opt]
1616 ///
1617 /// [MS]  assembly-instruction-list:
1618 ///         assembly-instruction ';'[opt]
1619 ///         assembly-instruction-list ';' assembly-instruction ';'[opt]
1620 ///
1621 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
1622   assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1623   SourceLocation AsmLoc = ConsumeToken();
1624
1625   if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1626     msAsm = true;
1627     return FuzzyParseMicrosoftAsmStatement(AsmLoc);
1628   }
1629   DeclSpec DS(AttrFactory);
1630   SourceLocation Loc = Tok.getLocation();
1631   ParseTypeQualifierListOpt(DS, true, false);
1632
1633   // GNU asms accept, but warn, about type-qualifiers other than volatile.
1634   if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1635     Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1636   if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1637     Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1638
1639   // Remember if this was a volatile asm.
1640   bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1641   if (Tok.isNot(tok::l_paren)) {
1642     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1643     SkipUntil(tok::r_paren);
1644     return StmtError();
1645   }
1646   Loc = ConsumeParen();
1647
1648   ExprResult AsmString(ParseAsmStringLiteral());
1649   if (AsmString.isInvalid())
1650     return StmtError();
1651
1652   llvm::SmallVector<IdentifierInfo *, 4> Names;
1653   ExprVector Constraints(Actions);
1654   ExprVector Exprs(Actions);
1655   ExprVector Clobbers(Actions);
1656
1657   if (Tok.is(tok::r_paren)) {
1658     // We have a simple asm expression like 'asm("foo")'.
1659     SourceLocation RParenLoc = ConsumeParen();
1660     return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1661                                 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0, 
1662                                 move_arg(Constraints), move_arg(Exprs),
1663                                 AsmString.take(), move_arg(Clobbers),
1664                                 RParenLoc);
1665   }
1666
1667   // Parse Outputs, if present.
1668   bool AteExtraColon = false;
1669   if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1670     // In C++ mode, parse "::" like ": :".
1671     AteExtraColon = Tok.is(tok::coloncolon);
1672     ConsumeToken();
1673   
1674     if (!AteExtraColon &&
1675         ParseAsmOperandsOpt(Names, Constraints, Exprs))
1676       return StmtError();
1677   }
1678   
1679   unsigned NumOutputs = Names.size();
1680
1681   // Parse Inputs, if present.
1682   if (AteExtraColon ||
1683       Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1684     // In C++ mode, parse "::" like ": :".
1685     if (AteExtraColon)
1686       AteExtraColon = false;
1687     else {
1688       AteExtraColon = Tok.is(tok::coloncolon);
1689       ConsumeToken();
1690     }
1691     
1692     if (!AteExtraColon &&
1693         ParseAsmOperandsOpt(Names, Constraints, Exprs))
1694       return StmtError();
1695   }
1696
1697   assert(Names.size() == Constraints.size() &&
1698          Constraints.size() == Exprs.size() &&
1699          "Input operand size mismatch!");
1700
1701   unsigned NumInputs = Names.size() - NumOutputs;
1702
1703   // Parse the clobbers, if present.
1704   if (AteExtraColon || Tok.is(tok::colon)) {
1705     if (!AteExtraColon)
1706       ConsumeToken();
1707
1708     // Parse the asm-string list for clobbers if present.
1709     if (Tok.isNot(tok::r_paren)) {
1710       while (1) {
1711         ExprResult Clobber(ParseAsmStringLiteral());
1712
1713         if (Clobber.isInvalid())
1714           break;
1715
1716         Clobbers.push_back(Clobber.release());
1717
1718         if (Tok.isNot(tok::comma)) break;
1719         ConsumeToken();
1720       }
1721     }
1722   }
1723
1724   SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1725   return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1726                               NumOutputs, NumInputs, Names.data(),
1727                               move_arg(Constraints), move_arg(Exprs),
1728                               AsmString.take(), move_arg(Clobbers),
1729                               RParenLoc);
1730 }
1731
1732 /// ParseAsmOperands - Parse the asm-operands production as used by
1733 /// asm-statement, assuming the leading ':' token was eaten.
1734 ///
1735 /// [GNU] asm-operands:
1736 ///         asm-operand
1737 ///         asm-operands ',' asm-operand
1738 ///
1739 /// [GNU] asm-operand:
1740 ///         asm-string-literal '(' expression ')'
1741 ///         '[' identifier ']' asm-string-literal '(' expression ')'
1742 ///
1743 //
1744 // FIXME: Avoid unnecessary std::string trashing.
1745 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1746                                  llvm::SmallVectorImpl<ExprTy *> &Constraints,
1747                                  llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1748   // 'asm-operands' isn't present?
1749   if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1750     return false;
1751
1752   while (1) {
1753     // Read the [id] if present.
1754     if (Tok.is(tok::l_square)) {
1755       SourceLocation Loc = ConsumeBracket();
1756
1757       if (Tok.isNot(tok::identifier)) {
1758         Diag(Tok, diag::err_expected_ident);
1759         SkipUntil(tok::r_paren);
1760         return true;
1761       }
1762
1763       IdentifierInfo *II = Tok.getIdentifierInfo();
1764       ConsumeToken();
1765
1766       Names.push_back(II);
1767       MatchRHSPunctuation(tok::r_square, Loc);
1768     } else
1769       Names.push_back(0);
1770
1771     ExprResult Constraint(ParseAsmStringLiteral());
1772     if (Constraint.isInvalid()) {
1773         SkipUntil(tok::r_paren);
1774         return true;
1775     }
1776     Constraints.push_back(Constraint.release());
1777
1778     if (Tok.isNot(tok::l_paren)) {
1779       Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1780       SkipUntil(tok::r_paren);
1781       return true;
1782     }
1783
1784     // Read the parenthesized expression.
1785     SourceLocation OpenLoc = ConsumeParen();
1786     ExprResult Res(ParseExpression());
1787     MatchRHSPunctuation(tok::r_paren, OpenLoc);
1788     if (Res.isInvalid()) {
1789       SkipUntil(tok::r_paren);
1790       return true;
1791     }
1792     Exprs.push_back(Res.release());
1793     // Eat the comma and continue parsing if it exists.
1794     if (Tok.isNot(tok::comma)) return false;
1795     ConsumeToken();
1796   }
1797
1798   return true;
1799 }
1800
1801 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1802   assert(Tok.is(tok::l_brace));
1803   SourceLocation LBraceLoc = Tok.getLocation();
1804
1805   if (PP.isCodeCompletionEnabled()) {
1806     if (trySkippingFunctionBodyForCodeCompletion()) {
1807       BodyScope.Exit();
1808       return Actions.ActOnFinishFunctionBody(Decl, 0);
1809     }
1810   }
1811   
1812   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1813                                       "parsing function body");
1814
1815   // Do not enter a scope for the brace, as the arguments are in the same scope
1816   // (the function body) as the body itself.  Instead, just read the statement
1817   // list and put it into a CompoundStmt for safe keeping.
1818   StmtResult FnBody(ParseCompoundStatementBody());
1819
1820   // If the function body could not be parsed, make a bogus compoundstmt.
1821   if (FnBody.isInvalid())
1822     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1823                                        MultiStmtArg(Actions), false);
1824
1825   BodyScope.Exit();
1826   return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1827 }
1828
1829 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1830 ///
1831 ///       function-try-block:
1832 ///         'try' ctor-initializer[opt] compound-statement handler-seq
1833 ///
1834 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1835   assert(Tok.is(tok::kw_try) && "Expected 'try'");
1836   SourceLocation TryLoc = ConsumeToken();
1837
1838   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1839                                       "parsing function try block");
1840
1841   // Constructor initializer list?
1842   if (Tok.is(tok::colon))
1843     ParseConstructorInitializer(Decl);
1844
1845   if (PP.isCodeCompletionEnabled()) {
1846     if (trySkippingFunctionBodyForCodeCompletion()) {
1847       BodyScope.Exit();
1848       return Actions.ActOnFinishFunctionBody(Decl, 0);
1849     }
1850   }
1851
1852   SourceLocation LBraceLoc = Tok.getLocation();
1853   StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1854   // If we failed to parse the try-catch, we just give the function an empty
1855   // compound statement as the body.
1856   if (FnBody.isInvalid())
1857     FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1858                                        MultiStmtArg(Actions), false);
1859
1860   BodyScope.Exit();
1861   return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1862 }
1863
1864 bool Parser::trySkippingFunctionBodyForCodeCompletion() {
1865   assert(Tok.is(tok::l_brace));
1866   assert(PP.isCodeCompletionEnabled() &&
1867          "Should only be called when in code-completion mode");
1868
1869   // We're in code-completion mode. Skip parsing for all function bodies unless
1870   // the body contains the code-completion point.
1871   TentativeParsingAction PA(*this);
1872   ConsumeBrace();
1873   if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
1874                 /*StopAtCodeCompletion=*/true)) {
1875     PA.Commit();
1876     return true;
1877   }
1878
1879   PA.Revert();
1880   return false;
1881 }
1882
1883 /// ParseCXXTryBlock - Parse a C++ try-block.
1884 ///
1885 ///       try-block:
1886 ///         'try' compound-statement handler-seq
1887 ///
1888 StmtResult Parser::ParseCXXTryBlock(ParsedAttributes &attrs) {
1889   // FIXME: Add attributes?
1890
1891   assert(Tok.is(tok::kw_try) && "Expected 'try'");
1892
1893   SourceLocation TryLoc = ConsumeToken();
1894   return ParseCXXTryBlockCommon(TryLoc);
1895 }
1896
1897 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1898 /// function-try-block.
1899 ///
1900 ///       try-block:
1901 ///         'try' compound-statement handler-seq
1902 ///
1903 ///       function-try-block:
1904 ///         'try' ctor-initializer[opt] compound-statement handler-seq
1905 ///
1906 ///       handler-seq:
1907 ///         handler handler-seq[opt]
1908 ///
1909 ///       [Borland] try-block:
1910 ///         'try' compound-statement seh-except-block
1911 ///         'try' compound-statment  seh-finally-block
1912 ///
1913 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1914   if (Tok.isNot(tok::l_brace))
1915     return StmtError(Diag(Tok, diag::err_expected_lbrace));
1916   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1917   ParsedAttributesWithRange attrs(AttrFactory);
1918   StmtResult TryBlock(ParseCompoundStatement(attrs, /*isStmtExpr=*/false,
1919                                              Scope::DeclScope|Scope::TryScope));
1920   if (TryBlock.isInvalid())
1921     return move(TryBlock);
1922
1923   // Borland allows SEH-handlers with 'try'
1924   if(Tok.is(tok::kw___except) || Tok.is(tok::kw___finally)) {
1925     // TODO: Factor into common return ParseSEHHandlerCommon(...)
1926     StmtResult Handler;
1927     if(Tok.is(tok::kw___except)) {
1928       SourceLocation Loc = ConsumeToken();
1929       Handler = ParseSEHExceptBlock(Loc);
1930     }
1931     else {
1932       SourceLocation Loc = ConsumeToken();
1933       Handler = ParseSEHFinallyBlock(Loc);
1934     }
1935     if(Handler.isInvalid())
1936       return move(Handler);
1937
1938     return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
1939                                     TryLoc,
1940                                     TryBlock.take(),
1941                                     Handler.take());
1942   }
1943   else {
1944     StmtVector Handlers(Actions);
1945     MaybeParseCXX0XAttributes(attrs);
1946     ProhibitAttributes(attrs);
1947
1948     if (Tok.isNot(tok::kw_catch))
1949       return StmtError(Diag(Tok, diag::err_expected_catch));
1950     while (Tok.is(tok::kw_catch)) {
1951       StmtResult Handler(ParseCXXCatchBlock());
1952       if (!Handler.isInvalid())
1953         Handlers.push_back(Handler.release());
1954     }
1955     // Don't bother creating the full statement if we don't have any usable
1956     // handlers.
1957     if (Handlers.empty())
1958       return StmtError();
1959
1960     return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
1961   }
1962 }
1963
1964 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1965 ///
1966 ///       handler:
1967 ///         'catch' '(' exception-declaration ')' compound-statement
1968 ///
1969 ///       exception-declaration:
1970 ///         type-specifier-seq declarator
1971 ///         type-specifier-seq abstract-declarator
1972 ///         type-specifier-seq
1973 ///         '...'
1974 ///
1975 StmtResult Parser::ParseCXXCatchBlock() {
1976   assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1977
1978   SourceLocation CatchLoc = ConsumeToken();
1979
1980   SourceLocation LParenLoc = Tok.getLocation();
1981   if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1982     return StmtError();
1983
1984   // C++ 3.3.2p3:
1985   // The name in a catch exception-declaration is local to the handler and
1986   // shall not be redeclared in the outermost block of the handler.
1987   ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1988
1989   // exception-declaration is equivalent to '...' or a parameter-declaration
1990   // without default arguments.
1991   Decl *ExceptionDecl = 0;
1992   if (Tok.isNot(tok::ellipsis)) {
1993     DeclSpec DS(AttrFactory);
1994     if (ParseCXXTypeSpecifierSeq(DS))
1995       return StmtError();
1996     Declarator ExDecl(DS, Declarator::CXXCatchContext);
1997     ParseDeclarator(ExDecl);
1998     ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
1999   } else
2000     ConsumeToken();
2001
2002   if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
2003     return StmtError();
2004
2005   if (Tok.isNot(tok::l_brace))
2006     return StmtError(Diag(Tok, diag::err_expected_lbrace));
2007
2008   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2009   ParsedAttributes attrs(AttrFactory);
2010   StmtResult Block(ParseCompoundStatement(attrs));
2011   if (Block.isInvalid())
2012     return move(Block);
2013
2014   return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
2015 }
2016
2017 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2018   bool Result;
2019   if (ParseMicrosoftIfExistsCondition(Result))
2020     return;
2021   
2022   if (Tok.isNot(tok::l_brace)) {
2023     Diag(Tok, diag::err_expected_lbrace);
2024     return;
2025   }
2026   ConsumeBrace();
2027
2028   // Condition is false skip all inside the {}.
2029   if (!Result) {
2030     SkipUntil(tok::r_brace, false);
2031     return;
2032   }
2033
2034   // Condition is true, parse the statements.
2035   while (Tok.isNot(tok::r_brace)) {
2036     StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2037     if (R.isUsable())
2038       Stmts.push_back(R.release());
2039   }
2040
2041   if (Tok.isNot(tok::r_brace)) {
2042     Diag(Tok, diag::err_expected_rbrace);
2043     return;
2044   }
2045   ConsumeBrace();
2046 }