1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Statement and Block portions of the Parser
13 //===----------------------------------------------------------------------===//
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;
25 //===----------------------------------------------------------------------===//
26 // C99 6.8: Statements and Blocks.
27 //===----------------------------------------------------------------------===//
29 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
30 /// StatementOrDeclaration:
36 /// compound-statement
37 /// expression-statement
38 /// selection-statement
39 /// iteration-statement
41 /// [C++] declaration-statement
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]
50 /// labeled-statement:
51 /// identifier ':' statement
52 /// 'case' constant-expression ':' statement
53 /// 'default' ':' statement
55 /// selection-statement:
59 /// iteration-statement:
64 /// expression-statement:
65 /// expression[opt] ';'
68 /// 'goto' identifier ';'
71 /// 'return' expression[opt] ';'
72 /// [GNU] 'goto' '*' expression ';'
74 /// [OBC] objc-throw-statement:
75 /// [OBC] '@' 'throw' expression ';'
76 /// [OBC] '@' 'throw' ';'
79 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement) {
80 const char *SemiError = 0;
83 ParenBraceBracketBalancer BalancerRAIIObj(*this);
85 ParsedAttributesWithRange attrs(AttrFactory);
86 MaybeParseCXX0XAttributes(attrs);
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.
92 tok::TokenKind Kind = Tok.getKind();
95 case tok::at: // May be a @try or @throw statement
97 AtLoc = ConsumeToken(); // consume @
98 return ParseObjCAtStatement(AtLoc);
101 case tok::code_completion:
102 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
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);
113 if (Next.isNot(tok::coloncolon)) {
115 IdentifierInfo *Name = Tok.getIdentifierInfo();
116 SourceLocation NameLoc = Tok.getLocation();
118 if (getLang().CPlusPlus)
119 CheckForTemplateAndDigraph(Next, ParsedType(),
120 /*EnteringContext=*/false, *Name, SS);
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());
134 // Fall through via the normal error path.
135 // FIXME: This seems like it could only happen for context-sensitive
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))
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.
152 Tok.setKind(tok::annot_typename);
153 setTypeAnnotation(Tok, Classification.getType());
154 Tok.setAnnotationEndLoc(NameLoc);
155 PP.AnnotateCachedTokens(Tok);
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);
165 case Sema::NC_TypeTemplate:
166 case Sema::NC_FunctionTemplate: {
167 ConsumeToken(); // the identifier
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))
183 // If the next token is '::', jump right into parsing a
184 // nested-name-specifier. We don't want to leave the template-id
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))
195 // We've annotated a template-id, so try again now.
199 case Sema::NC_NestedNameSpecifier:
200 // FIXME: Implement this!
209 if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
210 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
211 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
213 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
216 if (Tok.is(tok::r_brace)) {
217 Diag(Tok, diag::err_expected_statement);
221 return ParseExprStatement(attrs);
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);
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);
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);
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";
247 case tok::kw_for: // C99 6.8.5.3: for-statement
248 return ParseForStatement(attrs);
250 case tok::kw_goto: // C99 6.8.6.1: goto-statement
251 Res = ParseGotoStatement(attrs);
254 case tok::kw_continue: // C99 6.8.6.2: continue-statement
255 Res = ParseContinueStatement(attrs);
256 SemiError = "continue";
258 case tok::kw_break: // C99 6.8.6.3: break-statement
259 Res = ParseBreakStatement(attrs);
262 case tok::kw_return: // C99 6.8.6.4: return-statement
263 Res = ParseReturnStatement(attrs);
264 SemiError = "return";
268 ProhibitAttributes(attrs);
270 Res = ParseAsmStatement(msAsm);
271 Res = Actions.ActOnFinishFullStmt(Res.get());
272 if (msAsm) return move(Res);
277 case tok::kw_try: // C++ 15: try-block
278 return ParseCXXTryBlock(attrs);
281 return ParseSEHTryBlock(attrs);
284 // If we reached this code, the statement must end in a semicolon.
285 if (Tok.is(tok::semi)) {
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
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);
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;
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))
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 ");
324 // Recover parsing as a case statement.
325 return ParseCaseStatement(Attrs, /*MissingCase=*/true, Expr);
328 // Otherwise, eat the semicolon.
329 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
330 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
333 StmtResult Parser::ParseSEHTryBlock(ParsedAttributes & Attrs) {
334 assert(Tok.is(tok::kw___try) && "Expected '__try'");
335 SourceLocation Loc = ConsumeToken();
336 return ParseSEHTryBlockCommon(Loc);
339 /// ParseSEHTryBlockCommon
342 /// '__try' compound-statement seh-handler
346 /// seh-finally-block
348 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
349 if(Tok.isNot(tok::l_brace))
350 return StmtError(Diag(Tok,diag::err_expected_lbrace));
352 ParsedAttributesWithRange attrs(AttrFactory);
353 StmtResult TryBlock(ParseCompoundStatement(attrs));
354 if(TryBlock.isInvalid())
355 return move(TryBlock);
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);
365 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
368 if(Handler.isInvalid())
369 return move(Handler);
371 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
377 /// ParseSEHExceptBlock - Handle __except
379 /// seh-except-block:
380 /// '__except' '(' seh-filter-expression ')' compound-statement
382 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
383 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
384 raii2(Ident___exception_code, false),
385 raii3(Ident_GetExceptionCode, false);
387 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
390 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
392 if (getLang().Borland) {
393 Ident__exception_info->setIsPoisoned(false);
394 Ident___exception_info->setIsPoisoned(false);
395 Ident_GetExceptionInfo->setIsPoisoned(false);
397 ExprResult FilterExpr(ParseExpression());
399 if (getLang().Borland) {
400 Ident__exception_info->setIsPoisoned(true);
401 Ident___exception_info->setIsPoisoned(true);
402 Ident_GetExceptionInfo->setIsPoisoned(true);
405 if(FilterExpr.isInvalid())
408 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
411 ParsedAttributesWithRange attrs(AttrFactory);
412 StmtResult Block(ParseCompoundStatement(attrs));
414 if(Block.isInvalid())
417 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
420 /// ParseSEHFinallyBlock - Handle __finally
422 /// seh-finally-block:
423 /// '__finally' compound-statement
425 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
426 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
427 raii2(Ident___abnormal_termination, false),
428 raii3(Ident_AbnormalTermination, false);
430 ParsedAttributesWithRange attrs(AttrFactory);
431 StmtResult Block(ParseCompoundStatement(attrs));
432 if(Block.isInvalid())
435 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
438 /// ParseLabeledStatement - We have an identifier and a ':' after it.
440 /// labeled-statement:
441 /// identifier ':' statement
442 /// [GNU] identifier ':' attributes[opt] statement
444 StmtResult Parser::ParseLabeledStatement(ParsedAttributes &attrs) {
445 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
446 "Not an identifier!");
448 Token IdentTok = Tok; // Save the whole token.
449 ConsumeToken(); // eat the identifier.
451 assert(Tok.is(tok::colon) && "Not a label!");
453 // identifier ':' statement
454 SourceLocation ColonLoc = ConsumeToken();
456 // Read label attributes, if present.
457 MaybeParseGNUAttributes(attrs);
459 StmtResult SubStmt(ParseStatement());
461 // Broken substmt shouldn't prevent the label from being added to the AST.
462 if (SubStmt.isInvalid())
463 SubStmt = Actions.ActOnNullStmt(ColonLoc);
465 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
466 IdentTok.getLocation());
467 if (AttributeList *Attrs = attrs.getList())
468 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
470 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
474 /// ParseCaseStatement
475 /// labeled-statement:
476 /// 'case' constant-expression ':' statement
477 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
479 StmtResult Parser::ParseCaseStatement(ParsedAttributes &attrs, bool MissingCase,
481 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
482 // FIXME: Use attributes?
484 // It is very very common for code to contain many case statements recursively
485 // nested, as in (but usually without indentation):
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 :).
498 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
500 StmtResult TopLevelCase(true);
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;
507 // While we have case statements, eat and stack them.
508 SourceLocation ColonLoc;
510 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
511 ConsumeToken(); // eat the 'case'.
513 if (Tok.is(tok::code_completion)) {
514 Actions.CodeCompleteCase(getCurScope());
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
522 ColonProtectionRAIIObject ColonProtection(*this);
524 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
526 if (LHS.isInvalid()) {
527 SkipUntil(tok::colon);
531 // GNU case range extension.
532 SourceLocation DotDotDotLoc;
534 if (Tok.is(tok::ellipsis)) {
535 Diag(Tok, diag::ext_gnu_case_range);
536 DotDotDotLoc = ConsumeToken();
538 RHS = ParseConstantExpression();
539 if (RHS.isInvalid()) {
540 SkipUntil(tok::colon);
545 ColonProtection.restore();
547 if (Tok.is(tok::colon)) {
548 ColonLoc = ConsumeToken();
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, ":");
556 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
557 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
558 << FixItHint::CreateInsertion(ExpectedLoc, ":");
559 ColonLoc = ExpectedLoc;
563 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
564 RHS.get(), ColonLoc);
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.
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);
579 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
580 DeepestParsedCaseStmt = NextDeepest;
583 // Handle all case statements.
584 } while (Tok.is(tok::kw_case));
586 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
588 // If we found a non-case statement, start by parsing it.
591 if (Tok.isNot(tok::r_brace)) {
592 SubStmt = ParseStatement();
594 // Nicely diagnose the common error "switch (X) { case 4: }", which is
596 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
597 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement);
601 // Broken sub-stmt shouldn't prevent forming the case statement properly.
602 if (SubStmt.isInvalid())
603 SubStmt = Actions.ActOnNullStmt(SourceLocation());
605 // Install the body into the most deeply-nested case.
606 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
608 // Return the top level parsed statement tree.
609 return move(TopLevelCase);
612 /// ParseDefaultStatement
613 /// labeled-statement:
614 /// 'default' ':' statement
615 /// Note that this does not parse the 'statement' at the end.
617 StmtResult Parser::ParseDefaultStatement(ParsedAttributes &attrs) {
618 //FIXME: Use attributes?
620 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
621 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
623 SourceLocation ColonLoc;
624 if (Tok.is(tok::colon)) {
625 ColonLoc = ConsumeToken();
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, ":");
633 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
634 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
635 << FixItHint::CreateInsertion(ExpectedLoc, ":");
636 ColonLoc = ExpectedLoc;
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);
646 StmtResult SubStmt(ParseStatement());
647 if (SubStmt.isInvalid())
650 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
651 SubStmt.get(), getCurScope());
654 StmtResult Parser::ParseCompoundStatement(ParsedAttributes &Attr,
656 return ParseCompoundStatement(Attr, isStmtExpr, Scope::DeclScope);
659 /// ParseCompoundStatement - Parse a "{}" block.
661 /// compound-statement: [C99 6.8.2]
662 /// { block-item-list[opt] }
663 /// [GNU] { label-declarations block-item-list } [TODO]
667 /// block-item-list block-item
671 /// [GNU] '__extension__' declaration
673 /// [OMP] openmp-directive [TODO]
675 /// [GNU] label-declarations:
676 /// [GNU] label-declaration
677 /// [GNU] label-declarations label-declaration
679 /// [GNU] label-declaration:
680 /// [GNU] '__label__' identifier-list ';'
682 /// [OMP] openmp-directive: [TODO]
683 /// [OMP] barrier-directive
684 /// [OMP] flush-directive
686 StmtResult Parser::ParseCompoundStatement(ParsedAttributes &attrs,
688 unsigned ScopeFlags) {
689 //FIXME: Use attributes?
691 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
693 // Enter a scope to hold everything within the compound stmt. Compound
694 // statements can always hold declarations.
695 ParseScope CompoundScope(this, ScopeFlags);
697 // Parse the statements in the body.
698 return ParseCompoundStatementBody(isStmtExpr);
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
706 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
707 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
709 "in compound statement ('{}')");
710 InMessageExpressionRAIIObject InMessage(*this, false);
711 BalancedDelimiterTracker T(*this, tok::l_brace);
715 StmtVector Stmts(Actions);
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);
723 SmallVector<Decl *, 8> DeclsInGroup;
725 if (Tok.isNot(tok::identifier)) {
726 Diag(Tok, diag::err_expected_ident);
730 IdentifierInfo *II = Tok.getIdentifierInfo();
731 SourceLocation IdLoc = ConsumeToken();
732 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
734 if (!Tok.is(tok::comma))
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());
744 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
746 Stmts.push_back(R.release());
749 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
750 if (Tok.is(tok::annot_pragma_unused)) {
751 HandlePragmaUnused();
755 if (getLang().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
756 Tok.is(tok::kw___if_not_exists))) {
757 ParseMicrosoftIfExistsStatement(Stmts);
762 if (Tok.isNot(tok::kw___extension__)) {
763 R = ParseStatementOrDeclaration(Stmts, false);
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__))
773 ParsedAttributesWithRange attrs(AttrFactory);
774 MaybeParseCXX0XAttributes(attrs);
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);
782 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
783 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
784 Declarator::BlockContext, DeclEnd,
786 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
788 // Otherwise this was a unary __extension__ marker.
789 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
791 if (Res.isInvalid()) {
792 SkipUntil(tok::semi);
796 // FIXME: Use attributes?
797 // Eat the semicolon at the end of stmt and convert the expr into a
799 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
800 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
805 Stmts.push_back(R.release());
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) << "{";
815 if (T.consumeClose())
818 return Actions.ActOnCompoundStmt(T.getOpenLocation(), T.getCloseLocation(),
819 move_arg(Stmts), isStmtExpr);
822 /// ParseParenExprOrCondition:
823 /// [C ] '(' expression ')'
824 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
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,
836 bool ConvertToBoolean) {
837 BalancedDelimiterTracker T(*this, tok::l_paren);
840 if (getLang().CPlusPlus)
841 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
843 ExprResult = ParseExpression();
846 // If required, convert to a boolean value.
847 if (!ExprResult.isInvalid() && ConvertToBoolean)
849 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
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))
863 // Otherwise the condition is valid or the rparen is present.
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
876 StmtResult Parser::ParseIfStatement(ParsedAttributes &attrs) {
877 // FIXME: Use attributes?
879 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
880 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
882 if (Tok.isNot(tok::l_paren)) {
883 Diag(Tok, diag::err_expected_lparen_after) << "if";
884 SkipUntil(tok::semi);
888 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
890 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
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
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).
902 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
904 // Parse the condition.
907 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
910 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
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.
917 // The substatement in a selection-statement (each substatement, in the else
918 // form of the if statement) implicitly defines a local scope.
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.
930 ParseScope InnerScope(this, Scope::DeclScope,
931 C99orCXX && Tok.isNot(tok::l_brace));
933 // Read the 'then' stmt.
934 SourceLocation ThenStmtLoc = Tok.getLocation();
935 StmtResult ThenStmt(ParseStatement());
937 // Pop the 'if' scope if needed.
940 // If it has an else, parse it.
941 SourceLocation ElseLoc;
942 SourceLocation ElseStmtLoc;
945 if (Tok.is(tok::kw_else)) {
946 ElseLoc = ConsumeToken();
947 ElseStmtLoc = Tok.getLocation();
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
955 // The substatement in a selection-statement (each substatement, in the else
956 // form of the if statement) implicitly defines a local scope.
958 ParseScope InnerScope(this, Scope::DeclScope,
959 C99orCXX && Tok.isNot(tok::l_brace));
961 ElseStmt = ParseStatement();
963 // Pop the 'else' scope if needed.
965 } else if (Tok.is(tok::code_completion)) {
966 Actions.CodeCompleteAfterIf(getCurScope());
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)
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.
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);
994 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
995 ElseLoc, ElseStmt.get());
998 /// ParseSwitchStatement
999 /// switch-statement:
1000 /// 'switch' '(' expression ')' statement
1001 /// [C++] 'switch' '(' condition ')' statement
1002 StmtResult Parser::ParseSwitchStatement(ParsedAttributes &attrs) {
1003 // FIXME: Use attributes?
1005 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1006 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1008 if (Tok.isNot(tok::l_paren)) {
1009 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1010 SkipUntil(tok::semi);
1014 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
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.
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
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).
1028 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
1030 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1031 ParseScope SwitchScope(this, ScopeFlags);
1033 // Parse the condition.
1036 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1040 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
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)) {
1049 SkipUntil(tok::r_brace, false, false);
1051 SkipUntil(tok::semi);
1052 return move(Switch);
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.
1060 // The substatement in a selection-statement (each substatement, in the else
1061 // form of the if statement) implicitly defines a local scope.
1063 // See comments in ParseIfStatement for why we create a scope for the
1064 // condition and a new scope for substatement in C++.
1066 ParseScope InnerScope(this, Scope::DeclScope,
1067 C99orCXX && Tok.isNot(tok::l_brace));
1069 // Read the body statement.
1070 StmtResult Body(ParseStatement());
1076 if (Body.isInvalid())
1077 // FIXME: Remove the case statement list from the Switch statement.
1078 Body = Actions.ActOnNullStmt(Tok.getLocation());
1080 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
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?
1090 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1091 SourceLocation WhileLoc = Tok.getLocation();
1092 ConsumeToken(); // eat the 'while'.
1094 if (Tok.isNot(tok::l_paren)) {
1095 Diag(Tok, diag::err_expected_lparen_after) << "while";
1096 SkipUntil(tok::semi);
1100 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
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.
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
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).
1114 unsigned ScopeFlags;
1116 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1117 Scope::DeclScope | Scope::ControlScope;
1119 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1120 ParseScope WhileScope(this, ScopeFlags);
1122 // Parse the condition.
1125 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1128 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
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.
1135 // The substatement in an iteration-statement implicitly defines a local scope
1136 // which is entered and exited each time through the loop.
1138 // See comments in ParseIfStatement for why we create a scope for the
1139 // condition and a new scope for substatement in C++.
1141 ParseScope InnerScope(this, Scope::DeclScope,
1142 C99orCXX && Tok.isNot(tok::l_brace));
1144 // Read the body statement.
1145 StmtResult Body(ParseStatement());
1147 // Pop the body scope if needed.
1151 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1154 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
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?
1164 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1165 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
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;
1171 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1173 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1175 ParseScope DoScope(this, ScopeFlags);
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.
1182 // The substatement in an iteration-statement implicitly defines a local scope
1183 // which is entered and exited each time through the loop.
1185 ParseScope InnerScope(this, Scope::DeclScope,
1186 (getLang().C99 || getLang().CPlusPlus) &&
1187 Tok.isNot(tok::l_brace));
1189 // Read the body statement.
1190 StmtResult Body(ParseStatement());
1192 // Pop the body scope if needed.
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);
1203 SourceLocation WhileLoc = ConsumeToken();
1205 if (Tok.isNot(tok::l_paren)) {
1206 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1207 SkipUntil(tok::semi, false, true);
1211 // Parse the parenthesized condition.
1212 BalancedDelimiterTracker T(*this, tok::l_paren);
1214 ExprResult Cond = ParseExpression();
1218 if (Cond.isInvalid() || Body.isInvalid())
1221 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1222 Cond.get(), T.getCloseLocation());
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] ')'
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
1235 /// [C++] for-init-statement:
1236 /// [C++] expression-statement
1237 /// [C++] simple-declaration
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?
1247 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1248 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1250 if (Tok.isNot(tok::l_paren)) {
1251 Diag(Tok, diag::err_expected_lparen_after) << "for";
1252 SkipUntil(tok::semi);
1256 bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
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.
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
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).
1270 // Names declared in the for-init-statement are in the same declarative-region
1271 // as those declared in the condition.
1273 unsigned ScopeFlags;
1275 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1276 Scope::DeclScope | Scope::ControlScope;
1278 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1280 ParseScope ForScope(this, ScopeFlags);
1282 BalancedDelimiterTracker T(*this, tok::l_paren);
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;
1296 if (Tok.is(tok::code_completion)) {
1297 Actions.CodeCompleteOrdinaryName(getCurScope(),
1298 C99orCXXorObjC? Sema::PCC_ForInit
1299 : Sema::PCC_Expression);
1304 // Parse the first part of the for specifier.
1305 if (Tok.is(tok::semi)) { // for (;
1306 // no first part, eat the ';'.
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);
1313 ParsedAttributesWithRange attrs(AttrFactory);
1314 MaybeParseCXX0XAttributes(attrs);
1316 // In C++0x, "for (T NS:a" might not be a typo for ::
1317 bool MightBeForRangeStmt = getLang().CPlusPlus;
1318 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1320 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1321 StmtVector Stmts(Actions);
1322 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
1323 DeclEnd, attrs, false,
1324 MightBeForRangeStmt ?
1326 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1328 if (ForRangeInit.ParsedForRangeDecl()) {
1329 if (!getLang().CPlusPlus0x)
1330 Diag(ForRangeInit.ColonLoc, diag::ext_for_range);
1333 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1335 } else if ((ForEach = isTokIdentifier_in())) {
1336 Actions.ActOnForEachDeclStmt(DG);
1337 // ObjC: for (id x in expr)
1338 ConsumeToken(); // consume 'in'
1340 if (Tok.is(tok::code_completion)) {
1341 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1345 Collection = ParseExpression();
1347 Diag(Tok, diag::err_expected_semi_for);
1350 Value = ParseExpression();
1352 ForEach = isTokIdentifier_in();
1354 // Turn the expression into a stmt.
1355 if (!Value.isInvalid()) {
1357 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1359 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1362 if (Tok.is(tok::semi)) {
1364 } else if (ForEach) {
1365 ConsumeToken(); // consume 'in'
1367 if (Tok.is(tok::code_completion)) {
1368 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1372 Collection = ParseExpression();
1374 if (!Value.isInvalid()) {
1375 Diag(Tok, diag::err_expected_semi_for);
1377 // Skip until semicolon or rparen, don't consume it.
1378 SkipUntil(tok::r_paren, true, true);
1379 if (Tok.is(tok::semi))
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 (...;;
1389 } else if (Tok.is(tok::r_paren)) {
1390 // missing both semicolons.
1393 if (getLang().CPlusPlus)
1394 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1396 Second = ParseExpression();
1397 if (!Second.isInvalid())
1398 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1401 SecondPartIsInvalid = Second.isInvalid();
1402 SecondPart = Actions.MakeFullExpr(Second.get());
1405 if (Tok.isNot(tok::semi)) {
1406 if (!SecondPartIsInvalid || SecondVar)
1407 Diag(Tok, diag::err_expected_semi_for);
1409 // Skip until semicolon or rparen, don't consume it.
1410 SkipUntil(tok::r_paren, true, true);
1413 if (Tok.is(tok::semi)) {
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());
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;
1431 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, T.getOpenLocation(),
1433 ForRangeInit.ColonLoc,
1434 ForRangeInit.RangeExpr.get(),
1435 T.getCloseLocation());
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())
1443 Actions.ActOnObjCForCollectionOperand(ForLoc, Collection.take());
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.
1451 // The substatement in an iteration-statement implicitly defines a local scope
1452 // which is entered and exited each time through the loop.
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++.
1457 ParseScope InnerScope(this, Scope::DeclScope,
1458 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1460 // Read the body statement.
1461 StmtResult Body(ParseStatement());
1463 // Pop the body scope if needed.
1466 // Leave the for-scope.
1469 if (Body.isInvalid())
1473 return Actions.ActOnObjCForCollectionStmt(ForLoc, T.getOpenLocation(),
1476 T.getCloseLocation(),
1480 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1482 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1483 SecondPart, SecondVar, ThirdPart,
1484 T.getCloseLocation(), Body.take());
1487 /// ParseGotoStatement
1489 /// 'goto' identifier ';'
1490 /// [GNU] 'goto' '*' expression ';'
1492 /// Note: this lets the caller parse the end ';'.
1494 StmtResult Parser::ParseGotoStatement(ParsedAttributes &attrs) {
1495 // FIXME: Use attributes?
1497 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1498 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1501 if (Tok.is(tok::identifier)) {
1502 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1504 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
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);
1515 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1517 Diag(Tok, diag::err_expected_ident);
1524 /// ParseContinueStatement
1528 /// Note: this lets the caller parse the end ';'.
1530 StmtResult Parser::ParseContinueStatement(ParsedAttributes &attrs) {
1531 // FIXME: Use attributes?
1533 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1534 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1537 /// ParseBreakStatement
1541 /// Note: this lets the caller parse the end ';'.
1543 StmtResult Parser::ParseBreakStatement(ParsedAttributes &attrs) {
1544 // FIXME: Use attributes?
1546 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1547 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1550 /// ParseReturnStatement
1552 /// 'return' expression[opt] ';'
1553 StmtResult Parser::ParseReturnStatement(ParsedAttributes &attrs) {
1554 // FIXME: Use attributes?
1556 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1557 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1560 if (Tok.isNot(tok::semi)) {
1561 if (Tok.is(tok::code_completion)) {
1562 Actions.CodeCompleteReturn(getCurScope());
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();
1576 R = ParseExpression();
1577 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1578 SkipUntil(tok::semi, false, true);
1582 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
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;
1591 bool InBraces = false;
1592 unsigned short savedBraceCount = 0;
1593 bool InAsmComment = false;
1595 unsigned LineNo = 0;
1596 unsigned NumTokensRead = 0;
1597 SourceLocation LBraceLoc;
1599 if (Tok.is(tok::l_brace)) {
1600 // Braced inline asm: consume the opening brace.
1602 savedBraceCount = BraceCount;
1603 EndLoc = LBraceLoc = ConsumeBrace();
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);
1613 SourceLocation TokLoc = Tok.getLocation();
1615 // If we hit EOF, we're done, period.
1616 if (Tok.is(tok::eof))
1618 // When we consume the closing brace, we're done.
1619 if (InBraces && BraceCount == savedBraceCount)
1622 if (!InAsmComment && Tok.is(tok::semi)) {
1623 // A semicolon in an asm is the start of a comment.
1624 InAsmComment = true;
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);
1632 } else if (!InBraces || InAsmComment) {
1633 // If end-of-line is significant, check whether this token is on a
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.
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?
1652 // Consume the next token; make sure we don't modify the brace count etc.
1653 // if we are in a comment.
1659 TokLoc = Tok.getLocation();
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) << "{";
1668 } else if (NumTokensRead == 0) {
1670 Diag(Tok, diag::err_expected_lbrace);
1673 // Multiple adjacent asm's form together into a single asm statement
1675 if (!Tok.is(tok::kw_asm))
1677 EndLoc = ConsumeToken();
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.
1685 t.setKind(tok::string_literal);
1686 t.setLiteralData("\"/*FIXME: not done*/\"");
1687 t.clearFlag(Token::NeedsCleaning);
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),
1699 /// ParseAsmStatement - Parse a GNU extended asm statement.
1701 /// gnu-asm-statement
1702 /// ms-asm-statement
1704 /// [GNU] gnu-asm-statement:
1705 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
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
1714 /// [GNU] asm-clobbers:
1715 /// asm-string-literal
1716 /// asm-clobbers ',' asm-string-literal
1718 /// [MS] ms-asm-statement:
1720 /// ms-asm-block ms-asm-statement
1722 /// [MS] ms-asm-block:
1723 /// '__asm' ms-asm-line '\n'
1724 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
1726 /// [MS] ms-asm-instruction-block
1728 /// ms-asm-line '\n' ms-asm-instruction-block
1730 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
1731 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1732 SourceLocation AsmLoc = ConsumeToken();
1734 if (getLang().MicrosoftExt && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1736 return ParseMicrosoftAsmStatement(AsmLoc);
1738 DeclSpec DS(AttrFactory);
1739 SourceLocation Loc = Tok.getLocation();
1740 ParseTypeQualifierListOpt(DS, true, false);
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";
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);
1755 BalancedDelimiterTracker T(*this, tok::l_paren);
1758 ExprResult AsmString(ParseAsmStringLiteral());
1759 if (AsmString.isInvalid())
1762 SmallVector<IdentifierInfo *, 4> Names;
1763 ExprVector Constraints(Actions);
1764 ExprVector Exprs(Actions);
1765 ExprVector Clobbers(Actions);
1767 if (Tok.is(tok::r_paren)) {
1768 // We have a simple asm expression like 'asm("foo")'.
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());
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);
1784 if (!AteExtraColon &&
1785 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1789 unsigned NumOutputs = Names.size();
1791 // Parse Inputs, if present.
1792 if (AteExtraColon ||
1793 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1794 // In C++ mode, parse "::" like ": :".
1796 AteExtraColon = false;
1798 AteExtraColon = Tok.is(tok::coloncolon);
1802 if (!AteExtraColon &&
1803 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1807 assert(Names.size() == Constraints.size() &&
1808 Constraints.size() == Exprs.size() &&
1809 "Input operand size mismatch!");
1811 unsigned NumInputs = Names.size() - NumOutputs;
1813 // Parse the clobbers, if present.
1814 if (AteExtraColon || Tok.is(tok::colon)) {
1818 // Parse the asm-string list for clobbers if present.
1819 if (Tok.isNot(tok::r_paren)) {
1821 ExprResult Clobber(ParseAsmStringLiteral());
1823 if (Clobber.isInvalid())
1826 Clobbers.push_back(Clobber.release());
1828 if (Tok.isNot(tok::comma)) break;
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());
1842 /// ParseAsmOperands - Parse the asm-operands production as used by
1843 /// asm-statement, assuming the leading ':' token was eaten.
1845 /// [GNU] asm-operands:
1847 /// asm-operands ',' asm-operand
1849 /// [GNU] asm-operand:
1850 /// asm-string-literal '(' expression ')'
1851 /// '[' identifier ']' asm-string-literal '(' expression ')'
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))
1863 // Read the [id] if present.
1864 if (Tok.is(tok::l_square)) {
1865 BalancedDelimiterTracker T(*this, tok::l_square);
1868 if (Tok.isNot(tok::identifier)) {
1869 Diag(Tok, diag::err_expected_ident);
1870 SkipUntil(tok::r_paren);
1874 IdentifierInfo *II = Tok.getIdentifierInfo();
1877 Names.push_back(II);
1882 ExprResult Constraint(ParseAsmStringLiteral());
1883 if (Constraint.isInvalid()) {
1884 SkipUntil(tok::r_paren);
1887 Constraints.push_back(Constraint.release());
1889 if (Tok.isNot(tok::l_paren)) {
1890 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1891 SkipUntil(tok::r_paren);
1895 // Read the parenthesized expression.
1896 BalancedDelimiterTracker T(*this, tok::l_paren);
1898 ExprResult Res(ParseExpression());
1900 if (Res.isInvalid()) {
1901 SkipUntil(tok::r_paren);
1904 Exprs.push_back(Res.release());
1905 // Eat the comma and continue parsing if it exists.
1906 if (Tok.isNot(tok::comma)) return false;
1913 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
1914 assert(Tok.is(tok::l_brace));
1915 SourceLocation LBraceLoc = Tok.getLocation();
1917 if (PP.isCodeCompletionEnabled()) {
1918 if (trySkippingFunctionBodyForCodeCompletion()) {
1920 return Actions.ActOnFinishFunctionBody(Decl, 0);
1924 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1925 "parsing function body");
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());
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);
1938 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1941 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1943 /// function-try-block:
1944 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1946 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
1947 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1948 SourceLocation TryLoc = ConsumeToken();
1950 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1951 "parsing function try block");
1953 // Constructor initializer list?
1954 if (Tok.is(tok::colon))
1955 ParseConstructorInitializer(Decl);
1957 Actions.ActOnDefaultCtorInitializers(Decl);
1959 if (PP.isCodeCompletionEnabled()) {
1960 if (trySkippingFunctionBodyForCodeCompletion()) {
1962 return Actions.ActOnFinishFunctionBody(Decl, 0);
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);
1975 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
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");
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);
1987 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
1988 /*StopAtCodeCompletion=*/true)) {
1997 /// ParseCXXTryBlock - Parse a C++ try-block.
2000 /// 'try' compound-statement handler-seq
2002 StmtResult Parser::ParseCXXTryBlock(ParsedAttributes &attrs) {
2003 // FIXME: Add attributes?
2005 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2007 SourceLocation TryLoc = ConsumeToken();
2008 return ParseCXXTryBlockCommon(TryLoc);
2011 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2012 /// function-try-block.
2015 /// 'try' compound-statement handler-seq
2017 /// function-try-block:
2018 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2021 /// handler handler-seq[opt]
2023 /// [Borland] try-block:
2024 /// 'try' compound-statement seh-except-block
2025 /// 'try' compound-statment seh-finally-block
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);
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(...)
2041 if(Tok.is(tok::kw___except)) {
2042 SourceLocation Loc = ConsumeToken();
2043 Handler = ParseSEHExceptBlock(Loc);
2046 SourceLocation Loc = ConsumeToken();
2047 Handler = ParseSEHFinallyBlock(Loc);
2049 if(Handler.isInvalid())
2050 return move(Handler);
2052 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2058 StmtVector Handlers(Actions);
2059 MaybeParseCXX0XAttributes(attrs);
2060 ProhibitAttributes(attrs);
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());
2069 // Don't bother creating the full statement if we don't have any usable
2071 if (Handlers.empty())
2074 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
2078 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2081 /// 'catch' '(' exception-declaration ')' compound-statement
2083 /// exception-declaration:
2084 /// type-specifier-seq declarator
2085 /// type-specifier-seq abstract-declarator
2086 /// type-specifier-seq
2089 StmtResult Parser::ParseCXXCatchBlock() {
2090 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2092 SourceLocation CatchLoc = ConsumeToken();
2094 BalancedDelimiterTracker T(*this, tok::l_paren);
2095 if (T.expectAndConsume(diag::err_expected_lparen))
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);
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))
2110 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2111 ParseDeclarator(ExDecl);
2112 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2117 if (T.getCloseLocation().isInvalid())
2120 if (Tok.isNot(tok::l_brace))
2121 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2123 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2124 ParsedAttributes attrs(AttrFactory);
2125 StmtResult Block(ParseCompoundStatement(attrs));
2126 if (Block.isInvalid())
2129 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
2132 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2134 if (ParseMicrosoftIfExistsCondition(Result))
2137 if (Tok.isNot(tok::l_brace)) {
2138 Diag(Tok, diag::err_expected_lbrace);
2143 // Condition is false skip all inside the {}.
2145 SkipUntil(tok::r_brace, false);
2149 // Condition is true, parse the statements.
2150 while (Tok.isNot(tok::r_brace)) {
2151 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2153 Stmts.push_back(R.release());
2156 if (Tok.isNot(tok::r_brace)) {
2157 Diag(Tok, diag::err_expected_rbrace);