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