Amazing that there are still issues with the fields of anonymous struct/unions..
[clang.git] / lib / Parse / ParseStmt.cpp
blob5f932919b9250b7e6a00b8cbfcf3a474e0184e87
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 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();
91 SourceLocation AtLoc;
92 switch (Kind) {
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);
109 // PASS THROUGH.
111 default: {
112 if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
113 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
114 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
115 DeclEnd, attrs);
116 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
119 if (Tok.is(tok::r_brace)) {
120 Diag(Tok, diag::err_expected_statement);
121 return StmtError();
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))
133 ConsumeToken();
134 return StmtError();
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";
163 break;
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);
169 SemiError = "goto";
170 break;
171 case tok::kw_continue: // C99 6.8.6.2: continue-statement
172 Res = ParseContinueStatement(attrs);
173 SemiError = "continue";
174 break;
175 case tok::kw_break: // C99 6.8.6.3: break-statement
176 Res = ParseBreakStatement(attrs);
177 SemiError = "break";
178 break;
179 case tok::kw_return: // C99 6.8.6.4: return-statement
180 Res = ParseReturnStatement(attrs);
181 SemiError = "return";
182 break;
184 case tok::kw_asm: {
185 ProhibitAttributes(attrs);
186 bool msAsm = false;
187 Res = ParseAsmStatement(msAsm);
188 Res = Actions.ActOnFinishFullStmt(Res.get());
189 if (msAsm) return move(Res);
190 SemiError = "asm";
191 break;
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)) {
200 ConsumeToken();
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
204 // succeed.
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);
210 return move(Res);
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):
256 // case 1:
257 // case 2:
258 // case 3:
259 // case 4:
260 // case 5: etc.
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
269 // example above.
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.
278 do {
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
288 /// expression.
289 ColonProtectionRAIIObject ColonProtection(*this);
291 ExprResult LHS(ParseConstantExpression());
292 if (LHS.isInvalid()) {
293 SkipUntil(tok::colon);
294 return StmtError();
297 // GNU case range extension.
298 SourceLocation DotDotDotLoc;
299 ExprResult RHS;
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);
307 return StmtError();
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, ":");
322 } else {
323 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
324 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
325 << FixItHint::CreateInsertion(ExpectedLoc, ":");
326 ColonLoc = ExpectedLoc;
329 StmtResult Case =
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.
339 } else {
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);
345 else
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.
356 StmtResult SubStmt;
358 if (Tok.isNot(tok::r_brace)) {
359 SubStmt = ParseStatement();
360 } else {
361 // Nicely diagnose the common error "switch (X) { case 4: }", which is
362 // not valid.
363 // FIXME: add insertion hint.
364 Diag(Tok, diag::err_label_end_of_compound_statement);
365 SubStmt = true;
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, ":");
399 } else {
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);
409 return StmtError();
412 StmtResult SubStmt(ParseStatement());
413 if (SubStmt.isInvalid())
414 return StmtError();
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]
427 /// block-item-list:
428 /// block-item
429 /// block-item-list block-item
431 /// block-item:
432 /// declaration
433 /// [GNU] '__extension__' declaration
434 /// statement
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,
449 bool isStmtExpr) {
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
466 /// stack.
467 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
468 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
469 Tok.getLocation(),
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();
483 continue;
486 StmtResult R;
487 if (Tok.isNot(tok::kw___extension__)) {
488 R = ParseStatementOrDeclaration(Stmts, false);
489 } else {
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__))
496 ConsumeToken();
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,
510 attrs);
511 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
512 } else {
513 // Otherwise this was a unary __extension__ marker.
514 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
516 if (Res.isInvalid()) {
517 SkipUntil(tok::semi);
518 continue;
521 // FIXME: Use attributes?
522 // Eat the semicolon at the end of stmt and convert the expr into a
523 // statement.
524 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
525 R = Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.get()));
529 if (R.isUsable())
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) << "{";
537 return StmtError();
540 SourceLocation RBraceLoc = ConsumeBrace();
541 return Actions.ActOnCompoundStmt(LBraceLoc, RBraceLoc, move_arg(Stmts),
542 isStmtExpr);
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,
557 Decl *&DeclResult,
558 SourceLocation Loc,
559 bool ConvertToBoolean) {
560 SourceLocation LParenLoc = ConsumeParen();
561 if (getLang().CPlusPlus)
562 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
563 else {
564 ExprResult = ParseExpression();
565 DeclResult = 0;
567 // If required, convert to a boolean value.
568 if (!ExprResult.isInvalid() && ConvertToBoolean)
569 ExprResult
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))
581 return true;
584 // Otherwise the condition is valid or the rparen is present.
585 MatchRHSPunctuation(tok::r_paren, LParenLoc);
586 return false;
590 /// ParseIfStatement
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);
606 return StmtError();
609 bool C99orCXX = getLang().C99 || getLang().CPlusPlus;
611 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
612 // the case for C90.
614 // C++ 6.4p3:
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
617 // condition.
618 // C++ 3.3.2p4:
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.
626 ExprResult CondExp;
627 Decl *CondVar = 0;
628 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
629 return StmtError();
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.
637 // C++ 6.4p1:
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.
659 InnerScope.Exit();
661 // If it has an else, parse it.
662 SourceLocation ElseLoc;
663 SourceLocation ElseStmtLoc;
664 StmtResult ElseStmt;
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
673 // cases.
675 // C++ 6.4p1:
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.
685 InnerScope.Exit();
688 IfScope.Exit();
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)
693 return StmtError();
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.
702 return StmtError();
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);
728 return StmtError();
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.
736 // C++ 6.4p3:
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
739 // condition.
740 // C++ 3.3.2p4:
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;
746 if (C99orCXX)
747 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
748 ParseScope SwitchScope(this, ScopeFlags);
750 // Parse the condition.
751 ExprResult Cond;
752 Decl *CondVar = 0;
753 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
754 return StmtError();
756 StmtResult Switch
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)) {
765 ConsumeBrace();
766 SkipUntil(tok::r_brace, false, false);
767 } else
768 SkipUntil(tok::semi);
769 return move(Switch);
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.
776 // C++ 6.4p1:
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());
789 // Pop the scopes.
790 InnerScope.Exit();
791 SwitchScope.Exit();
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);
814 return StmtError();
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.
822 // C++ 6.4p3:
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
825 // condition.
826 // C++ 3.3.2p4:
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).
831 unsigned ScopeFlags;
832 if (C99orCXX)
833 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
834 Scope::DeclScope | Scope::ControlScope;
835 else
836 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
837 ParseScope WhileScope(this, ScopeFlags);
839 // Parse the condition.
840 ExprResult Cond;
841 Decl *CondVar = 0;
842 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
843 return StmtError();
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.
851 // C++ 6.5p2:
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.
865 InnerScope.Exit();
866 WhileScope.Exit();
868 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
869 return StmtError();
871 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
874 /// ParseDoStatement
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.
886 unsigned ScopeFlags;
887 if (getLang().C99)
888 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
889 else
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.
898 // C++ 6.5p2:
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.
910 InnerScope.Exit();
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);
918 return StmtError();
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);
925 return StmtError();
928 // Parse the parenthesized condition.
929 SourceLocation LPLoc = ConsumeParen();
930 ExprResult Cond = ParseExpression();
931 SourceLocation RPLoc = MatchRHSPunctuation(tok::r_paren, LPLoc);
932 DoScope.Exit();
934 if (Cond.isInvalid() || Body.isInvalid())
935 return StmtError();
937 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, LPLoc,
938 Cond.get(), RPLoc);
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] ')'
946 /// [C++] statement
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);
963 return StmtError();
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.
971 // C++ 6.4p3:
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
974 // condition.
975 // C++ 3.3.2p4:
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).
979 // C++ 6.5.3p1:
980 // Names declared in the for-init-statement are in the same declarative-region
981 // as those declared in the condition.
983 unsigned ScopeFlags;
984 if (C99orCXXorObjC)
985 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
986 Scope::DeclScope | Scope::ControlScope;
987 else
988 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
990 ParseScope ForScope(this, ScopeFlags);
992 SourceLocation LParenLoc = ConsumeParen();
993 ExprResult Value;
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 ';'.
1013 ConsumeToken();
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;
1029 ConsumeToken();
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();
1040 } else {
1041 Diag(Tok, diag::err_expected_semi_for);
1042 SkipUntil(tok::semi);
1044 } else {
1045 Value = ParseExpression();
1047 ForEach = isTokIdentifier_in();
1049 // Turn the expression into a stmt.
1050 if (!Value.isInvalid()) {
1051 if (ForEach)
1052 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1053 else
1054 FirstPart = Actions.ActOnExprStmt(Actions.MakeFullExpr(Value.get()));
1057 if (Tok.is(tok::semi)) {
1058 ConsumeToken();
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();
1067 } else {
1068 if (!Value.isInvalid()) Diag(Tok, diag::err_expected_semi_for);
1069 SkipUntil(tok::semi);
1072 if (!ForEach) {
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 (...;;
1076 // no second part.
1077 } else {
1078 ExprResult Second;
1079 if (getLang().CPlusPlus)
1080 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1081 else {
1082 Second = ParseExpression();
1083 if (!Second.isInvalid())
1084 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1085 Second.get());
1087 SecondPartIsInvalid = Second.isInvalid();
1088 SecondPart = Actions.MakeFullExpr(Second.get());
1091 if (Tok.is(tok::semi)) {
1092 ConsumeToken();
1093 } else {
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());
1105 // Match the ')'.
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.
1112 // C++ 6.5p2:
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.
1126 InnerScope.Exit();
1128 // Leave the for-scope.
1129 ForScope.Exit();
1131 if (Body.isInvalid())
1132 return StmtError();
1134 if (!ForEach)
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,
1142 Body.take());
1145 /// ParseGotoStatement
1146 /// jump-statement:
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'.
1158 StmtResult Res;
1159 if (Tok.is(tok::identifier)) {
1160 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(),
1161 Tok.getIdentifierInfo());
1162 ConsumeToken();
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);
1170 return StmtError();
1172 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1173 } else {
1174 Diag(Tok, diag::err_expected_ident);
1175 return StmtError();
1178 return move(Res);
1181 /// ParseContinueStatement
1182 /// jump-statement:
1183 /// 'continue' ';'
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
1195 /// jump-statement:
1196 /// 'break' ';'
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
1208 /// jump-statement:
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'.
1216 ExprResult R;
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);
1222 return StmtError();
1225 R = ParseExpression();
1226 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1227 SkipUntil(tok::semi, false, true);
1228 return StmtError();
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;
1240 do {
1241 EndLoc = Tok.getLocation();
1242 ConsumeAnyToken();
1243 } while (BraceCount > savedBraceCount && Tok.isNot(tok::eof));
1244 } else {
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);
1250 do {
1251 EndLoc = TokLoc;
1252 ConsumeAnyToken();
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));
1258 Token t;
1259 t.setKind(tok::string_literal);
1260 t.setLiteralData("\"/*FIXME: not done*/\"");
1261 t.clearFlag(Token::NeedsCleaning);
1262 t.setLength(21);
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),
1270 EndLoc, true);
1273 /// ParseAsmStatement - Parse a GNU extended asm statement.
1274 /// 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()) {
1305 msAsm = true;
1306 return FuzzyParseMicrosoftAsmStatement(AsmLoc);
1308 DeclSpec DS;
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);
1323 return StmtError();
1325 Loc = ConsumeParen();
1327 ExprResult AsmString(ParseAsmStringLiteral());
1328 if (AsmString.isInvalid())
1329 return StmtError();
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),
1343 RParenLoc);
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);
1351 ConsumeToken();
1353 if (!AteExtraColon &&
1354 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1355 return StmtError();
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 ": :".
1364 if (AteExtraColon)
1365 AteExtraColon = false;
1366 else {
1367 AteExtraColon = Tok.is(tok::coloncolon);
1368 ConsumeToken();
1371 if (!AteExtraColon &&
1372 ParseAsmOperandsOpt(Names, Constraints, Exprs))
1373 return StmtError();
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)) {
1384 if (!AteExtraColon)
1385 ConsumeToken();
1387 // Parse the asm-string list for clobbers if present.
1388 if (Tok.isNot(tok::r_paren)) {
1389 while (1) {
1390 ExprResult Clobber(ParseAsmStringLiteral());
1392 if (Clobber.isInvalid())
1393 break;
1395 Clobbers.push_back(Clobber.release());
1397 if (Tok.isNot(tok::comma)) break;
1398 ConsumeToken();
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),
1408 RParenLoc);
1411 /// ParseAsmOperands - Parse the asm-operands production as used by
1412 /// asm-statement, assuming the leading ':' token was eaten.
1414 /// [GNU] asm-operands:
1415 /// asm-operand
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))
1429 return false;
1431 while (1) {
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);
1439 return true;
1442 IdentifierInfo *II = Tok.getIdentifierInfo();
1443 ConsumeToken();
1445 Names.push_back(II);
1446 MatchRHSPunctuation(tok::r_square, Loc);
1447 } else
1448 Names.push_back(0);
1450 ExprResult Constraint(ParseAsmStringLiteral());
1451 if (Constraint.isInvalid()) {
1452 SkipUntil(tok::r_paren);
1453 return true;
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);
1460 return true;
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);
1469 return true;
1471 Exprs.push_back(Res.release());
1472 // Eat the comma and continue parsing if it exists.
1473 if (Tok.isNot(tok::comma)) return false;
1474 ConsumeToken();
1477 return true;
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);
1543 ConsumeBrace();
1544 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false,
1545 /*StopAtCodeCompletion=*/true)) {
1546 PA.Commit();
1547 return true;
1550 PA.Revert();
1551 return false;
1554 /// ParseCXXTryBlock - Parse a C++ try-block.
1556 /// 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.
1571 /// try-block:
1572 /// 'try' compound-statement handler-seq
1574 /// function-try-block:
1575 /// 'try' ctor-initializer[opt] compound-statement handler-seq
1577 /// 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
1601 // handlers.
1602 if (Handlers.empty())
1603 return StmtError();
1605 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), move_arg(Handlers));
1608 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
1610 /// handler:
1611 /// 'catch' '(' exception-declaration ')' compound-statement
1613 /// exception-declaration:
1614 /// type-specifier-seq declarator
1615 /// type-specifier-seq abstract-declarator
1616 /// type-specifier-seq
1617 /// '...'
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))
1626 return StmtError();
1628 // C++ 3.3.2p3:
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)) {
1637 DeclSpec DS;
1638 if (ParseCXXTypeSpecifierSeq(DS))
1639 return StmtError();
1640 Declarator ExDecl(DS, Declarator::CXXCatchContext);
1641 ParseDeclarator(ExDecl);
1642 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
1643 } else
1644 ConsumeToken();
1646 if (MatchRHSPunctuation(tok::r_paren, LParenLoc).isInvalid())
1647 return StmtError();
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())
1656 return move(Block);
1658 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());