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 /// [OBC] objc-throw-statement
44 /// [OBC] objc-try-catch-statement
45 /// [OBC] objc-synchronized-statement
46 /// [GNU] asm-statement
47 /// [OMP] openmp-construct [TODO]
49 /// labeled-statement:
50 /// identifier ':' statement
51 /// 'case' constant-expression ':' statement
52 /// 'default' ':' statement
54 /// selection-statement:
58 /// iteration-statement:
63 /// expression-statement:
64 /// expression[opt] ';'
67 /// 'goto' identifier ';'
70 /// 'return' expression[opt] ';'
71 /// [GNU] 'goto' '*' expression ';'
73 /// [OBC] objc-throw-statement:
74 /// [OBC] '@' 'throw' expression ';'
75 /// [OBC] '@' 'throw' ';'
78 Parser::ParseStatementOrDeclaration(StmtVector
&Stmts
, bool OnlyStatement
) {
79 const char *SemiError
= 0;
82 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
84 ParsedAttributesWithRange attrs
;
85 MaybeParseCXX0XAttributes(attrs
);
87 // Cases in this switch statement should fall through if the parser expects
88 // the token to end in a semicolon (in which case SemiError should be set),
89 // or they directly 'return;' if not.
90 tok::TokenKind Kind
= Tok
.getKind();
93 case tok::at
: // May be a @try or @throw statement
95 AtLoc
= ConsumeToken(); // consume @
96 return ParseObjCAtStatement(AtLoc
);
99 case tok::code_completion
:
100 Actions
.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement
);
101 ConsumeCodeCompletionToken();
102 return ParseStatementOrDeclaration(Stmts
, OnlyStatement
);
104 case tok::identifier
:
105 if (NextToken().is(tok::colon
)) { // C99 6.8.1: labeled-statement
106 // identifier ':' statement
107 return ParseLabeledStatement(attrs
);
112 if ((getLang().CPlusPlus
|| !OnlyStatement
) && isDeclarationStatement()) {
113 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
114 DeclGroupPtrTy Decl
= ParseDeclaration(Stmts
, Declarator::BlockContext
,
116 return Actions
.ActOnDeclStmt(Decl
, DeclStart
, DeclEnd
);
119 if (Tok
.is(tok::r_brace
)) {
120 Diag(Tok
, diag::err_expected_statement
);
124 // FIXME: Use the attributes
125 // expression[opt] ';'
126 ExprResult
Expr(ParseExpression());
127 if (Expr
.isInvalid()) {
128 // If the expression is invalid, skip ahead to the next semicolon or '}'.
129 // Not doing this opens us up to the possibility of infinite loops if
130 // ParseExpression does not consume any tokens.
131 SkipUntil(tok::r_brace
, /*StopAtSemi=*/true, /*DontConsume=*/true);
132 if (Tok
.is(tok::semi
))
136 // Otherwise, eat the semicolon.
137 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr
);
138 return Actions
.ActOnExprStmt(Actions
.MakeFullExpr(Expr
.get()));
141 case tok::kw_case
: // C99 6.8.1: labeled-statement
142 return ParseCaseStatement(attrs
);
143 case tok::kw_default
: // C99 6.8.1: labeled-statement
144 return ParseDefaultStatement(attrs
);
146 case tok::l_brace
: // C99 6.8.2: compound-statement
147 return ParseCompoundStatement(attrs
);
148 case tok::semi
: { // C99 6.8.3p3: expression[opt] ';'
149 bool LeadingEmptyMacro
= Tok
.hasLeadingEmptyMacro();
150 return Actions
.ActOnNullStmt(ConsumeToken(), LeadingEmptyMacro
);
153 case tok::kw_if
: // C99 6.8.4.1: if-statement
154 return ParseIfStatement(attrs
);
155 case tok::kw_switch
: // C99 6.8.4.2: switch-statement
156 return ParseSwitchStatement(attrs
);
158 case tok::kw_while
: // C99 6.8.5.1: while-statement
159 return ParseWhileStatement(attrs
);
160 case tok::kw_do
: // C99 6.8.5.2: do-statement
161 Res
= ParseDoStatement(attrs
);
162 SemiError
= "do/while";
164 case tok::kw_for
: // C99 6.8.5.3: for-statement
165 return ParseForStatement(attrs
);
167 case tok::kw_goto
: // C99 6.8.6.1: goto-statement
168 Res
= ParseGotoStatement(attrs
);
171 case tok::kw_continue
: // C99 6.8.6.2: continue-statement
172 Res
= ParseContinueStatement(attrs
);
173 SemiError
= "continue";
175 case tok::kw_break
: // C99 6.8.6.3: break-statement
176 Res
= ParseBreakStatement(attrs
);
179 case tok::kw_return
: // C99 6.8.6.4: return-statement
180 Res
= ParseReturnStatement(attrs
);
181 SemiError
= "return";
185 ProhibitAttributes(attrs
);
187 Res
= ParseAsmStatement(msAsm
);
188 Res
= Actions
.ActOnFinishFullStmt(Res
.get());
189 if (msAsm
) return move(Res
);
194 case tok::kw_try
: // C++ 15: try-block
195 return ParseCXXTryBlock(attrs
);
198 // If we reached this code, the statement must end in a semicolon.
199 if (Tok
.is(tok::semi
)) {
201 } else if (!Res
.isInvalid()) {
202 // If the result was valid, then we do want to diagnose this. Use
203 // ExpectAndConsume to emit the diagnostic, even though we know it won't
205 ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_stmt
, SemiError
);
206 // Skip until we see a } or ;, but don't eat it.
207 SkipUntil(tok::r_brace
, true, true);
213 /// ParseLabeledStatement - We have an identifier and a ':' after it.
215 /// labeled-statement:
216 /// identifier ':' statement
217 /// [GNU] identifier ':' attributes[opt] statement
219 StmtResult
Parser::ParseLabeledStatement(ParsedAttributes
&attrs
) {
220 assert(Tok
.is(tok::identifier
) && Tok
.getIdentifierInfo() &&
221 "Not an identifier!");
223 Token IdentTok
= Tok
; // Save the whole token.
224 ConsumeToken(); // eat the identifier.
226 assert(Tok
.is(tok::colon
) && "Not a label!");
228 // identifier ':' statement
229 SourceLocation ColonLoc
= ConsumeToken();
231 // Read label attributes, if present.
232 MaybeParseGNUAttributes(attrs
);
234 StmtResult
SubStmt(ParseStatement());
236 // Broken substmt shouldn't prevent the label from being added to the AST.
237 if (SubStmt
.isInvalid())
238 SubStmt
= Actions
.ActOnNullStmt(ColonLoc
);
240 return Actions
.ActOnLabelStmt(IdentTok
.getLocation(),
241 IdentTok
.getIdentifierInfo(),
242 ColonLoc
, SubStmt
.get(), attrs
.getList());
245 /// ParseCaseStatement
246 /// labeled-statement:
247 /// 'case' constant-expression ':' statement
248 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
250 StmtResult
Parser::ParseCaseStatement(ParsedAttributes
&attrs
) {
251 assert(Tok
.is(tok::kw_case
) && "Not a case stmt!");
252 // FIXME: Use attributes?
254 // It is very very common for code to contain many case statements recursively
255 // nested, as in (but usually without indentation):
262 // Parsing this naively works, but is both inefficient and can cause us to run
263 // out of stack space in our recursive descent parser. As a special case,
264 // flatten this recursion into an iterative loop. This is complex and gross,
265 // but all the grossness is constrained to ParseCaseStatement (and some
266 // wierdness in the actions), so this is just local grossness :).
268 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
270 StmtResult
TopLevelCase(true);
272 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
273 // gets updated each time a new case is parsed, and whose body is unset so
274 // far. When parsing 'case 4', this is the 'case 3' node.
275 StmtTy
*DeepestParsedCaseStmt
= 0;
277 // While we have case statements, eat and stack them.
279 SourceLocation CaseLoc
= ConsumeToken(); // eat the 'case'.
281 if (Tok
.is(tok::code_completion
)) {
282 Actions
.CodeCompleteCase(getCurScope());
283 ConsumeCodeCompletionToken();
286 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
287 /// Disable this form of error recovery while we're parsing the case
289 ColonProtectionRAIIObject
ColonProtection(*this);
291 ExprResult
LHS(ParseConstantExpression());
292 if (LHS
.isInvalid()) {
293 SkipUntil(tok::colon
);
297 // GNU case range extension.
298 SourceLocation DotDotDotLoc
;
300 if (Tok
.is(tok::ellipsis
)) {
301 Diag(Tok
, diag::ext_gnu_case_range
);
302 DotDotDotLoc
= ConsumeToken();
304 RHS
= ParseConstantExpression();
305 if (RHS
.isInvalid()) {
306 SkipUntil(tok::colon
);
311 ColonProtection
.restore();
313 SourceLocation ColonLoc
;
314 if (Tok
.is(tok::colon
)) {
315 ColonLoc
= ConsumeToken();
317 // Treat "case blah;" as a typo for "case blah:".
318 } else if (Tok
.is(tok::semi
)) {
319 ColonLoc
= ConsumeToken();
320 Diag(ColonLoc
, diag::err_expected_colon_after
) << "'case'"
321 << FixItHint::CreateReplacement(ColonLoc
, ":");
323 SourceLocation ExpectedLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
324 Diag(ExpectedLoc
, diag::err_expected_colon_after
) << "'case'"
325 << FixItHint::CreateInsertion(ExpectedLoc
, ":");
326 ColonLoc
= ExpectedLoc
;
330 Actions
.ActOnCaseStmt(CaseLoc
, LHS
.get(), DotDotDotLoc
,
331 RHS
.get(), ColonLoc
);
333 // If we had a sema error parsing this case, then just ignore it and
334 // continue parsing the sub-stmt.
335 if (Case
.isInvalid()) {
336 if (TopLevelCase
.isInvalid()) // No parsed case stmts.
337 return ParseStatement();
338 // Otherwise, just don't add it as a nested case.
340 // If this is the first case statement we parsed, it becomes TopLevelCase.
341 // Otherwise we link it into the current chain.
342 Stmt
*NextDeepest
= Case
.get();
343 if (TopLevelCase
.isInvalid())
344 TopLevelCase
= move(Case
);
346 Actions
.ActOnCaseStmtBody(DeepestParsedCaseStmt
, Case
.get());
347 DeepestParsedCaseStmt
= NextDeepest
;
350 // Handle all case statements.
351 } while (Tok
.is(tok::kw_case
));
353 assert(!TopLevelCase
.isInvalid() && "Should have parsed at least one case!");
355 // If we found a non-case statement, start by parsing it.
358 if (Tok
.isNot(tok::r_brace
)) {
359 SubStmt
= ParseStatement();
361 // Nicely diagnose the common error "switch (X) { case 4: }", which is
363 // FIXME: add insertion hint.
364 Diag(Tok
, diag::err_label_end_of_compound_statement
);
368 // Broken sub-stmt shouldn't prevent forming the case statement properly.
369 if (SubStmt
.isInvalid())
370 SubStmt
= Actions
.ActOnNullStmt(SourceLocation());
372 // Install the body into the most deeply-nested case.
373 Actions
.ActOnCaseStmtBody(DeepestParsedCaseStmt
, SubStmt
.get());
375 // Return the top level parsed statement tree.
376 return move(TopLevelCase
);
379 /// ParseDefaultStatement
380 /// labeled-statement:
381 /// 'default' ':' statement
382 /// Note that this does not parse the 'statement' at the end.
384 StmtResult
Parser::ParseDefaultStatement(ParsedAttributes
&attrs
) {
385 //FIXME: Use attributes?
387 assert(Tok
.is(tok::kw_default
) && "Not a default stmt!");
388 SourceLocation DefaultLoc
= ConsumeToken(); // eat the 'default'.
390 SourceLocation ColonLoc
;
391 if (Tok
.is(tok::colon
)) {
392 ColonLoc
= ConsumeToken();
394 // Treat "default;" as a typo for "default:".
395 } else if (Tok
.is(tok::semi
)) {
396 ColonLoc
= ConsumeToken();
397 Diag(ColonLoc
, diag::err_expected_colon_after
) << "'default'"
398 << FixItHint::CreateReplacement(ColonLoc
, ":");
400 SourceLocation ExpectedLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
401 Diag(ExpectedLoc
, diag::err_expected_colon_after
) << "'default'"
402 << FixItHint::CreateInsertion(ExpectedLoc
, ":");
403 ColonLoc
= ExpectedLoc
;
406 // Diagnose the common error "switch (X) {... default: }", which is not valid.
407 if (Tok
.is(tok::r_brace
)) {
408 Diag(Tok
, diag::err_label_end_of_compound_statement
);
412 StmtResult
SubStmt(ParseStatement());
413 if (SubStmt
.isInvalid())
416 return Actions
.ActOnDefaultStmt(DefaultLoc
, ColonLoc
,
417 SubStmt
.get(), getCurScope());
421 /// ParseCompoundStatement - Parse a "{}" block.
423 /// compound-statement: [C99 6.8.2]
424 /// { block-item-list[opt] }
425 /// [GNU] { label-declarations block-item-list } [TODO]
429 /// block-item-list block-item
433 /// [GNU] '__extension__' declaration
435 /// [OMP] openmp-directive [TODO]
437 /// [GNU] label-declarations:
438 /// [GNU] label-declaration
439 /// [GNU] label-declarations label-declaration
441 /// [GNU] label-declaration:
442 /// [GNU] '__label__' identifier-list ';'
444 /// [OMP] openmp-directive: [TODO]
445 /// [OMP] barrier-directive
446 /// [OMP] flush-directive
448 StmtResult
Parser::ParseCompoundStatement(ParsedAttributes
&attrs
,
450 //FIXME: Use attributes?
452 assert(Tok
.is(tok::l_brace
) && "Not a compount stmt!");
454 // Enter a scope to hold everything within the compound stmt. Compound
455 // statements can always hold declarations.
456 ParseScope
CompoundScope(this, Scope::DeclScope
);
458 // Parse the statements in the body.
459 return ParseCompoundStatementBody(isStmtExpr
);
463 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
464 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
465 /// consume the '}' at the end of the block. It does not manipulate the scope
467 StmtResult
Parser::ParseCompoundStatementBody(bool isStmtExpr
) {
468 PrettyStackTraceLoc
CrashInfo(PP
.getSourceManager(),
470 "in compound statement ('{}')");
471 InMessageExpressionRAIIObject
InMessage(*this, false);
473 SourceLocation LBraceLoc
= ConsumeBrace(); // eat the '{'.
475 // TODO: "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
476 // only allowed at the start of a compound stmt regardless of the language.
478 StmtVector
Stmts(Actions
);
479 while (Tok
.isNot(tok::r_brace
) && Tok
.isNot(tok::eof
)) {
481 if (Tok
.is(tok::annot_pragma_unused
)) {
482 HandlePragmaUnused();
487 if (Tok
.isNot(tok::kw___extension__
)) {
488 R
= ParseStatementOrDeclaration(Stmts
, false);
490 // __extension__ can start declarations and it can also be a unary
491 // operator for expressions. Consume multiple __extension__ markers here
492 // until we can determine which is which.
493 // FIXME: This loses extension expressions in the AST!
494 SourceLocation ExtLoc
= ConsumeToken();
495 while (Tok
.is(tok::kw___extension__
))
498 ParsedAttributesWithRange attrs
;
499 MaybeParseCXX0XAttributes(attrs
);
501 // If this is the start of a declaration, parse it as such.
502 if (isDeclarationStatement()) {
503 // __extension__ silences extension warnings in the subdeclaration.
504 // FIXME: Save the __extension__ on the decl as a node somehow?
505 ExtensionRAIIObject
O(Diags
);
507 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
508 DeclGroupPtrTy Res
= ParseDeclaration(Stmts
,
509 Declarator::BlockContext
, DeclEnd
,
511 R
= Actions
.ActOnDeclStmt(Res
, DeclStart
, DeclEnd
);
513 // Otherwise this was a unary __extension__ marker.
514 ExprResult
Res(ParseExpressionWithLeadingExtension(ExtLoc
));
516 if (Res
.isInvalid()) {
517 SkipUntil(tok::semi
);
521 // FIXME: Use attributes?
522 // Eat the semicolon at the end of stmt and convert the expr into a
524 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr
);
525 R
= Actions
.ActOnExprStmt(Actions
.MakeFullExpr(Res
.get()));
530 Stmts
.push_back(R
.release());
533 // We broke out of the while loop because we found a '}' or EOF.
534 if (Tok
.isNot(tok::r_brace
)) {
535 Diag(Tok
, diag::err_expected_rbrace
);
536 Diag(LBraceLoc
, diag::note_matching
) << "{";
540 SourceLocation RBraceLoc
= ConsumeBrace();
541 return Actions
.ActOnCompoundStmt(LBraceLoc
, RBraceLoc
, move_arg(Stmts
),
545 /// ParseParenExprOrCondition:
546 /// [C ] '(' expression ')'
547 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
549 /// This function parses and performs error recovery on the specified condition
550 /// or expression (depending on whether we're in C++ or C mode). This function
551 /// goes out of its way to recover well. It returns true if there was a parser
552 /// error (the right paren couldn't be found), which indicates that the caller
553 /// should try to recover harder. It returns false if the condition is
554 /// successfully parsed. Note that a successful parse can still have semantic
555 /// errors in the condition.
556 bool Parser::ParseParenExprOrCondition(ExprResult
&ExprResult
,
559 bool ConvertToBoolean
) {
560 SourceLocation LParenLoc
= ConsumeParen();
561 if (getLang().CPlusPlus
)
562 ParseCXXCondition(ExprResult
, DeclResult
, Loc
, ConvertToBoolean
);
564 ExprResult
= ParseExpression();
567 // If required, convert to a boolean value.
568 if (!ExprResult
.isInvalid() && ConvertToBoolean
)
570 = Actions
.ActOnBooleanCondition(getCurScope(), Loc
, ExprResult
.get());
573 // If the parser was confused by the condition and we don't have a ')', try to
574 // recover by skipping ahead to a semi and bailing out. If condexp is
575 // semantically invalid but we have well formed code, keep going.
576 if (ExprResult
.isInvalid() && !DeclResult
&& Tok
.isNot(tok::r_paren
)) {
577 SkipUntil(tok::semi
);
578 // Skipping may have stopped if it found the containing ')'. If so, we can
579 // continue parsing the if statement.
580 if (Tok
.isNot(tok::r_paren
))
584 // Otherwise the condition is valid or the rparen is present.
585 MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
591 /// if-statement: [C99 6.8.4.1]
592 /// 'if' '(' expression ')' statement
593 /// 'if' '(' expression ')' statement 'else' statement
594 /// [C++] 'if' '(' condition ')' statement
595 /// [C++] 'if' '(' condition ')' statement 'else' statement
597 StmtResult
Parser::ParseIfStatement(ParsedAttributes
&attrs
) {
598 // FIXME: Use attributes?
600 assert(Tok
.is(tok::kw_if
) && "Not an if stmt!");
601 SourceLocation IfLoc
= ConsumeToken(); // eat the 'if'.
603 if (Tok
.isNot(tok::l_paren
)) {
604 Diag(Tok
, diag::err_expected_lparen_after
) << "if";
605 SkipUntil(tok::semi
);
609 bool C99orCXX
= getLang().C99
|| getLang().CPlusPlus
;
611 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
615 // A name introduced by a declaration in a condition is in scope from its
616 // point of declaration until the end of the substatements controlled by the
619 // Names declared in the for-init-statement, and in the condition of if,
620 // while, for, and switch statements are local to the if, while, for, or
621 // switch statement (including the controlled statement).
623 ParseScope
IfScope(this, Scope::DeclScope
| Scope::ControlScope
, C99orCXX
);
625 // Parse the condition.
628 if (ParseParenExprOrCondition(CondExp
, CondVar
, IfLoc
, true))
631 FullExprArg
FullCondExp(Actions
.MakeFullExpr(CondExp
.get()));
633 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
634 // there is no compound stmt. C90 does not have this clause. We only do this
635 // if the body isn't a compound statement to avoid push/pop in common cases.
638 // The substatement in a selection-statement (each substatement, in the else
639 // form of the if statement) implicitly defines a local scope.
641 // For C++ we create a scope for the condition and a new scope for
642 // substatements because:
643 // -When the 'then' scope exits, we want the condition declaration to still be
644 // active for the 'else' scope too.
645 // -Sema will detect name clashes by considering declarations of a
646 // 'ControlScope' as part of its direct subscope.
647 // -If we wanted the condition and substatement to be in the same scope, we
648 // would have to notify ParseStatement not to create a new scope. It's
649 // simpler to let it create a new scope.
651 ParseScope
InnerScope(this, Scope::DeclScope
,
652 C99orCXX
&& Tok
.isNot(tok::l_brace
));
654 // Read the 'then' stmt.
655 SourceLocation ThenStmtLoc
= Tok
.getLocation();
656 StmtResult
ThenStmt(ParseStatement());
658 // Pop the 'if' scope if needed.
661 // If it has an else, parse it.
662 SourceLocation ElseLoc
;
663 SourceLocation ElseStmtLoc
;
666 if (Tok
.is(tok::kw_else
)) {
667 ElseLoc
= ConsumeToken();
668 ElseStmtLoc
= Tok
.getLocation();
670 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
671 // there is no compound stmt. C90 does not have this clause. We only do
672 // this if the body isn't a compound statement to avoid push/pop in common
676 // The substatement in a selection-statement (each substatement, in the else
677 // form of the if statement) implicitly defines a local scope.
679 ParseScope
InnerScope(this, Scope::DeclScope
,
680 C99orCXX
&& Tok
.isNot(tok::l_brace
));
682 ElseStmt
= ParseStatement();
684 // Pop the 'else' scope if needed.
690 // If the condition was invalid, discard the if statement. We could recover
691 // better by replacing it with a valid expr, but don't do that yet.
692 if (CondExp
.isInvalid() && !CondVar
)
695 // If the then or else stmt is invalid and the other is valid (and present),
696 // make turn the invalid one into a null stmt to avoid dropping the other
697 // part. If both are invalid, return error.
698 if ((ThenStmt
.isInvalid() && ElseStmt
.isInvalid()) ||
699 (ThenStmt
.isInvalid() && ElseStmt
.get() == 0) ||
700 (ThenStmt
.get() == 0 && ElseStmt
.isInvalid())) {
701 // Both invalid, or one is invalid and other is non-present: return error.
705 // Now if either are invalid, replace with a ';'.
706 if (ThenStmt
.isInvalid())
707 ThenStmt
= Actions
.ActOnNullStmt(ThenStmtLoc
);
708 if (ElseStmt
.isInvalid())
709 ElseStmt
= Actions
.ActOnNullStmt(ElseStmtLoc
);
711 return Actions
.ActOnIfStmt(IfLoc
, FullCondExp
, CondVar
, ThenStmt
.get(),
712 ElseLoc
, ElseStmt
.get());
715 /// ParseSwitchStatement
716 /// switch-statement:
717 /// 'switch' '(' expression ')' statement
718 /// [C++] 'switch' '(' condition ')' statement
719 StmtResult
Parser::ParseSwitchStatement(ParsedAttributes
&attrs
) {
720 // FIXME: Use attributes?
722 assert(Tok
.is(tok::kw_switch
) && "Not a switch stmt!");
723 SourceLocation SwitchLoc
= ConsumeToken(); // eat the 'switch'.
725 if (Tok
.isNot(tok::l_paren
)) {
726 Diag(Tok
, diag::err_expected_lparen_after
) << "switch";
727 SkipUntil(tok::semi
);
731 bool C99orCXX
= getLang().C99
|| getLang().CPlusPlus
;
733 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
734 // not the case for C90. Start the switch scope.
737 // A name introduced by a declaration in a condition is in scope from its
738 // point of declaration until the end of the substatements controlled by the
741 // Names declared in the for-init-statement, and in the condition of if,
742 // while, for, and switch statements are local to the if, while, for, or
743 // switch statement (including the controlled statement).
745 unsigned ScopeFlags
= Scope::BreakScope
;
747 ScopeFlags
|= Scope::DeclScope
| Scope::ControlScope
;
748 ParseScope
SwitchScope(this, ScopeFlags
);
750 // Parse the condition.
753 if (ParseParenExprOrCondition(Cond
, CondVar
, SwitchLoc
, false))
757 = Actions
.ActOnStartOfSwitchStmt(SwitchLoc
, Cond
.get(), CondVar
);
759 if (Switch
.isInvalid()) {
760 // Skip the switch body.
761 // FIXME: This is not optimal recovery, but parsing the body is more
762 // dangerous due to the presence of case and default statements, which
763 // will have no place to connect back with the switch.
764 if (Tok
.is(tok::l_brace
)) {
766 SkipUntil(tok::r_brace
, false, false);
768 SkipUntil(tok::semi
);
772 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
773 // there is no compound stmt. C90 does not have this clause. We only do this
774 // if the body isn't a compound statement to avoid push/pop in common cases.
777 // The substatement in a selection-statement (each substatement, in the else
778 // form of the if statement) implicitly defines a local scope.
780 // See comments in ParseIfStatement for why we create a scope for the
781 // condition and a new scope for substatement in C++.
783 ParseScope
InnerScope(this, Scope::DeclScope
,
784 C99orCXX
&& Tok
.isNot(tok::l_brace
));
786 // Read the body statement.
787 StmtResult
Body(ParseStatement());
793 if (Body
.isInvalid())
794 // FIXME: Remove the case statement list from the Switch statement.
795 Body
= Actions
.ActOnNullStmt(Tok
.getLocation());
797 return Actions
.ActOnFinishSwitchStmt(SwitchLoc
, Switch
.get(), Body
.get());
800 /// ParseWhileStatement
801 /// while-statement: [C99 6.8.5.1]
802 /// 'while' '(' expression ')' statement
803 /// [C++] 'while' '(' condition ')' statement
804 StmtResult
Parser::ParseWhileStatement(ParsedAttributes
&attrs
) {
805 // FIXME: Use attributes?
807 assert(Tok
.is(tok::kw_while
) && "Not a while stmt!");
808 SourceLocation WhileLoc
= Tok
.getLocation();
809 ConsumeToken(); // eat the 'while'.
811 if (Tok
.isNot(tok::l_paren
)) {
812 Diag(Tok
, diag::err_expected_lparen_after
) << "while";
813 SkipUntil(tok::semi
);
817 bool C99orCXX
= getLang().C99
|| getLang().CPlusPlus
;
819 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
820 // the case for C90. Start the loop scope.
823 // A name introduced by a declaration in a condition is in scope from its
824 // point of declaration until the end of the substatements controlled by the
827 // Names declared in the for-init-statement, and in the condition of if,
828 // while, for, and switch statements are local to the if, while, for, or
829 // switch statement (including the controlled statement).
833 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
|
834 Scope::DeclScope
| Scope::ControlScope
;
836 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
837 ParseScope
WhileScope(this, ScopeFlags
);
839 // Parse the condition.
842 if (ParseParenExprOrCondition(Cond
, CondVar
, WhileLoc
, true))
845 FullExprArg
FullCond(Actions
.MakeFullExpr(Cond
.get()));
847 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
848 // there is no compound stmt. C90 does not have this clause. We only do this
849 // if the body isn't a compound statement to avoid push/pop in common cases.
852 // The substatement in an iteration-statement implicitly defines a local scope
853 // which is entered and exited each time through the loop.
855 // See comments in ParseIfStatement for why we create a scope for the
856 // condition and a new scope for substatement in C++.
858 ParseScope
InnerScope(this, Scope::DeclScope
,
859 C99orCXX
&& Tok
.isNot(tok::l_brace
));
861 // Read the body statement.
862 StmtResult
Body(ParseStatement());
864 // Pop the body scope if needed.
868 if ((Cond
.isInvalid() && !CondVar
) || Body
.isInvalid())
871 return Actions
.ActOnWhileStmt(WhileLoc
, FullCond
, CondVar
, Body
.get());
875 /// do-statement: [C99 6.8.5.2]
876 /// 'do' statement 'while' '(' expression ')' ';'
877 /// Note: this lets the caller parse the end ';'.
878 StmtResult
Parser::ParseDoStatement(ParsedAttributes
&attrs
) {
879 // FIXME: Use attributes?
881 assert(Tok
.is(tok::kw_do
) && "Not a do stmt!");
882 SourceLocation DoLoc
= ConsumeToken(); // eat the 'do'.
884 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
885 // the case for C90. Start the loop scope.
888 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
| Scope::DeclScope
;
890 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
892 ParseScope
DoScope(this, ScopeFlags
);
894 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
895 // there is no compound stmt. C90 does not have this clause. We only do this
896 // if the body isn't a compound statement to avoid push/pop in common cases.
899 // The substatement in an iteration-statement implicitly defines a local scope
900 // which is entered and exited each time through the loop.
902 ParseScope
InnerScope(this, Scope::DeclScope
,
903 (getLang().C99
|| getLang().CPlusPlus
) &&
904 Tok
.isNot(tok::l_brace
));
906 // Read the body statement.
907 StmtResult
Body(ParseStatement());
909 // Pop the body scope if needed.
912 if (Tok
.isNot(tok::kw_while
)) {
913 if (!Body
.isInvalid()) {
914 Diag(Tok
, diag::err_expected_while
);
915 Diag(DoLoc
, diag::note_matching
) << "do";
916 SkipUntil(tok::semi
, false, true);
920 SourceLocation WhileLoc
= ConsumeToken();
922 if (Tok
.isNot(tok::l_paren
)) {
923 Diag(Tok
, diag::err_expected_lparen_after
) << "do/while";
924 SkipUntil(tok::semi
, false, true);
928 // Parse the parenthesized condition.
929 SourceLocation LPLoc
= ConsumeParen();
930 ExprResult Cond
= ParseExpression();
931 SourceLocation RPLoc
= MatchRHSPunctuation(tok::r_paren
, LPLoc
);
934 if (Cond
.isInvalid() || Body
.isInvalid())
937 return Actions
.ActOnDoStmt(DoLoc
, Body
.get(), WhileLoc
, LPLoc
,
941 /// ParseForStatement
942 /// for-statement: [C99 6.8.5.3]
943 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
944 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
945 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
947 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
948 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
950 /// [C++] for-init-statement:
951 /// [C++] expression-statement
952 /// [C++] simple-declaration
954 StmtResult
Parser::ParseForStatement(ParsedAttributes
&attrs
) {
955 // FIXME: Use attributes?
957 assert(Tok
.is(tok::kw_for
) && "Not a for stmt!");
958 SourceLocation ForLoc
= ConsumeToken(); // eat the 'for'.
960 if (Tok
.isNot(tok::l_paren
)) {
961 Diag(Tok
, diag::err_expected_lparen_after
) << "for";
962 SkipUntil(tok::semi
);
966 bool C99orCXXorObjC
= getLang().C99
|| getLang().CPlusPlus
|| getLang().ObjC1
;
968 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
969 // the case for C90. Start the loop scope.
972 // A name introduced by a declaration in a condition is in scope from its
973 // point of declaration until the end of the substatements controlled by the
976 // Names declared in the for-init-statement, and in the condition of if,
977 // while, for, and switch statements are local to the if, while, for, or
978 // switch statement (including the controlled statement).
980 // Names declared in the for-init-statement are in the same declarative-region
981 // as those declared in the condition.
985 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
|
986 Scope::DeclScope
| Scope::ControlScope
;
988 ScopeFlags
= Scope::BreakScope
| Scope::ContinueScope
;
990 ParseScope
ForScope(this, ScopeFlags
);
992 SourceLocation LParenLoc
= ConsumeParen();
995 bool ForEach
= false;
996 StmtResult FirstPart
;
997 bool SecondPartIsInvalid
= false;
998 FullExprArg
SecondPart(Actions
);
999 ExprResult Collection
;
1000 FullExprArg
ThirdPart(Actions
);
1001 Decl
*SecondVar
= 0;
1003 if (Tok
.is(tok::code_completion
)) {
1004 Actions
.CodeCompleteOrdinaryName(getCurScope(),
1005 C99orCXXorObjC
? Sema::PCC_ForInit
1006 : Sema::PCC_Expression
);
1007 ConsumeCodeCompletionToken();
1010 // Parse the first part of the for specifier.
1011 if (Tok
.is(tok::semi
)) { // for (;
1012 // no first part, eat the ';'.
1014 } else if (isSimpleDeclaration()) { // for (int X = 4;
1015 // Parse declaration, which eats the ';'.
1016 if (!C99orCXXorObjC
) // Use of C99-style for loops in C90 mode?
1017 Diag(Tok
, diag::ext_c99_variable_decl_in_for_loop
);
1019 ParsedAttributesWithRange attrs
;
1020 MaybeParseCXX0XAttributes(attrs
);
1022 SourceLocation DeclStart
= Tok
.getLocation(), DeclEnd
;
1023 StmtVector
Stmts(Actions
);
1024 DeclGroupPtrTy DG
= ParseSimpleDeclaration(Stmts
, Declarator::ForContext
,
1025 DeclEnd
, attrs
, false);
1026 FirstPart
= Actions
.ActOnDeclStmt(DG
, DeclStart
, Tok
.getLocation());
1028 if (Tok
.is(tok::semi
)) { // for (int x = 4;
1030 } else if ((ForEach
= isTokIdentifier_in())) {
1031 Actions
.ActOnForEachDeclStmt(DG
);
1032 // ObjC: for (id x in expr)
1033 ConsumeToken(); // consume 'in'
1035 if (Tok
.is(tok::code_completion
)) {
1036 Actions
.CodeCompleteObjCForCollection(getCurScope(), DG
);
1037 ConsumeCodeCompletionToken();
1039 Collection
= ParseExpression();
1041 Diag(Tok
, diag::err_expected_semi_for
);
1042 SkipUntil(tok::semi
);
1045 Value
= ParseExpression();
1047 ForEach
= isTokIdentifier_in();
1049 // Turn the expression into a stmt.
1050 if (!Value
.isInvalid()) {
1052 FirstPart
= Actions
.ActOnForEachLValueExpr(Value
.get());
1054 FirstPart
= Actions
.ActOnExprStmt(Actions
.MakeFullExpr(Value
.get()));
1057 if (Tok
.is(tok::semi
)) {
1059 } else if (ForEach
) {
1060 ConsumeToken(); // consume 'in'
1062 if (Tok
.is(tok::code_completion
)) {
1063 Actions
.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1064 ConsumeCodeCompletionToken();
1066 Collection
= ParseExpression();
1068 if (!Value
.isInvalid()) Diag(Tok
, diag::err_expected_semi_for
);
1069 SkipUntil(tok::semi
);
1073 assert(!SecondPart
.get() && "Shouldn't have a second expression yet.");
1074 // Parse the second part of the for specifier.
1075 if (Tok
.is(tok::semi
)) { // for (...;;
1079 if (getLang().CPlusPlus
)
1080 ParseCXXCondition(Second
, SecondVar
, ForLoc
, true);
1082 Second
= ParseExpression();
1083 if (!Second
.isInvalid())
1084 Second
= Actions
.ActOnBooleanCondition(getCurScope(), ForLoc
,
1087 SecondPartIsInvalid
= Second
.isInvalid();
1088 SecondPart
= Actions
.MakeFullExpr(Second
.get());
1091 if (Tok
.is(tok::semi
)) {
1094 if (!SecondPartIsInvalid
|| SecondVar
)
1095 Diag(Tok
, diag::err_expected_semi_for
);
1096 SkipUntil(tok::semi
);
1099 // Parse the third part of the for specifier.
1100 if (Tok
.isNot(tok::r_paren
)) { // for (...;...;)
1101 ExprResult Third
= ParseExpression();
1102 ThirdPart
= Actions
.MakeFullExpr(Third
.take());
1106 SourceLocation RParenLoc
= MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
1108 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1109 // there is no compound stmt. C90 does not have this clause. We only do this
1110 // if the body isn't a compound statement to avoid push/pop in common cases.
1113 // The substatement in an iteration-statement implicitly defines a local scope
1114 // which is entered and exited each time through the loop.
1116 // See comments in ParseIfStatement for why we create a scope for
1117 // for-init-statement/condition and a new scope for substatement in C++.
1119 ParseScope
InnerScope(this, Scope::DeclScope
,
1120 C99orCXXorObjC
&& Tok
.isNot(tok::l_brace
));
1122 // Read the body statement.
1123 StmtResult
Body(ParseStatement());
1125 // Pop the body scope if needed.
1128 // Leave the for-scope.
1131 if (Body
.isInvalid())
1135 return Actions
.ActOnForStmt(ForLoc
, LParenLoc
, FirstPart
.take(), SecondPart
,
1136 SecondVar
, ThirdPart
, RParenLoc
, Body
.take());
1138 // FIXME: It isn't clear how to communicate the late destruction of
1139 // C++ temporaries used to create the collection.
1140 return Actions
.ActOnObjCForCollectionStmt(ForLoc
, LParenLoc
, FirstPart
.take(),
1141 Collection
.take(), RParenLoc
,
1145 /// ParseGotoStatement
1147 /// 'goto' identifier ';'
1148 /// [GNU] 'goto' '*' expression ';'
1150 /// Note: this lets the caller parse the end ';'.
1152 StmtResult
Parser::ParseGotoStatement(ParsedAttributes
&attrs
) {
1153 // FIXME: Use attributes?
1155 assert(Tok
.is(tok::kw_goto
) && "Not a goto stmt!");
1156 SourceLocation GotoLoc
= ConsumeToken(); // eat the 'goto'.
1159 if (Tok
.is(tok::identifier
)) {
1160 Res
= Actions
.ActOnGotoStmt(GotoLoc
, Tok
.getLocation(),
1161 Tok
.getIdentifierInfo());
1163 } else if (Tok
.is(tok::star
)) {
1164 // GNU indirect goto extension.
1165 Diag(Tok
, diag::ext_gnu_indirect_goto
);
1166 SourceLocation StarLoc
= ConsumeToken();
1167 ExprResult
R(ParseExpression());
1168 if (R
.isInvalid()) { // Skip to the semicolon, but don't consume it.
1169 SkipUntil(tok::semi
, false, true);
1172 Res
= Actions
.ActOnIndirectGotoStmt(GotoLoc
, StarLoc
, R
.take());
1174 Diag(Tok
, diag::err_expected_ident
);
1181 /// ParseContinueStatement
1185 /// Note: this lets the caller parse the end ';'.
1187 StmtResult
Parser::ParseContinueStatement(ParsedAttributes
&attrs
) {
1188 // FIXME: Use attributes?
1190 SourceLocation ContinueLoc
= ConsumeToken(); // eat the 'continue'.
1191 return Actions
.ActOnContinueStmt(ContinueLoc
, getCurScope());
1194 /// ParseBreakStatement
1198 /// Note: this lets the caller parse the end ';'.
1200 StmtResult
Parser::ParseBreakStatement(ParsedAttributes
&attrs
) {
1201 // FIXME: Use attributes?
1203 SourceLocation BreakLoc
= ConsumeToken(); // eat the 'break'.
1204 return Actions
.ActOnBreakStmt(BreakLoc
, getCurScope());
1207 /// ParseReturnStatement
1209 /// 'return' expression[opt] ';'
1210 StmtResult
Parser::ParseReturnStatement(ParsedAttributes
&attrs
) {
1211 // FIXME: Use attributes?
1213 assert(Tok
.is(tok::kw_return
) && "Not a return stmt!");
1214 SourceLocation ReturnLoc
= ConsumeToken(); // eat the 'return'.
1217 if (Tok
.isNot(tok::semi
)) {
1218 if (Tok
.is(tok::code_completion
)) {
1219 Actions
.CodeCompleteReturn(getCurScope());
1220 ConsumeCodeCompletionToken();
1221 SkipUntil(tok::semi
, false, true);
1225 R
= ParseExpression();
1226 if (R
.isInvalid()) { // Skip to the semicolon, but don't consume it.
1227 SkipUntil(tok::semi
, false, true);
1231 return Actions
.ActOnReturnStmt(ReturnLoc
, R
.take());
1234 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1235 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1236 StmtResult
Parser::FuzzyParseMicrosoftAsmStatement(SourceLocation AsmLoc
) {
1237 SourceLocation EndLoc
;
1238 if (Tok
.is(tok::l_brace
)) {
1239 unsigned short savedBraceCount
= BraceCount
;
1241 EndLoc
= Tok
.getLocation();
1243 } while (BraceCount
> savedBraceCount
&& Tok
.isNot(tok::eof
));
1245 // From the MS website: If used without braces, the __asm keyword means
1246 // that the rest of the line is an assembly-language statement.
1247 SourceManager
&SrcMgr
= PP
.getSourceManager();
1248 SourceLocation TokLoc
= Tok
.getLocation();
1249 unsigned LineNo
= SrcMgr
.getInstantiationLineNumber(TokLoc
);
1253 TokLoc
= Tok
.getLocation();
1254 } while ((SrcMgr
.getInstantiationLineNumber(TokLoc
) == LineNo
) &&
1255 Tok
.isNot(tok::r_brace
) && Tok
.isNot(tok::semi
) &&
1256 Tok
.isNot(tok::eof
));
1259 t
.setKind(tok::string_literal
);
1260 t
.setLiteralData("\"/*FIXME: not done*/\"");
1261 t
.clearFlag(Token::NeedsCleaning
);
1263 ExprResult
AsmString(Actions
.ActOnStringLiteral(&t
, 1));
1264 ExprVector
Constraints(Actions
);
1265 ExprVector
Exprs(Actions
);
1266 ExprVector
Clobbers(Actions
);
1267 return Actions
.ActOnAsmStmt(AsmLoc
, true, true, 0, 0, 0,
1268 move_arg(Constraints
), move_arg(Exprs
),
1269 AsmString
.take(), move_arg(Clobbers
),
1273 /// ParseAsmStatement - Parse a GNU extended asm statement.
1275 /// gnu-asm-statement
1276 /// ms-asm-statement
1278 /// [GNU] gnu-asm-statement:
1279 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1281 /// [GNU] asm-argument:
1282 /// asm-string-literal
1283 /// asm-string-literal ':' asm-operands[opt]
1284 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1285 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1286 /// ':' asm-clobbers
1288 /// [GNU] asm-clobbers:
1289 /// asm-string-literal
1290 /// asm-clobbers ',' asm-string-literal
1292 /// [MS] ms-asm-statement:
1293 /// '__asm' assembly-instruction ';'[opt]
1294 /// '__asm' '{' assembly-instruction-list '}' ';'[opt]
1296 /// [MS] assembly-instruction-list:
1297 /// assembly-instruction ';'[opt]
1298 /// assembly-instruction-list ';' assembly-instruction ';'[opt]
1300 StmtResult
Parser::ParseAsmStatement(bool &msAsm
) {
1301 assert(Tok
.is(tok::kw_asm
) && "Not an asm stmt");
1302 SourceLocation AsmLoc
= ConsumeToken();
1304 if (getLang().Microsoft
&& Tok
.isNot(tok::l_paren
) && !isTypeQualifier()) {
1306 return FuzzyParseMicrosoftAsmStatement(AsmLoc
);
1309 SourceLocation Loc
= Tok
.getLocation();
1310 ParseTypeQualifierListOpt(DS
, true, false);
1312 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1313 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
1314 Diag(Loc
, diag::w_asm_qualifier_ignored
) << "const";
1315 if (DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
)
1316 Diag(Loc
, diag::w_asm_qualifier_ignored
) << "restrict";
1318 // Remember if this was a volatile asm.
1319 bool isVolatile
= DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
;
1320 if (Tok
.isNot(tok::l_paren
)) {
1321 Diag(Tok
, diag::err_expected_lparen_after
) << "asm";
1322 SkipUntil(tok::r_paren
);
1325 Loc
= ConsumeParen();
1327 ExprResult
AsmString(ParseAsmStringLiteral());
1328 if (AsmString
.isInvalid())
1331 llvm::SmallVector
<IdentifierInfo
*, 4> Names
;
1332 ExprVector
Constraints(Actions
);
1333 ExprVector
Exprs(Actions
);
1334 ExprVector
Clobbers(Actions
);
1336 if (Tok
.is(tok::r_paren
)) {
1337 // We have a simple asm expression like 'asm("foo")'.
1338 SourceLocation RParenLoc
= ConsumeParen();
1339 return Actions
.ActOnAsmStmt(AsmLoc
, /*isSimple*/ true, isVolatile
,
1340 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1341 move_arg(Constraints
), move_arg(Exprs
),
1342 AsmString
.take(), move_arg(Clobbers
),
1346 // Parse Outputs, if present.
1347 bool AteExtraColon
= false;
1348 if (Tok
.is(tok::colon
) || Tok
.is(tok::coloncolon
)) {
1349 // In C++ mode, parse "::" like ": :".
1350 AteExtraColon
= Tok
.is(tok::coloncolon
);
1353 if (!AteExtraColon
&&
1354 ParseAsmOperandsOpt(Names
, Constraints
, Exprs
))
1358 unsigned NumOutputs
= Names
.size();
1360 // Parse Inputs, if present.
1361 if (AteExtraColon
||
1362 Tok
.is(tok::colon
) || Tok
.is(tok::coloncolon
)) {
1363 // In C++ mode, parse "::" like ": :".
1365 AteExtraColon
= false;
1367 AteExtraColon
= Tok
.is(tok::coloncolon
);
1371 if (!AteExtraColon
&&
1372 ParseAsmOperandsOpt(Names
, Constraints
, Exprs
))
1376 assert(Names
.size() == Constraints
.size() &&
1377 Constraints
.size() == Exprs
.size() &&
1378 "Input operand size mismatch!");
1380 unsigned NumInputs
= Names
.size() - NumOutputs
;
1382 // Parse the clobbers, if present.
1383 if (AteExtraColon
|| Tok
.is(tok::colon
)) {
1387 // Parse the asm-string list for clobbers if present.
1388 if (Tok
.isNot(tok::r_paren
)) {
1390 ExprResult
Clobber(ParseAsmStringLiteral());
1392 if (Clobber
.isInvalid())
1395 Clobbers
.push_back(Clobber
.release());
1397 if (Tok
.isNot(tok::comma
)) break;
1403 SourceLocation RParenLoc
= MatchRHSPunctuation(tok::r_paren
, Loc
);
1404 return Actions
.ActOnAsmStmt(AsmLoc
, false, isVolatile
,
1405 NumOutputs
, NumInputs
, Names
.data(),
1406 move_arg(Constraints
), move_arg(Exprs
),
1407 AsmString
.take(), move_arg(Clobbers
),
1411 /// ParseAsmOperands - Parse the asm-operands production as used by
1412 /// asm-statement, assuming the leading ':' token was eaten.
1414 /// [GNU] asm-operands:
1416 /// asm-operands ',' asm-operand
1418 /// [GNU] asm-operand:
1419 /// asm-string-literal '(' expression ')'
1420 /// '[' identifier ']' asm-string-literal '(' expression ')'
1423 // FIXME: Avoid unnecessary std::string trashing.
1424 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl
<IdentifierInfo
*> &Names
,
1425 llvm::SmallVectorImpl
<ExprTy
*> &Constraints
,
1426 llvm::SmallVectorImpl
<ExprTy
*> &Exprs
) {
1427 // 'asm-operands' isn't present?
1428 if (!isTokenStringLiteral() && Tok
.isNot(tok::l_square
))
1432 // Read the [id] if present.
1433 if (Tok
.is(tok::l_square
)) {
1434 SourceLocation Loc
= ConsumeBracket();
1436 if (Tok
.isNot(tok::identifier
)) {
1437 Diag(Tok
, diag::err_expected_ident
);
1438 SkipUntil(tok::r_paren
);
1442 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1445 Names
.push_back(II
);
1446 MatchRHSPunctuation(tok::r_square
, Loc
);
1450 ExprResult
Constraint(ParseAsmStringLiteral());
1451 if (Constraint
.isInvalid()) {
1452 SkipUntil(tok::r_paren
);
1455 Constraints
.push_back(Constraint
.release());
1457 if (Tok
.isNot(tok::l_paren
)) {
1458 Diag(Tok
, diag::err_expected_lparen_after
) << "asm operand";
1459 SkipUntil(tok::r_paren
);
1463 // Read the parenthesized expression.
1464 SourceLocation OpenLoc
= ConsumeParen();
1465 ExprResult
Res(ParseExpression());
1466 MatchRHSPunctuation(tok::r_paren
, OpenLoc
);
1467 if (Res
.isInvalid()) {
1468 SkipUntil(tok::r_paren
);
1471 Exprs
.push_back(Res
.release());
1472 // Eat the comma and continue parsing if it exists.
1473 if (Tok
.isNot(tok::comma
)) return false;
1480 Decl
*Parser::ParseFunctionStatementBody(Decl
*Decl
) {
1481 assert(Tok
.is(tok::l_brace
));
1482 SourceLocation LBraceLoc
= Tok
.getLocation();
1484 if (PP
.isCodeCompletionEnabled())
1485 if (trySkippingFunctionBodyForCodeCompletion())
1486 return Actions
.ActOnFinishFunctionBody(Decl
, 0);
1488 PrettyDeclStackTraceEntry
CrashInfo(Actions
, Decl
, LBraceLoc
,
1489 "parsing function body");
1491 // Do not enter a scope for the brace, as the arguments are in the same scope
1492 // (the function body) as the body itself. Instead, just read the statement
1493 // list and put it into a CompoundStmt for safe keeping.
1494 StmtResult
FnBody(ParseCompoundStatementBody());
1496 // If the function body could not be parsed, make a bogus compoundstmt.
1497 if (FnBody
.isInvalid())
1498 FnBody
= Actions
.ActOnCompoundStmt(LBraceLoc
, LBraceLoc
,
1499 MultiStmtArg(Actions
), false);
1501 return Actions
.ActOnFinishFunctionBody(Decl
, FnBody
.take());
1504 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1506 /// function-try-block:
1507 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1509 Decl
*Parser::ParseFunctionTryBlock(Decl
*Decl
) {
1510 assert(Tok
.is(tok::kw_try
) && "Expected 'try'");
1511 SourceLocation TryLoc
= ConsumeToken();
1513 PrettyDeclStackTraceEntry
CrashInfo(Actions
, Decl
, TryLoc
,
1514 "parsing function try block");
1516 // Constructor initializer list?
1517 if (Tok
.is(tok::colon
))
1518 ParseConstructorInitializer(Decl
);
1520 if (PP
.isCodeCompletionEnabled())
1521 if (trySkippingFunctionBodyForCodeCompletion())
1522 return Actions
.ActOnFinishFunctionBody(Decl
, 0);
1524 SourceLocation LBraceLoc
= Tok
.getLocation();
1525 StmtResult
FnBody(ParseCXXTryBlockCommon(TryLoc
));
1526 // If we failed to parse the try-catch, we just give the function an empty
1527 // compound statement as the body.
1528 if (FnBody
.isInvalid())
1529 FnBody
= Actions
.ActOnCompoundStmt(LBraceLoc
, LBraceLoc
,
1530 MultiStmtArg(Actions
), false);
1532 return Actions
.ActOnFinishFunctionBody(Decl
, FnBody
.take());
1535 bool Parser::trySkippingFunctionBodyForCodeCompletion() {
1536 assert(Tok
.is(tok::l_brace
));
1537 assert(PP
.isCodeCompletionEnabled() &&
1538 "Should only be called when in code-completion mode");
1540 // We're in code-completion mode. Skip parsing for all function bodies unless
1541 // the body contains the code-completion point.
1542 TentativeParsingAction
PA(*this);
1544 if (SkipUntil(tok::r_brace
, /*StopAtSemi=*/false, /*DontConsume=*/false,
1545 /*StopAtCodeCompletion=*/true)) {
1554 /// ParseCXXTryBlock - Parse a C++ try-block.
1557 /// 'try' compound-statement handler-seq
1559 StmtResult
Parser::ParseCXXTryBlock(ParsedAttributes
&attrs
) {
1560 // FIXME: Add attributes?
1562 assert(Tok
.is(tok::kw_try
) && "Expected 'try'");
1564 SourceLocation TryLoc
= ConsumeToken();
1565 return ParseCXXTryBlockCommon(TryLoc
);
1568 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1569 /// function-try-block.
1572 /// 'try' compound-statement handler-seq
1574 /// function-try-block:
1575 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1578 /// handler handler-seq[opt]
1580 StmtResult
Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc
) {
1581 if (Tok
.isNot(tok::l_brace
))
1582 return StmtError(Diag(Tok
, diag::err_expected_lbrace
));
1583 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1584 ParsedAttributesWithRange attrs
;
1585 StmtResult
TryBlock(ParseCompoundStatement(attrs
));
1586 if (TryBlock
.isInvalid())
1587 return move(TryBlock
);
1589 StmtVector
Handlers(Actions
);
1590 MaybeParseCXX0XAttributes(attrs
);
1591 ProhibitAttributes(attrs
);
1593 if (Tok
.isNot(tok::kw_catch
))
1594 return StmtError(Diag(Tok
, diag::err_expected_catch
));
1595 while (Tok
.is(tok::kw_catch
)) {
1596 StmtResult
Handler(ParseCXXCatchBlock());
1597 if (!Handler
.isInvalid())
1598 Handlers
.push_back(Handler
.release());
1600 // Don't bother creating the full statement if we don't have any usable
1602 if (Handlers
.empty())
1605 return Actions
.ActOnCXXTryBlock(TryLoc
, TryBlock
.take(), move_arg(Handlers
));
1608 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1611 /// 'catch' '(' exception-declaration ')' compound-statement
1613 /// exception-declaration:
1614 /// type-specifier-seq declarator
1615 /// type-specifier-seq abstract-declarator
1616 /// type-specifier-seq
1619 StmtResult
Parser::ParseCXXCatchBlock() {
1620 assert(Tok
.is(tok::kw_catch
) && "Expected 'catch'");
1622 SourceLocation CatchLoc
= ConsumeToken();
1624 SourceLocation LParenLoc
= Tok
.getLocation();
1625 if (ExpectAndConsume(tok::l_paren
, diag::err_expected_lparen
))
1629 // The name in a catch exception-declaration is local to the handler and
1630 // shall not be redeclared in the outermost block of the handler.
1631 ParseScope
CatchScope(this, Scope::DeclScope
| Scope::ControlScope
);
1633 // exception-declaration is equivalent to '...' or a parameter-declaration
1634 // without default arguments.
1635 Decl
*ExceptionDecl
= 0;
1636 if (Tok
.isNot(tok::ellipsis
)) {
1638 if (ParseCXXTypeSpecifierSeq(DS
))
1640 Declarator
ExDecl(DS
, Declarator::CXXCatchContext
);
1641 ParseDeclarator(ExDecl
);
1642 ExceptionDecl
= Actions
.ActOnExceptionDeclarator(getCurScope(), ExDecl
);
1646 if (MatchRHSPunctuation(tok::r_paren
, LParenLoc
).isInvalid())
1649 if (Tok
.isNot(tok::l_brace
))
1650 return StmtError(Diag(Tok
, diag::err_expected_lbrace
));
1652 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1653 ParsedAttributes attrs
;
1654 StmtResult
Block(ParseCompoundStatement(attrs
));
1655 if (Block
.isInvalid())
1658 return Actions
.ActOnCXXCatchBlock(CatchLoc
, ExceptionDecl
, Block
.take());