Don't warn for empty 'if' body if there is a macro that expands to nothing, e.g:
[clang.git] / lib / Parse / ParseStmt.cpp
blobe3c15680c231f253fc1d1c4316c0881d753065c2
1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Statement and Block portions of the Parser
11 // interface.
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:
31 /// statement
32 /// declaration
33 ///
34 /// statement:
35 /// labeled-statement
36 /// compound-statement
37 /// expression-statement
38 /// selection-statement
39 /// iteration-statement
40 /// jump-statement
41 /// [C++] declaration-statement
42 /// [C++] try-block
43 /// [OBC] objc-throw-statement
44 /// [OBC] objc-try-catch-statement
45 /// [OBC] objc-synchronized-statement
46 /// [GNU] asm-statement
47 /// [OMP] openmp-construct [TODO]
48 ///
49 /// labeled-statement:
50 /// identifier ':' statement
51 /// 'case' constant-expression ':' statement
52 /// 'default' ':' statement
53 ///
54 /// selection-statement:
55 /// if-statement
56 /// switch-statement
57 ///
58 /// iteration-statement:
59 /// while-statement
60 /// do-statement
61 /// for-statement
62 ///
63 /// expression-statement:
64 /// expression[opt] ';'
65 ///
66 /// jump-statement:
67 /// 'goto' identifier ';'
68 /// 'continue' ';'
69 /// 'break' ';'
70 /// 'return' expression[opt] ';'
71 /// [GNU] 'goto' '*' expression ';'
72 ///
73 /// [OBC] objc-throw-statement:
74 /// [OBC] '@' 'throw' expression ';'
75 /// [OBC] '@' 'throw' ';'
76 ///
77 StmtResult
78 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement) {
79 const char *SemiError = 0;
80 StmtResult Res;
82 ParenBraceBracketBalancer BalancerRAIIObj(*this);
84 CXX0XAttributeList Attr;
85 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
86 Attr = ParseCXX0XAttributes();
87 AttributeList *AttrList = Attr.AttrList;
89 // Cases in this switch statement should fall through if the parser expects
90 // the token to end in a semicolon (in which case SemiError should be set),
91 // or they directly 'return;' if not.
92 tok::TokenKind Kind = Tok.getKind();
93 SourceLocation AtLoc;
94 switch (Kind) {
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);
103 ConsumeCodeCompletionToken();
104 return ParseStatementOrDeclaration(Stmts, OnlyStatement);
106 case tok::identifier:
107 if (NextToken().is(tok::colon)) { // C99 6.8.1: labeled-statement
108 // identifier ':' statement
109 return ParseLabeledStatement(AttrList);
111 // PASS THROUGH.
113 default: {
114 if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
115 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
116 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
117 DeclEnd, Attr);
118 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
121 if (Tok.is(tok::r_brace)) {
122 Diag(Tok, diag::err_expected_statement);
123 return StmtError();
126 // FIXME: Use the attributes
127 // expression[opt] ';'
128 ExprResult Expr(ParseExpression());
129 if (Expr.isInvalid()) {
130 // If the expression is invalid, skip ahead to the next semicolon or '}'.
131 // Not doing this opens us up to the possibility of infinite loops if
132 // ParseExpression does not consume any tokens.
133 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true);
134 if (Tok.is(tok::semi))
135 ConsumeToken();
136 return StmtError();
138 // Otherwise, eat the semicolon.
139 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
140 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Expr.get()));
143 case tok::kw_case: // C99 6.8.1: labeled-statement
144 return ParseCaseStatement(AttrList);
145 case tok::kw_default: // C99 6.8.1: labeled-statement
146 return ParseDefaultStatement(AttrList);
148 case tok::l_brace: // C99 6.8.2: compound-statement
149 return ParseCompoundStatement(AttrList);
150 case tok::semi: // C99 6.8.3p3: expression[opt] ';'
151 return Actions.ActOnNullStmt(ConsumeToken());
153 case tok::kw_if: // C99 6.8.4.1: if-statement
154 return ParseIfStatement(AttrList);
155 case tok::kw_switch: // C99 6.8.4.2: switch-statement
156 return ParseSwitchStatement(AttrList);
158 case tok::kw_while: // C99 6.8.5.1: while-statement
159 return ParseWhileStatement(AttrList);
160 case tok::kw_do: // C99 6.8.5.2: do-statement
161 Res = ParseDoStatement(AttrList);
162 SemiError = "do/while";
163 break;
164 case tok::kw_for: // C99 6.8.5.3: for-statement
165 return ParseForStatement(AttrList);
167 case tok::kw_goto: // C99 6.8.6.1: goto-statement
168 Res = ParseGotoStatement(AttrList);
169 SemiError = "goto";
170 break;
171 case tok::kw_continue: // C99 6.8.6.2: continue-statement
172 Res = ParseContinueStatement(AttrList);
173 SemiError = "continue";
174 break;
175 case tok::kw_break: // C99 6.8.6.3: break-statement
176 Res = ParseBreakStatement(AttrList);
177 SemiError = "break";
178 break;
179 case tok::kw_return: // C99 6.8.6.4: return-statement
180 Res = ParseReturnStatement(AttrList);
181 SemiError = "return";
182 break;
184 case tok::kw_asm: {
185 if (Attr.HasAttr)
186 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
187 << Attr.Range;
188 bool msAsm = false;
189 Res = ParseAsmStatement(msAsm);
190 Res = Actions.ActOnFinishFullStmt(Res.get());
191 if (msAsm) return move(Res);
192 SemiError = "asm";
193 break;
196 case tok::kw_try: // C++ 15: try-block
197 return ParseCXXTryBlock(AttrList);
200 // If we reached this code, the statement must end in a semicolon.
201 if (Tok.is(tok::semi)) {
202 ConsumeToken();
203 } else if (!Res.isInvalid()) {
204 // If the result was valid, then we do want to diagnose this. Use
205 // ExpectAndConsume to emit the diagnostic, even though we know it won't
206 // succeed.
207 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
208 // Skip until we see a } or ;, but don't eat it.
209 SkipUntil(tok::r_brace, true, true);
212 return move(Res);
215 /// ParseLabeledStatement - We have an identifier and a ':' after it.
217 /// labeled-statement:
218 /// identifier ':' statement
219 /// [GNU] identifier ':' attributes[opt] statement
221 StmtResult Parser::ParseLabeledStatement(AttributeList *Attr) {
222 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
223 "Not an identifier!");
225 Token IdentTok = Tok; // Save the whole token.
226 ConsumeToken(); // eat the identifier.
228 assert(Tok.is(tok::colon) && "Not a label!");
230 // identifier ':' statement
231 SourceLocation ColonLoc = ConsumeToken();
233 // Read label attributes, if present.
234 if (Tok.is(tok::kw___attribute))
235 Attr = addAttributeLists(Attr, ParseGNUAttributes());
237 StmtResult SubStmt(ParseStatement());
239 // Broken substmt shouldn't prevent the label from being added to the AST.
240 if (SubStmt.isInvalid())
241 SubStmt = Actions.ActOnNullStmt(ColonLoc);
243 return Actions.ActOnLabelStmt(IdentTok.getLocation(),
244 IdentTok.getIdentifierInfo(),
245 ColonLoc, SubStmt.get(), Attr);
248 /// ParseCaseStatement
249 /// labeled-statement:
250 /// 'case' constant-expression ':' statement
251 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
253 StmtResult Parser::ParseCaseStatement(AttributeList *Attr) {
254 assert(Tok.is(tok::kw_case) && "Not a case stmt!");
255 // FIXME: Use attributes?
257 // It is very very common for code to contain many case statements recursively
258 // nested, as in (but usually without indentation):
259 // case 1:
260 // case 2:
261 // case 3:
262 // case 4:
263 // case 5: etc.
265 // Parsing this naively works, but is both inefficient and can cause us to run
266 // out of stack space in our recursive descent parser. As a special case,
267 // flatten this recursion into an iterative loop. This is complex and gross,
268 // but all the grossness is constrained to ParseCaseStatement (and some
269 // wierdness in the actions), so this is just local grossness :).
271 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
272 // example above.
273 StmtResult TopLevelCase(true);
275 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
276 // gets updated each time a new case is parsed, and whose body is unset so
277 // far. When parsing 'case 4', this is the 'case 3' node.
278 StmtTy *DeepestParsedCaseStmt = 0;
280 // While we have case statements, eat and stack them.
281 do {
282 SourceLocation CaseLoc = ConsumeToken(); // eat the 'case'.
284 if (Tok.is(tok::code_completion)) {
285 Actions.CodeCompleteCase(getCurScope());
286 ConsumeCodeCompletionToken();
289 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
290 /// Disable this form of error recovery while we're parsing the case
291 /// expression.
292 ColonProtectionRAIIObject ColonProtection(*this);
294 ExprResult LHS(ParseConstantExpression());
295 if (LHS.isInvalid()) {
296 SkipUntil(tok::colon);
297 return StmtError();
300 // GNU case range extension.
301 SourceLocation DotDotDotLoc;
302 ExprResult RHS;
303 if (Tok.is(tok::ellipsis)) {
304 Diag(Tok, diag::ext_gnu_case_range);
305 DotDotDotLoc = ConsumeToken();
307 RHS = ParseConstantExpression();
308 if (RHS.isInvalid()) {
309 SkipUntil(tok::colon);
310 return StmtError();
314 ColonProtection.restore();
316 if (Tok.isNot(tok::colon)) {
317 Diag(Tok, diag::err_expected_colon_after) << "'case'";
318 SkipUntil(tok::colon);
319 return StmtError();
322 SourceLocation ColonLoc = ConsumeToken();
324 StmtResult Case =
325 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
326 RHS.get(), ColonLoc);
328 // If we had a sema error parsing this case, then just ignore it and
329 // continue parsing the sub-stmt.
330 if (Case.isInvalid()) {
331 if (TopLevelCase.isInvalid()) // No parsed case stmts.
332 return ParseStatement();
333 // Otherwise, just don't add it as a nested case.
334 } else {
335 // If this is the first case statement we parsed, it becomes TopLevelCase.
336 // Otherwise we link it into the current chain.
337 Stmt *NextDeepest = Case.get();
338 if (TopLevelCase.isInvalid())
339 TopLevelCase = move(Case);
340 else
341 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
342 DeepestParsedCaseStmt = NextDeepest;
345 // Handle all case statements.
346 } while (Tok.is(tok::kw_case));
348 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
350 // If we found a non-case statement, start by parsing it.
351 StmtResult SubStmt;
353 if (Tok.isNot(tok::r_brace)) {
354 SubStmt = ParseStatement();
355 } else {
356 // Nicely diagnose the common error "switch (X) { case 4: }", which is
357 // not valid.
358 // FIXME: add insertion hint.
359 Diag(Tok, diag::err_label_end_of_compound_statement);
360 SubStmt = true;
363 // Broken sub-stmt shouldn't prevent forming the case statement properly.
364 if (SubStmt.isInvalid())
365 SubStmt = Actions.ActOnNullStmt(SourceLocation());
367 // Install the body into the most deeply-nested case.
368 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
370 // Return the top level parsed statement tree.
371 return move(TopLevelCase);
374 /// ParseDefaultStatement
375 /// labeled-statement:
376 /// 'default' ':' statement
377 /// Note that this does not parse the 'statement' at the end.
379 StmtResult Parser::ParseDefaultStatement(AttributeList *Attr) {
380 //FIXME: Use attributes?
382 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
383 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
385 if (Tok.isNot(tok::colon)) {
386 Diag(Tok, diag::err_expected_colon_after) << "'default'";
387 SkipUntil(tok::colon);
388 return StmtError();
391 SourceLocation ColonLoc = ConsumeToken();
393 // Diagnose the common error "switch (X) {... default: }", which is not valid.
394 if (Tok.is(tok::r_brace)) {
395 Diag(Tok, diag::err_label_end_of_compound_statement);
396 return StmtError();
399 StmtResult SubStmt(ParseStatement());
400 if (SubStmt.isInvalid())
401 return StmtError();
403 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
404 SubStmt.get(), getCurScope());
408 /// ParseCompoundStatement - Parse a "{}" block.
410 /// compound-statement: [C99 6.8.2]
411 /// { block-item-list[opt] }
412 /// [GNU] { label-declarations block-item-list } [TODO]
414 /// block-item-list:
415 /// block-item
416 /// block-item-list block-item
418 /// block-item:
419 /// declaration
420 /// [GNU] '__extension__' declaration
421 /// statement
422 /// [OMP] openmp-directive [TODO]
424 /// [GNU] label-declarations:
425 /// [GNU] label-declaration
426 /// [GNU] label-declarations label-declaration
428 /// [GNU] label-declaration:
429 /// [GNU] '__label__' identifier-list ';'
431 /// [OMP] openmp-directive: [TODO]
432 /// [OMP] barrier-directive
433 /// [OMP] flush-directive
435 StmtResult Parser::ParseCompoundStatement(AttributeList *Attr,
436 bool isStmtExpr) {
437 //FIXME: Use attributes?
439 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
441 // Enter a scope to hold everything within the compound stmt. Compound
442 // statements can always hold declarations.
443 ParseScope CompoundScope(this, Scope::DeclScope);
445 // Parse the statements in the body.
446 return ParseCompoundStatementBody(isStmtExpr);
450 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
451 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
452 /// consume the '}' at the end of the block. It does not manipulate the scope
453 /// stack.
454 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
455 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
456 Tok.getLocation(),
457 "in compound statement ('{}')");
458 InMessageExpressionRAIIObject InMessage(*this, false);
460 SourceLocation LBraceLoc = ConsumeBrace(); // eat the '{'.
462 // TODO: "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
463 // only allowed at the start of a compound stmt regardless of the language.
465 StmtVector Stmts(Actions);
466 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
467 StmtResult R;
468 if (Tok.isNot(tok::kw___extension__)) {
469 R = ParseStatementOrDeclaration(Stmts, false);
470 } else {
471 // __extension__ can start declarations and it can also be a unary
472 // operator for expressions. Consume multiple __extension__ markers here
473 // until we can determine which is which.
474 // FIXME: This loses extension expressions in the AST!
475 SourceLocation ExtLoc = ConsumeToken();
476 while (Tok.is(tok::kw___extension__))
477 ConsumeToken();
479 CXX0XAttributeList Attr;
480 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
481 Attr = ParseCXX0XAttributes();
483 // If this is the start of a declaration, parse it as such.
484 if (isDeclarationStatement()) {
485 // __extension__ silences extension warnings in the subdeclaration.
486 // FIXME: Save the __extension__ on the decl as a node somehow?
487 ExtensionRAIIObject O(Diags);
489 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
490 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
491 Declarator::BlockContext, DeclEnd,
492 Attr);
493 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
494 } else {
495 // Otherwise this was a unary __extension__ marker.
496 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
498 if (Res.isInvalid()) {
499 SkipUntil(tok::semi);
500 continue;
503 // FIXME: Use attributes?
504 // Eat the semicolon at the end of stmt and convert the expr into a
505 // statement.
506 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
507 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
511 if (R.isUsable())
512 Stmts.push_back(R.release());
515 // We broke out of the while loop because we found a '}' or EOF.
516 if (Tok.isNot(tok::r_brace)) {
517 Diag(Tok, diag::err_expected_rbrace);
518 Diag(LBraceLoc, diag::note_matching) << "{";
519 return StmtError();
522 SourceLocation RBraceLoc = ConsumeBrace();
523 return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
524 isStmtExpr);
527 /// ParseParenExprOrCondition:
528 /// [C ] '(' expression ')'
529 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
531 /// This function parses and performs error recovery on the specified condition
532 /// or expression (depending on whether we're in C++ or C mode). This function
533 /// goes out of its way to recover well. It returns true if there was a parser
534 /// error (the right paren couldn't be found), which indicates that the caller
535 /// should try to recover harder. It returns false if the condition is
536 /// successfully parsed. Note that a successful parse can still have semantic
537 /// errors in the condition.
538 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
539 Decl *&DeclResult,
540 SourceLocation Loc,
541 bool ConvertToBoolean,
542 bool *MacroExpandedAfterRParen) {
543 bool ParseError = false;
545 SourceLocation LParenLoc = ConsumeParen();
546 if (getLang().CPlusPlus)
547 ParseError = ParseCXXCondition(ExprResult, DeclResult, Loc,
548 ConvertToBoolean);
549 else {
550 ExprResult = ParseExpression();
551 DeclResult = 0;
553 // If required, convert to a boolean value.
554 if (!ExprResult.isInvalid() && ConvertToBoolean)
555 ExprResult
556 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
559 // If the parser was confused by the condition and we don't have a ')', try to
560 // recover by skipping ahead to a semi and bailing out. If condexp is
561 // semantically invalid but we have well formed code, keep going.
562 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
563 SkipUntil(tok::semi);
564 // Skipping may have stopped if it found the containing ')'. If so, we can
565 // continue parsing the if statement.
566 if (Tok.isNot(tok::r_paren))
567 return true;
570 // Otherwise the condition is valid or the rparen is present.
572 // Catch a macro expansion after ')'. This is used to know that there is a
573 // macro for 'if' body and not warn for empty body if the macro is empty.
574 PPMacroExpansionTrap MacroExpansionTrap(PP);
575 MatchRHSPunctuation(tok::r_paren, LParenLoc);
576 if (MacroExpandedAfterRParen)
577 *MacroExpandedAfterRParen = MacroExpansionTrap.hasMacroExpansionOccured();
579 return false;
583 /// ParseIfStatement
584 /// if-statement: [C99 6.8.4.1]
585 /// 'if' '(' expression ')' statement
586 /// 'if' '(' expression ')' statement 'else' statement
587 /// [C++] 'if' '(' condition ')' statement
588 /// [C++] 'if' '(' condition ')' statement 'else' statement
590 StmtResult Parser::ParseIfStatement(AttributeList *Attr) {
591 // FIXME: Use attributes?
593 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
594 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
596 if (Tok.isNot(tok::l_paren)) {
597 Diag(Tok, diag::err_expected_lparen_after) << "if";
598 SkipUntil(tok::semi);
599 return StmtError();
602 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
604 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
605 // the case for C90.
607 // C++ 6.4p3:
608 // A name introduced by a declaration in a condition is in scope from its
609 // point of declaration until the end of the substatements controlled by the
610 // condition.
611 // C++ 3.3.2p4:
612 // Names declared in the for-init-statement, and in the condition of if,
613 // while, for, and switch statements are local to the if, while, for, or
614 // switch statement (including the controlled statement).
616 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
618 // Parse the condition.
619 ExprResult CondExp;
620 Decl *CondVar = 0;
621 bool MacroExpandedInThenStmt;
622 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true,
623 &MacroExpandedInThenStmt))
624 return StmtError();
626 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get()));
628 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
629 // there is no compound stmt. C90 does not have this clause. We only do this
630 // if the body isn't a compound statement to avoid push/pop in common cases.
632 // C++ 6.4p1:
633 // The substatement in a selection-statement (each substatement, in the else
634 // form of the if statement) implicitly defines a local scope.
636 // For C++ we create a scope for the condition and a new scope for
637 // substatements because:
638 // -When the 'then' scope exits, we want the condition declaration to still be
639 // active for the 'else' scope too.
640 // -Sema will detect name clashes by considering declarations of a
641 // 'ControlScope' as part of its direct subscope.
642 // -If we wanted the condition and substatement to be in the same scope, we
643 // would have to notify ParseStatement not to create a new scope. It's
644 // simpler to let it create a new scope.
646 ParseScope InnerScope(this, Scope::DeclScope,
647 C99orCXX && Tok.isNot(tok::l_brace));
649 // Read the 'then' stmt.
650 SourceLocation ThenStmtLoc = Tok.getLocation();
651 StmtResult ThenStmt(ParseStatement());
653 // Pop the 'if' scope if needed.
654 InnerScope.Exit();
656 // If it has an else, parse it.
657 SourceLocation ElseLoc;
658 SourceLocation ElseStmtLoc;
659 StmtResult ElseStmt;
661 if (Tok.is(tok::kw_else)) {
662 ElseLoc = ConsumeToken();
663 ElseStmtLoc = Tok.getLocation();
665 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
666 // there is no compound stmt. C90 does not have this clause. We only do
667 // this if the body isn't a compound statement to avoid push/pop in common
668 // cases.
670 // C++ 6.4p1:
671 // The substatement in a selection-statement (each substatement, in the else
672 // form of the if statement) implicitly defines a local scope.
674 ParseScope InnerScope(this, Scope::DeclScope,
675 C99orCXX && Tok.isNot(tok::l_brace));
677 ElseStmt = ParseStatement();
679 // Pop the 'else' scope if needed.
680 InnerScope.Exit();
683 IfScope.Exit();
685 // If the condition was invalid, discard the if statement. We could recover
686 // better by replacing it with a valid expr, but don't do that yet.
687 if (CondExp.isInvalid() && !CondVar)
688 return StmtError();
690 // If the then or else stmt is invalid and the other is valid (and present),
691 // make turn the invalid one into a null stmt to avoid dropping the other
692 // part. If both are invalid, return error.
693 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
694 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
695 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
696 // Both invalid, or one is invalid and other is non-present: return error.
697 return StmtError();
700 // Now if either are invalid, replace with a ';'.
701 if (ThenStmt.isInvalid())
702 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
703 if (ElseStmt.isInvalid())
704 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
706 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
707 MacroExpandedInThenStmt, ElseLoc, ElseStmt.get());
710 /// ParseSwitchStatement
711 /// switch-statement:
712 /// 'switch' '(' expression ')' statement
713 /// [C++] 'switch' '(' condition ')' statement
714 StmtResult Parser::ParseSwitchStatement(AttributeList *Attr) {
715 // FIXME: Use attributes?
717 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
718 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
720 if (Tok.isNot(tok::l_paren)) {
721 Diag(Tok, diag::err_expected_lparen_after) << "switch";
722 SkipUntil(tok::semi);
723 return StmtError();
726 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
728 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
729 // not the case for C90. Start the switch scope.
731 // C++ 6.4p3:
732 // A name introduced by a declaration in a condition is in scope from its
733 // point of declaration until the end of the substatements controlled by the
734 // condition.
735 // C++ 3.3.2p4:
736 // Names declared in the for-init-statement, and in the condition of if,
737 // while, for, and switch statements are local to the if, while, for, or
738 // switch statement (including the controlled statement).
740 unsigned ScopeFlags = Scope::BreakScope;
741 if (C99orCXX)
742 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
743 ParseScope SwitchScope(this, ScopeFlags);
745 // Parse the condition.
746 ExprResult Cond;
747 Decl *CondVar = 0;
748 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
749 return StmtError();
751 StmtResult Switch
752 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
754 if (Switch.isInvalid()) {
755 // Skip the switch body.
756 // FIXME: This is not optimal recovery, but parsing the body is more
757 // dangerous due to the presence of case and default statements, which
758 // will have no place to connect back with the switch.
759 if (Tok.is(tok::l_brace)) {
760 ConsumeBrace();
761 SkipUntil(tok::r_brace, false, false);
762 } else
763 SkipUntil(tok::semi);
764 return move(Switch);
767 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
768 // there is no compound stmt. C90 does not have this clause. We only do this
769 // if the body isn't a compound statement to avoid push/pop in common cases.
771 // C++ 6.4p1:
772 // The substatement in a selection-statement (each substatement, in the else
773 // form of the if statement) implicitly defines a local scope.
775 // See comments in ParseIfStatement for why we create a scope for the
776 // condition and a new scope for substatement in C++.
778 ParseScope InnerScope(this, Scope::DeclScope,
779 C99orCXX && Tok.isNot(tok::l_brace));
781 // Read the body statement.
782 StmtResult Body(ParseStatement());
784 // Pop the scopes.
785 InnerScope.Exit();
786 SwitchScope.Exit();
788 if (Body.isInvalid())
789 // FIXME: Remove the case statement list from the Switch statement.
790 Body = Actions.ActOnNullStmt(Tok.getLocation());
792 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
795 /// ParseWhileStatement
796 /// while-statement: [C99 6.8.5.1]
797 /// 'while' '(' expression ')' statement
798 /// [C++] 'while' '(' condition ')' statement
799 StmtResult Parser::ParseWhileStatement(AttributeList *Attr) {
800 // FIXME: Use attributes?
802 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
803 SourceLocation WhileLoc = Tok.getLocation();
804 ConsumeToken(); // eat the 'while'.
806 if (Tok.isNot(tok::l_paren)) {
807 Diag(Tok, diag::err_expected_lparen_after) << "while";
808 SkipUntil(tok::semi);
809 return StmtError();
812 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
814 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
815 // the case for C90. Start the loop scope.
817 // C++ 6.4p3:
818 // A name introduced by a declaration in a condition is in scope from its
819 // point of declaration until the end of the substatements controlled by the
820 // condition.
821 // C++ 3.3.2p4:
822 // Names declared in the for-init-statement, and in the condition of if,
823 // while, for, and switch statements are local to the if, while, for, or
824 // switch statement (including the controlled statement).
826 unsigned ScopeFlags;
827 if (C99orCXX)
828 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
829 Scope::DeclScope | Scope::ControlScope;
830 else
831 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
832 ParseScope WhileScope(this, ScopeFlags);
834 // Parse the condition.
835 ExprResult Cond;
836 Decl *CondVar = 0;
837 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
838 return StmtError();
840 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get()));
842 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
843 // there is no compound stmt. C90 does not have this clause. We only do this
844 // if the body isn't a compound statement to avoid push/pop in common cases.
846 // C++ 6.5p2:
847 // The substatement in an iteration-statement implicitly defines a local scope
848 // which is entered and exited each time through the loop.
850 // See comments in ParseIfStatement for why we create a scope for the
851 // condition and a new scope for substatement in C++.
853 ParseScope InnerScope(this, Scope::DeclScope,
854 C99orCXX && Tok.isNot(tok::l_brace));
856 // Read the body statement.
857 StmtResult Body(ParseStatement());
859 // Pop the body scope if needed.
860 InnerScope.Exit();
861 WhileScope.Exit();
863 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
864 return StmtError();
866 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
869 /// ParseDoStatement
870 /// do-statement: [C99 6.8.5.2]
871 /// 'do' statement 'while' '(' expression ')' ';'
872 /// Note: this lets the caller parse the end ';'.
873 StmtResult Parser::ParseDoStatement(AttributeList *Attr) {
874 // FIXME: Use attributes?
876 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
877 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
879 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
880 // the case for C90. Start the loop scope.
881 unsigned ScopeFlags;
882 if (getLang().C99)
883 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
884 else
885 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
887 ParseScope DoScope(this, ScopeFlags);
889 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
890 // there is no compound stmt. C90 does not have this clause. We only do this
891 // if the body isn't a compound statement to avoid push/pop in common cases.
893 // C++ 6.5p2:
894 // The substatement in an iteration-statement implicitly defines a local scope
895 // which is entered and exited each time through the loop.
897 ParseScope InnerScope(this, Scope::DeclScope,
898 (getLang().C99 || getLang().CPlusPlus) &&
899 Tok.isNot(tok::l_brace));
901 // Read the body statement.
902 StmtResult Body(ParseStatement());
904 // Pop the body scope if needed.
905 InnerScope.Exit();
907 if (Tok.isNot(tok::kw_while)) {
908 if (!Body.isInvalid()) {
909 Diag(Tok, diag::err_expected_while);
910 Diag(DoLoc, diag::note_matching) << "do";
911 SkipUntil(tok::semi, false, true);
913 return StmtError();
915 SourceLocation WhileLoc = ConsumeToken();
917 if (Tok.isNot(tok::l_paren)) {
918 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
919 SkipUntil(tok::semi, false, true);
920 return StmtError();
923 // Parse the parenthesized condition.
924 SourceLocation LPLoc = ConsumeParen();
925 ExprResult Cond = ParseExpression();
926 SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
927 DoScope.Exit();
929 if (Cond.isInvalid() || Body.isInvalid())
930 return StmtError();
932 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, LPLoc,
933 Cond.get(), RPLoc);
936 /// ParseForStatement
937 /// for-statement: [C99 6.8.5.3]
938 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
939 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
940 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
941 /// [C++] statement
942 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
943 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
945 /// [C++] for-init-statement:
946 /// [C++] expression-statement
947 /// [C++] simple-declaration
949 StmtResult Parser::ParseForStatement(AttributeList *Attr) {
950 // FIXME: Use attributes?
952 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
953 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
955 if (Tok.isNot(tok::l_paren)) {
956 Diag(Tok, diag::err_expected_lparen_after) << "for";
957 SkipUntil(tok::semi);
958 return StmtError();
961 bool C99orCXXorObjC = getLang().C99 || getLang().CPlusPlus || getLang().ObjC1;
963 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
964 // the case for C90. Start the loop scope.
966 // C++ 6.4p3:
967 // A name introduced by a declaration in a condition is in scope from its
968 // point of declaration until the end of the substatements controlled by the
969 // condition.
970 // C++ 3.3.2p4:
971 // Names declared in the for-init-statement, and in the condition of if,
972 // while, for, and switch statements are local to the if, while, for, or
973 // switch statement (including the controlled statement).
974 // C++ 6.5.3p1:
975 // Names declared in the for-init-statement are in the same declarative-region
976 // as those declared in the condition.
978 unsigned ScopeFlags;
979 if (C99orCXXorObjC)
980 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
981 Scope::DeclScope | Scope::ControlScope;
982 else
983 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
985 ParseScope ForScope(this, ScopeFlags);
987 SourceLocation LParenLoc = ConsumeParen();
988 ExprResult Value;
990 bool ForEach = false;
991 StmtResult FirstPart;
992 bool SecondPartIsInvalid = false;
993 FullExprArg SecondPart(Actions);
994 ExprResult Collection;
995 FullExprArg ThirdPart(Actions);
996 Decl *SecondVar = 0;
998 if (Tok.is(tok::code_completion)) {
999 Actions.CodeCompleteOrdinaryName(getCurScope(),
1000 C99orCXXorObjC? Sema::PCC_ForInit
1001 : Sema::PCC_Expression);
1002 ConsumeCodeCompletionToken();
1005 // Parse the first part of the for specifier.
1006 if (Tok.is(tok::semi)) { // for (;
1007 // no first part, eat the ';'.
1008 ConsumeToken();
1009 } else if (isSimpleDeclaration()) { // for (int X = 4;
1010 // Parse declaration, which eats the ';'.
1011 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1012 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1014 AttributeList *AttrList = 0;
1015 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1016 AttrList = ParseCXX0XAttributes().AttrList;
1018 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1019 StmtVector Stmts(Actions);
1020 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
1021 DeclEnd, AttrList, false);
1022 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1024 if (Tok.is(tok::semi)) { // for (int x = 4;
1025 ConsumeToken();
1026 } else if ((ForEach = isTokIdentifier_in())) {
1027 Actions.ActOnForEachDeclStmt(DG);
1028 // ObjC: for (id x in expr)
1029 ConsumeToken(); // consume 'in'
1031 if (Tok.is(tok::code_completion)) {
1032 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1033 ConsumeCodeCompletionToken();
1035 Collection = ParseExpression();
1036 } else {
1037 Diag(Tok, diag::err_expected_semi_for);
1038 SkipUntil(tok::semi);
1040 } else {
1041 Value = ParseExpression();
1043 // Turn the expression into a stmt.
1044 if (!Value.isInvalid())
1045 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1047 if (Tok.is(tok::semi)) {
1048 ConsumeToken();
1049 } else if ((ForEach = isTokIdentifier_in())) {
1050 ConsumeToken(); // consume 'in'
1052 if (Tok.is(tok::code_completion)) {
1053 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1054 ConsumeCodeCompletionToken();
1056 Collection = ParseExpression();
1057 } else {
1058 if (!Value.isInvalid()) Diag(Tok, diag::err_expected_semi_for);
1059 SkipUntil(tok::semi);
1062 if (!ForEach) {
1063 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1064 // Parse the second part of the for specifier.
1065 if (Tok.is(tok::semi)) { // for (...;;
1066 // no second part.
1067 } else {
1068 ExprResult Second;
1069 if (getLang().CPlusPlus)
1070 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1071 else {
1072 Second = ParseExpression();
1073 if (!Second.isInvalid())
1074 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1075 Second.get());
1077 SecondPartIsInvalid = Second.isInvalid();
1078 SecondPart = Actions.MakeFullExpr(Second.get());
1081 if (Tok.is(tok::semi)) {
1082 ConsumeToken();
1083 } else {
1084 if (!SecondPartIsInvalid || SecondVar)
1085 Diag(Tok, diag::err_expected_semi_for);
1086 SkipUntil(tok::semi);
1089 // Parse the third part of the for specifier.
1090 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1091 ExprResult Third = ParseExpression();
1092 ThirdPart = Actions.MakeFullExpr(Third.take());
1095 // Match the ')'.
1096 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1098 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1099 // there is no compound stmt. C90 does not have this clause. We only do this
1100 // if the body isn't a compound statement to avoid push/pop in common cases.
1102 // C++ 6.5p2:
1103 // The substatement in an iteration-statement implicitly defines a local scope
1104 // which is entered and exited each time through the loop.
1106 // See comments in ParseIfStatement for why we create a scope for
1107 // for-init-statement/condition and a new scope for substatement in C++.
1109 ParseScope InnerScope(this, Scope::DeclScope,
1110 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1112 // Read the body statement.
1113 StmtResult Body(ParseStatement());
1115 // Pop the body scope if needed.
1116 InnerScope.Exit();
1118 // Leave the for-scope.
1119 ForScope.Exit();
1121 if (Body.isInvalid())
1122 return StmtError();
1124 if (!ForEach)
1125 return Actions.ActOnForStmt(ForLoc, LParenLoc, FirstPart.take(), SecondPart,
1126 SecondVar, ThirdPart, RParenLoc, Body.take());
1128 // FIXME: It isn't clear how to communicate the late destruction of
1129 // C++ temporaries used to create the collection.
1130 return Actions.ActOnObjCForCollectionStmt(ForLoc, LParenLoc, FirstPart.take(),
1131 Collection.take(), RParenLoc,
1132 Body.take());
1135 /// ParseGotoStatement
1136 /// jump-statement:
1137 /// 'goto' identifier ';'
1138 /// [GNU] 'goto' '*' expression ';'
1140 /// Note: this lets the caller parse the end ';'.
1142 StmtResult Parser::ParseGotoStatement(AttributeList *Attr) {
1143 // FIXME: Use attributes?
1145 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1146 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1148 StmtResult Res;
1149 if (Tok.is(tok::identifier)) {
1150 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(),
1151 Tok.getIdentifierInfo());
1152 ConsumeToken();
1153 } else if (Tok.is(tok::star)) {
1154 // GNU indirect goto extension.
1155 Diag(Tok, diag::ext_gnu_indirect_goto);
1156 SourceLocation StarLoc = ConsumeToken();
1157 ExprResult R(ParseExpression());
1158 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1159 SkipUntil(tok::semi, false, true);
1160 return StmtError();
1162 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1163 } else {
1164 Diag(Tok, diag::err_expected_ident);
1165 return StmtError();
1168 return move(Res);
1171 /// ParseContinueStatement
1172 /// jump-statement:
1173 /// 'continue' ';'
1175 /// Note: this lets the caller parse the end ';'.
1177 StmtResult Parser::ParseContinueStatement(AttributeList *Attr) {
1178 // FIXME: Use attributes?
1180 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1181 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1184 /// ParseBreakStatement
1185 /// jump-statement:
1186 /// 'break' ';'
1188 /// Note: this lets the caller parse the end ';'.
1190 StmtResult Parser::ParseBreakStatement(AttributeList *Attr) {
1191 // FIXME: Use attributes?
1193 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1194 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1197 /// ParseReturnStatement
1198 /// jump-statement:
1199 /// 'return' expression[opt] ';'
1200 StmtResult Parser::ParseReturnStatement(AttributeList *Attr) {
1201 // FIXME: Use attributes?
1203 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1204 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1206 ExprResult R;
1207 if (Tok.isNot(tok::semi)) {
1208 if (Tok.is(tok::code_completion)) {
1209 Actions.CodeCompleteReturn(getCurScope());
1210 ConsumeCodeCompletionToken();
1211 SkipUntil(tok::semi, false, true);
1212 return StmtError();
1215 R = ParseExpression();
1216 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1217 SkipUntil(tok::semi, false, true);
1218 return StmtError();
1221 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1224 /// FuzzyParseMicrosoftAsmStatement. When -fms-extensions is enabled, this
1225 /// routine is called to skip/ignore tokens that comprise the MS asm statement.
1226 StmtResult Parser::FuzzyParseMicrosoftAsmStatement() {
1227 if (Tok.is(tok::l_brace)) {
1228 unsigned short savedBraceCount = BraceCount;
1229 do {
1230 ConsumeAnyToken();
1231 } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1232 } else {
1233 // From the MS website: If used without braces, the __asm keyword means
1234 // that the rest of the line is an assembly-language statement.
1235 SourceManager &SrcMgr = PP.getSourceManager();
1236 SourceLocation TokLoc = Tok.getLocation();
1237 unsigned LineNo = SrcMgr.getInstantiationLineNumber(TokLoc);
1238 do {
1239 ConsumeAnyToken();
1240 TokLoc = Tok.getLocation();
1241 } while ((SrcMgr.getInstantiationLineNumber(TokLoc) == LineNo) &&
1242 Tok.isNot(tok::r_brace) && Tok.isNot(tok::semi) &&
1243 Tok.isNot(tok::eof));
1245 Token t;
1246 t.setKind(tok::string_literal);
1247 t.setLiteralData("\"/*FIXME: not done*/\"");
1248 t.clearFlag(Token::NeedsCleaning);
1249 t.setLength(21);
1250 ExprResult AsmString(Actions.ActOnStringLiteral(&t, 1));
1251 ExprVector Constraints(Actions);
1252 ExprVector Exprs(Actions);
1253 ExprVector Clobbers(Actions);
1254 return Actions.ActOnAsmStmt(Tok.getLocation(), true, true, 0, 0, 0,
1255 move_arg(Constraints), move_arg(Exprs),
1256 AsmString.take(), move_arg(Clobbers),
1257 Tok.getLocation(), true);
1260 /// ParseAsmStatement - Parse a GNU extended asm statement.
1261 /// asm-statement:
1262 /// gnu-asm-statement
1263 /// ms-asm-statement
1265 /// [GNU] gnu-asm-statement:
1266 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
1268 /// [GNU] asm-argument:
1269 /// asm-string-literal
1270 /// asm-string-literal ':' asm-operands[opt]
1271 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1272 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
1273 /// ':' asm-clobbers
1275 /// [GNU] asm-clobbers:
1276 /// asm-string-literal
1277 /// asm-clobbers ',' asm-string-literal
1279 /// [MS] ms-asm-statement:
1280 /// '__asm' assembly-instruction ';'[opt]
1281 /// '__asm' '{' assembly-instruction-list '}' ';'[opt]
1283 /// [MS] assembly-instruction-list:
1284 /// assembly-instruction ';'[opt]
1285 /// assembly-instruction-list ';' assembly-instruction ';'[opt]
1287 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
1288 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
1289 SourceLocation AsmLoc = ConsumeToken();
1291 if (getLang().Microsoft && Tok.isNot(tok::l_paren) && !isTypeQualifier()) {
1292 msAsm = true;
1293 return FuzzyParseMicrosoftAsmStatement();
1295 DeclSpec DS;
1296 SourceLocation Loc = Tok.getLocation();
1297 ParseTypeQualifierListOpt(DS, true, false);
1299 // GNU asms accept, but warn, about type-qualifiers other than volatile.
1300 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1301 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
1302 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
1303 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
1305 // Remember if this was a volatile asm.
1306 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
1307 if (Tok.isNot(tok::l_paren)) {
1308 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1309 SkipUntil(tok::r_paren);
1310 return StmtError();
1312 Loc = ConsumeParen();
1314 ExprResult AsmString(ParseAsmStringLiteral());
1315 if (AsmString.isInvalid())
1316 return StmtError();
1318 llvm::SmallVector<IdentifierInfo *, 4> Names;
1319 ExprVector Constraints(Actions);
1320 ExprVector Exprs(Actions);
1321 ExprVector Clobbers(Actions);
1323 if (Tok.is(tok::r_paren)) {
1324 // We have a simple asm expression like 'asm("foo")'.
1325 SourceLocation RParenLoc = ConsumeParen();
1326 return Actions.ActOnAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
1327 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
1328 move_arg(Constraints), move_arg(Exprs),
1329 AsmString.take(), move_arg(Clobbers),
1330 RParenLoc);
1333 // Parse Outputs, if present.
1334 bool AteExtraColon = false;
1335 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1336 // In C++ mode, parse "::" like ": :".
1337 AteExtraColon = Tok.is(tok::coloncolon);
1338 ConsumeToken();
1340 if (!AteExtraColon &&
1341 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1342 return StmtError();
1345 unsigned NumOutputs = Names.size();
1347 // Parse Inputs, if present.
1348 if (AteExtraColon ||
1349 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
1350 // In C++ mode, parse "::" like ": :".
1351 if (AteExtraColon)
1352 AteExtraColon = false;
1353 else {
1354 AteExtraColon = Tok.is(tok::coloncolon);
1355 ConsumeToken();
1358 if (!AteExtraColon &&
1359 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1360 return StmtError();
1363 assert(Names.size() == Constraints.size() &&
1364 Constraints.size() == Exprs.size() &&
1365 "Input operand size mismatch!");
1367 unsigned NumInputs = Names.size() - NumOutputs;
1369 // Parse the clobbers, if present.
1370 if (AteExtraColon || Tok.is(tok::colon)) {
1371 if (!AteExtraColon)
1372 ConsumeToken();
1374 // Parse the asm-string list for clobbers if present.
1375 if (Tok.isNot(tok::r_paren)) {
1376 while (1) {
1377 ExprResult Clobber(ParseAsmStringLiteral());
1379 if (Clobber.isInvalid())
1380 break;
1382 Clobbers.push_back(Clobber.release());
1384 if (Tok.isNot(tok::comma)) break;
1385 ConsumeToken();
1390 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, Loc);
1391 return Actions.ActOnAsmStmt(AsmLoc, false, isVolatile,
1392 NumOutputs, NumInputs, Names.data(),
1393 move_arg(Constraints), move_arg(Exprs),
1394 AsmString.take(), move_arg(Clobbers),
1395 RParenLoc);
1398 /// ParseAsmOperands - Parse the asm-operands production as used by
1399 /// asm-statement, assuming the leading ':' token was eaten.
1401 /// [GNU] asm-operands:
1402 /// asm-operand
1403 /// asm-operands ',' asm-operand
1405 /// [GNU] asm-operand:
1406 /// asm-string-literal '(' expression ')'
1407 /// '[' identifier ']' asm-string-literal '(' expression ')'
1410 // FIXME: Avoid unnecessary std::string trashing.
1411 bool Parser::ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1412 llvm::SmallVectorImpl<ExprTy *> &Constraints,
1413 llvm::SmallVectorImpl<ExprTy *> &Exprs) {
1414 // 'asm-operands' isn't present?
1415 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
1416 return false;
1418 while (1) {
1419 // Read the [id] if present.
1420 if (Tok.is(tok::l_square)) {
1421 SourceLocation Loc = ConsumeBracket();
1423 if (Tok.isNot(tok::identifier)) {
1424 Diag(Tok, diag::err_expected_ident);
1425 SkipUntil(tok::r_paren);
1426 return true;
1429 IdentifierInfo *II = Tok.getIdentifierInfo();
1430 ConsumeToken();
1432 Names.push_back(II);
1433 MatchRHSPunctuation(tok::r_square, Loc);
1434 } else
1435 Names.push_back(0);
1437 ExprResult Constraint(ParseAsmStringLiteral());
1438 if (Constraint.isInvalid()) {
1439 SkipUntil(tok::r_paren);
1440 return true;
1442 Constraints.push_back(Constraint.release());
1444 if (Tok.isNot(tok::l_paren)) {
1445 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
1446 SkipUntil(tok::r_paren);
1447 return true;
1450 // Read the parenthesized expression.
1451 SourceLocation OpenLoc = ConsumeParen();
1452 ExprResult Res(ParseExpression());
1453 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1454 if (Res.isInvalid()) {
1455 SkipUntil(tok::r_paren);
1456 return true;
1458 Exprs.push_back(Res.release());
1459 // Eat the comma and continue parsing if it exists.
1460 if (Tok.isNot(tok::comma)) return false;
1461 ConsumeToken();
1464 return true;
1467 Decl *Parser::ParseFunctionStatementBody(Decl *Decl) {
1468 assert(Tok.is(tok::l_brace));
1469 SourceLocation LBraceLoc = Tok.getLocation();
1471 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
1472 "parsing function body");
1474 // Do not enter a scope for the brace, as the arguments are in the same scope
1475 // (the function body) as the body itself. Instead, just read the statement
1476 // list and put it into a CompoundStmt for safe keeping.
1477 StmtResult FnBody(ParseCompoundStatementBody());
1479 // If the function body could not be parsed, make a bogus compoundstmt.
1480 if (FnBody.isInvalid())
1481 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1482 MultiStmtArg(Actions), false);
1484 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1487 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
1489 /// function-try-block:
1490 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1492 Decl *Parser::ParseFunctionTryBlock(Decl *Decl) {
1493 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1494 SourceLocation TryLoc = ConsumeToken();
1496 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
1497 "parsing function try block");
1499 // Constructor initializer list?
1500 if (Tok.is(tok::colon))
1501 ParseConstructorInitializer(Decl);
1503 SourceLocation LBraceLoc = Tok.getLocation();
1504 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
1505 // If we failed to parse the try-catch, we just give the function an empty
1506 // compound statement as the body.
1507 if (FnBody.isInvalid())
1508 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
1509 MultiStmtArg(Actions), false);
1511 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
1514 /// ParseCXXTryBlock - Parse a C++ try-block.
1516 /// try-block:
1517 /// 'try' compound-statement handler-seq
1519 StmtResult Parser::ParseCXXTryBlock(AttributeList* Attr) {
1520 // FIXME: Add attributes?
1522 assert(Tok.is(tok::kw_try) && "Expected 'try'");
1524 SourceLocation TryLoc = ConsumeToken();
1525 return ParseCXXTryBlockCommon(TryLoc);
1528 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
1529 /// function-try-block.
1531 /// try-block:
1532 /// 'try' compound-statement handler-seq
1534 /// function-try-block:
1535 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1537 /// handler-seq:
1538 /// handler handler-seq[opt]
1540 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc) {
1541 if (Tok.isNot(tok::l_brace))
1542 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1543 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1544 StmtResult TryBlock(ParseCompoundStatement(0));
1545 if (TryBlock.isInvalid())
1546 return move(TryBlock);
1548 StmtVector Handlers(Actions);
1549 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1550 CXX0XAttributeList Attr = ParseCXX0XAttributes();
1551 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
1552 << Attr.Range;
1554 if (Tok.isNot(tok::kw_catch))
1555 return StmtError(Diag(Tok, diag::err_expected_catch));
1556 while (Tok.is(tok::kw_catch)) {
1557 StmtResult Handler(ParseCXXCatchBlock());
1558 if (!Handler.isInvalid())
1559 Handlers.push_back(Handler.release());
1561 // Don't bother creating the full statement if we don't have any usable
1562 // handlers.
1563 if (Handlers.empty())
1564 return StmtError();
1566 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
1569 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1571 /// handler:
1572 /// 'catch' '(' exception-declaration ')' compound-statement
1574 /// exception-declaration:
1575 /// type-specifier-seq declarator
1576 /// type-specifier-seq abstract-declarator
1577 /// type-specifier-seq
1578 /// '...'
1580 StmtResult Parser::ParseCXXCatchBlock() {
1581 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
1583 SourceLocation CatchLoc = ConsumeToken();
1585 SourceLocation LParenLoc = Tok.getLocation();
1586 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1587 return StmtError();
1589 // C++ 3.3.2p3:
1590 // The name in a catch exception-declaration is local to the handler and
1591 // shall not be redeclared in the outermost block of the handler.
1592 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope);
1594 // exception-declaration is equivalent to '...' or a parameter-declaration
1595 // without default arguments.
1596 Decl *ExceptionDecl = 0;
1597 if (Tok.isNot(tok::ellipsis)) {
1598 DeclSpec DS;
1599 if (ParseCXXTypeSpecifierSeq(DS))
1600 return StmtError();
1601 Declarator ExDecl(DS, Declarator::CXXCatchContext);
1602 ParseDeclarator(ExDecl);
1603 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
1604 } else
1605 ConsumeToken();
1607 if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
1608 return StmtError();
1610 if (Tok.isNot(tok::l_brace))
1611 return StmtError(Diag(Tok, diag::err_expected_lbrace));
1613 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
1614 StmtResult Block(ParseCompoundStatement(0));
1615 if (Block.isInvalid())
1616 return move(Block);
1618 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());