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