1 //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Statement and Block portions of the Parser
13 //===----------------------------------------------------------------------===//
15 #include "clang/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Basic/PrettyStackTrace.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Scope.h"
25 #include "clang/Sema/TypoCorrection.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCParser/MCAsmParser.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSubtargetInfo.h"
33 #include "llvm/MC/MCTargetAsmParser.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/ADT/SmallString.h"
38 using namespace clang;
40 //===----------------------------------------------------------------------===//
41 // C99 6.8: Statements and Blocks.
42 //===----------------------------------------------------------------------===//
44 /// \brief Parse a standalone statement (for instance, as the body of an 'if',
45 /// 'while', or 'for').
46 StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) {
49 // We may get back a null statement if we found a #pragma. Keep going until
50 // we get an actual statement.
53 Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
54 } while (!Res.isInvalid() && !Res.get());
59 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
60 /// StatementOrDeclaration:
66 /// compound-statement
67 /// expression-statement
68 /// selection-statement
69 /// iteration-statement
71 /// [C++] declaration-statement
73 /// [MS] seh-try-block
74 /// [OBC] objc-throw-statement
75 /// [OBC] objc-try-catch-statement
76 /// [OBC] objc-synchronized-statement
77 /// [GNU] asm-statement
78 /// [OMP] openmp-construct [TODO]
80 /// labeled-statement:
81 /// identifier ':' statement
82 /// 'case' constant-expression ':' statement
83 /// 'default' ':' statement
85 /// selection-statement:
89 /// iteration-statement:
94 /// expression-statement:
95 /// expression[opt] ';'
98 /// 'goto' identifier ';'
101 /// 'return' expression[opt] ';'
102 /// [GNU] 'goto' '*' expression ';'
104 /// [OBC] objc-throw-statement:
105 /// [OBC] '@' 'throw' expression ';'
106 /// [OBC] '@' 'throw' ';'
109 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
110 SourceLocation *TrailingElseLoc) {
112 ParenBraceBracketBalancer BalancerRAIIObj(*this);
114 ParsedAttributesWithRange Attrs(AttrFactory);
115 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true);
117 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts,
118 OnlyStatement, TrailingElseLoc, Attrs);
120 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
121 "attributes on empty statement");
123 if (Attrs.empty() || Res.isInvalid())
126 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range);
130 class StatementFilterCCC : public CorrectionCandidateCallback {
132 StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
133 WantTypeSpecifiers = nextTok.is(tok::l_paren) || nextTok.is(tok::less) ||
134 nextTok.is(tok::identifier) || nextTok.is(tok::star) ||
135 nextTok.is(tok::amp) || nextTok.is(tok::l_square);
136 WantExpressionKeywords = nextTok.is(tok::l_paren) ||
137 nextTok.is(tok::identifier) ||
138 nextTok.is(tok::arrow) || nextTok.is(tok::period);
139 WantRemainingKeywords = nextTok.is(tok::l_paren) || nextTok.is(tok::semi) ||
140 nextTok.is(tok::identifier) ||
141 nextTok.is(tok::l_brace);
142 WantCXXNamedCasts = false;
145 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
146 if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
147 return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
148 if (NextToken.is(tok::equal))
149 return candidate.getCorrectionDeclAs<VarDecl>();
150 if (NextToken.is(tok::period) &&
151 candidate.getCorrectionDeclAs<NamespaceDecl>())
153 return CorrectionCandidateCallback::ValidateCandidate(candidate);
162 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts,
163 bool OnlyStatement, SourceLocation *TrailingElseLoc,
164 ParsedAttributesWithRange &Attrs) {
165 const char *SemiError = 0;
168 // Cases in this switch statement should fall through if the parser expects
169 // the token to end in a semicolon (in which case SemiError should be set),
170 // or they directly 'return;' if not.
172 tok::TokenKind Kind = Tok.getKind();
173 SourceLocation AtLoc;
175 case tok::at: // May be a @try or @throw statement
177 ProhibitAttributes(Attrs); // TODO: is it correct?
178 AtLoc = ConsumeToken(); // consume @
179 return ParseObjCAtStatement(AtLoc);
182 case tok::code_completion:
183 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
187 case tok::identifier: {
188 Token Next = NextToken();
189 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
190 // identifier ':' statement
191 return ParseLabeledStatement(Attrs);
194 // Look up the identifier, and typo-correct it to a keyword if it's not
196 if (Next.isNot(tok::coloncolon)) {
197 // Try to limit which sets of keywords should be included in typo
198 // correction based on what the next token is.
199 StatementFilterCCC Validator(Next);
200 if (TryAnnotateName(/*IsAddressOfOperand*/false, &Validator)
202 // Handle errors here by skipping up to the next semicolon or '}', and
203 // eat the semicolon if that's what stopped us.
204 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
205 if (Tok.is(tok::semi))
210 // If the identifier was typo-corrected, try again.
211 if (Tok.isNot(tok::identifier))
219 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) {
220 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
221 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext,
223 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
226 if (Tok.is(tok::r_brace)) {
227 Diag(Tok, diag::err_expected_statement);
231 return ParseExprStatement();
234 case tok::kw_case: // C99 6.8.1: labeled-statement
235 return ParseCaseStatement();
236 case tok::kw_default: // C99 6.8.1: labeled-statement
237 return ParseDefaultStatement();
239 case tok::l_brace: // C99 6.8.2: compound-statement
240 return ParseCompoundStatement();
241 case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
242 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
243 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
246 case tok::kw_if: // C99 6.8.4.1: if-statement
247 return ParseIfStatement(TrailingElseLoc);
248 case tok::kw_switch: // C99 6.8.4.2: switch-statement
249 return ParseSwitchStatement(TrailingElseLoc);
251 case tok::kw_while: // C99 6.8.5.1: while-statement
252 return ParseWhileStatement(TrailingElseLoc);
253 case tok::kw_do: // C99 6.8.5.2: do-statement
254 Res = ParseDoStatement();
255 SemiError = "do/while";
257 case tok::kw_for: // C99 6.8.5.3: for-statement
258 return ParseForStatement(TrailingElseLoc);
260 case tok::kw_goto: // C99 6.8.6.1: goto-statement
261 Res = ParseGotoStatement();
264 case tok::kw_continue: // C99 6.8.6.2: continue-statement
265 Res = ParseContinueStatement();
266 SemiError = "continue";
268 case tok::kw_break: // C99 6.8.6.3: break-statement
269 Res = ParseBreakStatement();
272 case tok::kw_return: // C99 6.8.6.4: return-statement
273 Res = ParseReturnStatement();
274 SemiError = "return";
278 ProhibitAttributes(Attrs);
280 Res = ParseAsmStatement(msAsm);
281 Res = Actions.ActOnFinishFullStmt(Res.get());
282 if (msAsm) return Res;
287 case tok::kw_try: // C++ 15: try-block
288 return ParseCXXTryBlock();
291 ProhibitAttributes(Attrs); // TODO: is it correct?
292 return ParseSEHTryBlock();
294 case tok::annot_pragma_vis:
295 ProhibitAttributes(Attrs);
296 HandlePragmaVisibility();
299 case tok::annot_pragma_pack:
300 ProhibitAttributes(Attrs);
304 case tok::annot_pragma_msstruct:
305 ProhibitAttributes(Attrs);
306 HandlePragmaMSStruct();
309 case tok::annot_pragma_align:
310 ProhibitAttributes(Attrs);
314 case tok::annot_pragma_weak:
315 ProhibitAttributes(Attrs);
319 case tok::annot_pragma_weakalias:
320 ProhibitAttributes(Attrs);
321 HandlePragmaWeakAlias();
324 case tok::annot_pragma_redefine_extname:
325 ProhibitAttributes(Attrs);
326 HandlePragmaRedefineExtname();
329 case tok::annot_pragma_fp_contract:
330 ProhibitAttributes(Attrs);
331 Diag(Tok, diag::err_pragma_fp_contract_scope);
335 case tok::annot_pragma_opencl_extension:
336 ProhibitAttributes(Attrs);
337 HandlePragmaOpenCLExtension();
340 case tok::annot_pragma_captured:
341 ProhibitAttributes(Attrs);
342 return HandlePragmaCaptured();
344 case tok::annot_pragma_openmp:
345 ProhibitAttributes(Attrs);
346 return ParseOpenMPDeclarativeOrExecutableDirective();
350 // If we reached this code, the statement must end in a semicolon.
351 if (Tok.is(tok::semi)) {
353 } else if (!Res.isInvalid()) {
354 // If the result was valid, then we do want to diagnose this. Use
355 // ExpectAndConsume to emit the diagnostic, even though we know it won't
357 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
358 // Skip until we see a } or ;, but don't eat it.
359 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
365 /// \brief Parse an expression statement.
366 StmtResult Parser::ParseExprStatement() {
367 // If a case keyword is missing, this is where it should be inserted.
368 Token OldToken = Tok;
370 // expression[opt] ';'
371 ExprResult Expr(ParseExpression());
372 if (Expr.isInvalid()) {
373 // If the expression is invalid, skip ahead to the next semicolon or '}'.
374 // Not doing this opens us up to the possibility of infinite loops if
375 // ParseExpression does not consume any tokens.
376 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
377 if (Tok.is(tok::semi))
379 return Actions.ActOnExprStmtError();
382 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
383 Actions.CheckCaseExpression(Expr.get())) {
384 // If a constant expression is followed by a colon inside a switch block,
385 // suggest a missing case keyword.
386 Diag(OldToken, diag::err_expected_case_before_expression)
387 << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
389 // Recover parsing as a case statement.
390 return ParseCaseStatement(/*MissingCase=*/true, Expr);
393 // Otherwise, eat the semicolon.
394 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
395 return Actions.ActOnExprStmt(Expr);
398 StmtResult Parser::ParseSEHTryBlock() {
399 assert(Tok.is(tok::kw___try) && "Expected '__try'");
400 SourceLocation Loc = ConsumeToken();
401 return ParseSEHTryBlockCommon(Loc);
404 /// ParseSEHTryBlockCommon
407 /// '__try' compound-statement seh-handler
411 /// seh-finally-block
413 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
414 if(Tok.isNot(tok::l_brace))
415 return StmtError(Diag(Tok,diag::err_expected_lbrace));
417 StmtResult TryBlock(ParseCompoundStatement());
418 if(TryBlock.isInvalid())
422 if (Tok.is(tok::identifier) &&
423 Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
424 SourceLocation Loc = ConsumeToken();
425 Handler = ParseSEHExceptBlock(Loc);
426 } else if (Tok.is(tok::kw___finally)) {
427 SourceLocation Loc = ConsumeToken();
428 Handler = ParseSEHFinallyBlock(Loc);
430 return StmtError(Diag(Tok,diag::err_seh_expected_handler));
433 if(Handler.isInvalid())
436 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
442 /// ParseSEHExceptBlock - Handle __except
444 /// seh-except-block:
445 /// '__except' '(' seh-filter-expression ')' compound-statement
447 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
448 PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
449 raii2(Ident___exception_code, false),
450 raii3(Ident_GetExceptionCode, false);
452 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen))
455 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
457 if (getLangOpts().Borland) {
458 Ident__exception_info->setIsPoisoned(false);
459 Ident___exception_info->setIsPoisoned(false);
460 Ident_GetExceptionInfo->setIsPoisoned(false);
462 ExprResult FilterExpr(ParseExpression());
464 if (getLangOpts().Borland) {
465 Ident__exception_info->setIsPoisoned(true);
466 Ident___exception_info->setIsPoisoned(true);
467 Ident_GetExceptionInfo->setIsPoisoned(true);
470 if(FilterExpr.isInvalid())
473 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen))
476 StmtResult Block(ParseCompoundStatement());
478 if(Block.isInvalid())
481 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take());
484 /// ParseSEHFinallyBlock - Handle __finally
486 /// seh-finally-block:
487 /// '__finally' compound-statement
489 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) {
490 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
491 raii2(Ident___abnormal_termination, false),
492 raii3(Ident_AbnormalTermination, false);
494 StmtResult Block(ParseCompoundStatement());
495 if(Block.isInvalid())
498 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take());
501 /// ParseLabeledStatement - We have an identifier and a ':' after it.
503 /// labeled-statement:
504 /// identifier ':' statement
505 /// [GNU] identifier ':' attributes[opt] statement
507 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
508 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
509 "Not an identifier!");
511 Token IdentTok = Tok; // Save the whole token.
512 ConsumeToken(); // eat the identifier.
514 assert(Tok.is(tok::colon) && "Not a label!");
516 // identifier ':' statement
517 SourceLocation ColonLoc = ConsumeToken();
519 // Read label attributes, if present.
521 if (Tok.is(tok::kw___attribute)) {
522 ParsedAttributesWithRange TempAttrs(AttrFactory);
523 ParseGNUAttributes(TempAttrs);
525 // In C++, GNU attributes only apply to the label if they are followed by a
526 // semicolon, to disambiguate label attributes from attributes on a labeled
529 // This doesn't quite match what GCC does; if the attribute list is empty
530 // and followed by a semicolon, GCC will reject (it appears to parse the
531 // attributes as part of a statement in that case). That looks like a bug.
532 if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
533 attrs.takeAllFrom(TempAttrs);
534 else if (isDeclarationStatement()) {
536 // FIXME: We should do this whether or not we have a declaration
537 // statement, but that doesn't work correctly (because ProhibitAttributes
538 // can't handle GNU attributes), so only call it in the one case where
539 // GNU attributes are allowed.
540 SubStmt = ParseStatementOrDeclarationAfterAttributes(
541 Stmts, /*OnlyStmts*/ true, 0, TempAttrs);
542 if (!TempAttrs.empty() && !SubStmt.isInvalid())
543 SubStmt = Actions.ProcessStmtAttributes(
544 SubStmt.get(), TempAttrs.getList(), TempAttrs.Range);
546 Diag(Tok, diag::err_expected_semi_after) << "__attribute__";
550 // If we've not parsed a statement yet, parse one now.
551 if (!SubStmt.isInvalid() && !SubStmt.isUsable())
552 SubStmt = ParseStatement();
554 // Broken substmt shouldn't prevent the label from being added to the AST.
555 if (SubStmt.isInvalid())
556 SubStmt = Actions.ActOnNullStmt(ColonLoc);
558 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
559 IdentTok.getLocation());
560 if (AttributeList *Attrs = attrs.getList()) {
561 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs);
565 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
569 /// ParseCaseStatement
570 /// labeled-statement:
571 /// 'case' constant-expression ':' statement
572 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
574 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
575 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
577 // It is very very common for code to contain many case statements recursively
578 // nested, as in (but usually without indentation):
585 // Parsing this naively works, but is both inefficient and can cause us to run
586 // out of stack space in our recursive descent parser. As a special case,
587 // flatten this recursion into an iterative loop. This is complex and gross,
588 // but all the grossness is constrained to ParseCaseStatement (and some
589 // weirdness in the actions), so this is just local grossness :).
591 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the
593 StmtResult TopLevelCase(true);
595 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
596 // gets updated each time a new case is parsed, and whose body is unset so
597 // far. When parsing 'case 4', this is the 'case 3' node.
598 Stmt *DeepestParsedCaseStmt = 0;
600 // While we have case statements, eat and stack them.
601 SourceLocation ColonLoc;
603 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
604 ConsumeToken(); // eat the 'case'.
606 if (Tok.is(tok::code_completion)) {
607 Actions.CodeCompleteCase(getCurScope());
612 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
613 /// Disable this form of error recovery while we're parsing the case
615 ColonProtectionRAIIObject ColonProtection(*this);
617 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression());
619 if (LHS.isInvalid()) {
620 SkipUntil(tok::colon, StopAtSemi);
624 // GNU case range extension.
625 SourceLocation DotDotDotLoc;
627 if (Tok.is(tok::ellipsis)) {
628 Diag(Tok, diag::ext_gnu_case_range);
629 DotDotDotLoc = ConsumeToken();
631 RHS = ParseConstantExpression();
632 if (RHS.isInvalid()) {
633 SkipUntil(tok::colon, StopAtSemi);
638 ColonProtection.restore();
640 if (Tok.is(tok::colon)) {
641 ColonLoc = ConsumeToken();
643 // Treat "case blah;" as a typo for "case blah:".
644 } else if (Tok.is(tok::semi)) {
645 ColonLoc = ConsumeToken();
646 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'"
647 << FixItHint::CreateReplacement(ColonLoc, ":");
649 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
650 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'"
651 << FixItHint::CreateInsertion(ExpectedLoc, ":");
652 ColonLoc = ExpectedLoc;
656 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc,
657 RHS.get(), ColonLoc);
659 // If we had a sema error parsing this case, then just ignore it and
660 // continue parsing the sub-stmt.
661 if (Case.isInvalid()) {
662 if (TopLevelCase.isInvalid()) // No parsed case stmts.
663 return ParseStatement();
664 // Otherwise, just don't add it as a nested case.
666 // If this is the first case statement we parsed, it becomes TopLevelCase.
667 // Otherwise we link it into the current chain.
668 Stmt *NextDeepest = Case.get();
669 if (TopLevelCase.isInvalid())
672 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
673 DeepestParsedCaseStmt = NextDeepest;
676 // Handle all case statements.
677 } while (Tok.is(tok::kw_case));
679 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!");
681 // If we found a non-case statement, start by parsing it.
684 if (Tok.isNot(tok::r_brace)) {
685 SubStmt = ParseStatement();
687 // Nicely diagnose the common error "switch (X) { case 4: }", which is
689 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
690 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
691 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
695 // Broken sub-stmt shouldn't prevent forming the case statement properly.
696 if (SubStmt.isInvalid())
697 SubStmt = Actions.ActOnNullStmt(SourceLocation());
699 // Install the body into the most deeply-nested case.
700 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
702 // Return the top level parsed statement tree.
706 /// ParseDefaultStatement
707 /// labeled-statement:
708 /// 'default' ':' statement
709 /// Note that this does not parse the 'statement' at the end.
711 StmtResult Parser::ParseDefaultStatement() {
712 assert(Tok.is(tok::kw_default) && "Not a default stmt!");
713 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
715 SourceLocation ColonLoc;
716 if (Tok.is(tok::colon)) {
717 ColonLoc = ConsumeToken();
719 // Treat "default;" as a typo for "default:".
720 } else if (Tok.is(tok::semi)) {
721 ColonLoc = ConsumeToken();
722 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'"
723 << FixItHint::CreateReplacement(ColonLoc, ":");
725 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
726 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'"
727 << FixItHint::CreateInsertion(ExpectedLoc, ":");
728 ColonLoc = ExpectedLoc;
733 if (Tok.isNot(tok::r_brace)) {
734 SubStmt = ParseStatement();
736 // Diagnose the common error "switch (X) {... default: }", which is
738 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
739 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
740 << FixItHint::CreateInsertion(AfterColonLoc, " ;");
744 // Broken sub-stmt shouldn't prevent forming the case statement properly.
745 if (SubStmt.isInvalid())
746 SubStmt = Actions.ActOnNullStmt(ColonLoc);
748 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
749 SubStmt.get(), getCurScope());
752 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
753 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope);
756 /// ParseCompoundStatement - Parse a "{}" block.
758 /// compound-statement: [C99 6.8.2]
759 /// { block-item-list[opt] }
760 /// [GNU] { label-declarations block-item-list } [TODO]
764 /// block-item-list block-item
768 /// [GNU] '__extension__' declaration
770 /// [OMP] openmp-directive [TODO]
772 /// [GNU] label-declarations:
773 /// [GNU] label-declaration
774 /// [GNU] label-declarations label-declaration
776 /// [GNU] label-declaration:
777 /// [GNU] '__label__' identifier-list ';'
779 /// [OMP] openmp-directive: [TODO]
780 /// [OMP] barrier-directive
781 /// [OMP] flush-directive
783 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
784 unsigned ScopeFlags) {
785 assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
787 // Enter a scope to hold everything within the compound stmt. Compound
788 // statements can always hold declarations.
789 ParseScope CompoundScope(this, ScopeFlags);
791 // Parse the statements in the body.
792 return ParseCompoundStatementBody(isStmtExpr);
795 /// Parse any pragmas at the start of the compound expression. We handle these
796 /// separately since some pragmas (FP_CONTRACT) must appear before any C
797 /// statement in the compound, but may be intermingled with other pragmas.
798 void Parser::ParseCompoundStatementLeadingPragmas() {
799 bool checkForPragmas = true;
800 while (checkForPragmas) {
801 switch (Tok.getKind()) {
802 case tok::annot_pragma_vis:
803 HandlePragmaVisibility();
805 case tok::annot_pragma_pack:
808 case tok::annot_pragma_msstruct:
809 HandlePragmaMSStruct();
811 case tok::annot_pragma_align:
814 case tok::annot_pragma_weak:
817 case tok::annot_pragma_weakalias:
818 HandlePragmaWeakAlias();
820 case tok::annot_pragma_redefine_extname:
821 HandlePragmaRedefineExtname();
823 case tok::annot_pragma_opencl_extension:
824 HandlePragmaOpenCLExtension();
826 case tok::annot_pragma_fp_contract:
827 HandlePragmaFPContract();
830 checkForPragmas = false;
837 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
838 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and
839 /// consume the '}' at the end of the block. It does not manipulate the scope
841 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
842 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
844 "in compound statement ('{}')");
846 // Record the state of the FP_CONTRACT pragma, restore on leaving the
847 // compound statement.
848 Sema::FPContractStateRAII SaveFPContractState(Actions);
850 InMessageExpressionRAIIObject InMessage(*this, false);
851 BalancedDelimiterTracker T(*this, tok::l_brace);
855 Sema::CompoundScopeRAII CompoundScope(Actions);
857 // Parse any pragmas at the beginning of the compound statement.
858 ParseCompoundStatementLeadingPragmas();
862 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
863 // only allowed at the start of a compound stmt regardless of the language.
864 while (Tok.is(tok::kw___label__)) {
865 SourceLocation LabelLoc = ConsumeToken();
867 SmallVector<Decl *, 8> DeclsInGroup;
869 if (Tok.isNot(tok::identifier)) {
870 Diag(Tok, diag::err_expected_ident);
874 IdentifierInfo *II = Tok.getIdentifierInfo();
875 SourceLocation IdLoc = ConsumeToken();
876 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
878 if (!Tok.is(tok::comma))
883 DeclSpec DS(AttrFactory);
885 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
886 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
888 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
890 Stmts.push_back(R.release());
893 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
894 if (Tok.is(tok::annot_pragma_unused)) {
895 HandlePragmaUnused();
899 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
900 Tok.is(tok::kw___if_not_exists))) {
901 ParseMicrosoftIfExistsStatement(Stmts);
906 if (Tok.isNot(tok::kw___extension__)) {
907 R = ParseStatementOrDeclaration(Stmts, false);
909 // __extension__ can start declarations and it can also be a unary
910 // operator for expressions. Consume multiple __extension__ markers here
911 // until we can determine which is which.
912 // FIXME: This loses extension expressions in the AST!
913 SourceLocation ExtLoc = ConsumeToken();
914 while (Tok.is(tok::kw___extension__))
917 ParsedAttributesWithRange attrs(AttrFactory);
918 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
920 // If this is the start of a declaration, parse it as such.
921 if (isDeclarationStatement()) {
922 // __extension__ silences extension warnings in the subdeclaration.
923 // FIXME: Save the __extension__ on the decl as a node somehow?
924 ExtensionRAIIObject O(Diags);
926 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
927 DeclGroupPtrTy Res = ParseDeclaration(Stmts,
928 Declarator::BlockContext, DeclEnd,
930 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
932 // Otherwise this was a unary __extension__ marker.
933 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
935 if (Res.isInvalid()) {
936 SkipUntil(tok::semi);
940 // FIXME: Use attributes?
941 // Eat the semicolon at the end of stmt and convert the expr into a
943 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
944 R = Actions.ActOnExprStmt(Res);
949 Stmts.push_back(R.release());
952 SourceLocation CloseLoc = Tok.getLocation();
954 // We broke out of the while loop because we found a '}' or EOF.
955 if (!T.consumeClose())
956 // Recover by creating a compound statement with what we parsed so far,
957 // instead of dropping everything and returning StmtError();
958 CloseLoc = T.getCloseLocation();
960 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
964 /// ParseParenExprOrCondition:
965 /// [C ] '(' expression ')'
966 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true]
968 /// This function parses and performs error recovery on the specified condition
969 /// or expression (depending on whether we're in C++ or C mode). This function
970 /// goes out of its way to recover well. It returns true if there was a parser
971 /// error (the right paren couldn't be found), which indicates that the caller
972 /// should try to recover harder. It returns false if the condition is
973 /// successfully parsed. Note that a successful parse can still have semantic
974 /// errors in the condition.
975 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult,
978 bool ConvertToBoolean) {
979 BalancedDelimiterTracker T(*this, tok::l_paren);
982 if (getLangOpts().CPlusPlus)
983 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
985 ExprResult = ParseExpression();
988 // If required, convert to a boolean value.
989 if (!ExprResult.isInvalid() && ConvertToBoolean)
991 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get());
994 // If the parser was confused by the condition and we don't have a ')', try to
995 // recover by skipping ahead to a semi and bailing out. If condexp is
996 // semantically invalid but we have well formed code, keep going.
997 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) {
998 SkipUntil(tok::semi);
999 // Skipping may have stopped if it found the containing ')'. If so, we can
1000 // continue parsing the if statement.
1001 if (Tok.isNot(tok::r_paren))
1005 // Otherwise the condition is valid or the rparen is present.
1008 // Check for extraneous ')'s to catch things like "if (foo())) {". We know
1009 // that all callers are looking for a statement after the condition, so ")"
1011 while (Tok.is(tok::r_paren)) {
1012 Diag(Tok, diag::err_extraneous_rparen_in_condition)
1013 << FixItHint::CreateRemoval(Tok.getLocation());
1021 /// ParseIfStatement
1022 /// if-statement: [C99 6.8.4.1]
1023 /// 'if' '(' expression ')' statement
1024 /// 'if' '(' expression ')' statement 'else' statement
1025 /// [C++] 'if' '(' condition ')' statement
1026 /// [C++] 'if' '(' condition ')' statement 'else' statement
1028 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1029 assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1030 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
1032 if (Tok.isNot(tok::l_paren)) {
1033 Diag(Tok, diag::err_expected_lparen_after) << "if";
1034 SkipUntil(tok::semi);
1038 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1040 // C99 6.8.4p3 - In C99, the if statement is a block. This is not
1041 // the case for C90.
1044 // A name introduced by a declaration in a condition is in scope from its
1045 // point of declaration until the end of the substatements controlled by the
1048 // Names declared in the for-init-statement, and in the condition of if,
1049 // while, for, and switch statements are local to the if, while, for, or
1050 // switch statement (including the controlled statement).
1052 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1054 // Parse the condition.
1057 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true))
1060 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc));
1062 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1063 // there is no compound stmt. C90 does not have this clause. We only do this
1064 // if the body isn't a compound statement to avoid push/pop in common cases.
1067 // The substatement in a selection-statement (each substatement, in the else
1068 // form of the if statement) implicitly defines a local scope.
1070 // For C++ we create a scope for the condition and a new scope for
1071 // substatements because:
1072 // -When the 'then' scope exits, we want the condition declaration to still be
1073 // active for the 'else' scope too.
1074 // -Sema will detect name clashes by considering declarations of a
1075 // 'ControlScope' as part of its direct subscope.
1076 // -If we wanted the condition and substatement to be in the same scope, we
1077 // would have to notify ParseStatement not to create a new scope. It's
1078 // simpler to let it create a new scope.
1080 ParseScope InnerScope(this, Scope::DeclScope,
1081 C99orCXX && Tok.isNot(tok::l_brace));
1083 // Read the 'then' stmt.
1084 SourceLocation ThenStmtLoc = Tok.getLocation();
1086 SourceLocation InnerStatementTrailingElseLoc;
1087 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
1089 // Pop the 'if' scope if needed.
1092 // If it has an else, parse it.
1093 SourceLocation ElseLoc;
1094 SourceLocation ElseStmtLoc;
1095 StmtResult ElseStmt;
1097 if (Tok.is(tok::kw_else)) {
1098 if (TrailingElseLoc)
1099 *TrailingElseLoc = Tok.getLocation();
1101 ElseLoc = ConsumeToken();
1102 ElseStmtLoc = Tok.getLocation();
1104 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1105 // there is no compound stmt. C90 does not have this clause. We only do
1106 // this if the body isn't a compound statement to avoid push/pop in common
1110 // The substatement in a selection-statement (each substatement, in the else
1111 // form of the if statement) implicitly defines a local scope.
1113 ParseScope InnerScope(this, Scope::DeclScope,
1114 C99orCXX && Tok.isNot(tok::l_brace));
1116 ElseStmt = ParseStatement();
1118 // Pop the 'else' scope if needed.
1120 } else if (Tok.is(tok::code_completion)) {
1121 Actions.CodeCompleteAfterIf(getCurScope());
1124 } else if (InnerStatementTrailingElseLoc.isValid()) {
1125 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1130 // If the then or else stmt is invalid and the other is valid (and present),
1131 // make turn the invalid one into a null stmt to avoid dropping the other
1132 // part. If both are invalid, return error.
1133 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1134 (ThenStmt.isInvalid() && ElseStmt.get() == 0) ||
1135 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) {
1136 // Both invalid, or one is invalid and other is non-present: return error.
1140 // Now if either are invalid, replace with a ';'.
1141 if (ThenStmt.isInvalid())
1142 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1143 if (ElseStmt.isInvalid())
1144 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1146 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(),
1147 ElseLoc, ElseStmt.get());
1150 /// ParseSwitchStatement
1151 /// switch-statement:
1152 /// 'switch' '(' expression ')' statement
1153 /// [C++] 'switch' '(' condition ')' statement
1154 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1155 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1156 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
1158 if (Tok.isNot(tok::l_paren)) {
1159 Diag(Tok, diag::err_expected_lparen_after) << "switch";
1160 SkipUntil(tok::semi);
1164 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1166 // C99 6.8.4p3 - In C99, the switch statement is a block. This is
1167 // not the case for C90. Start the switch scope.
1170 // A name introduced by a declaration in a condition is in scope from its
1171 // point of declaration until the end of the substatements controlled by the
1174 // Names declared in the for-init-statement, and in the condition of if,
1175 // while, for, and switch statements are local to the if, while, for, or
1176 // switch statement (including the controlled statement).
1178 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope;
1180 ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1181 ParseScope SwitchScope(this, ScopeFlags);
1183 // Parse the condition.
1186 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false))
1190 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar);
1192 if (Switch.isInvalid()) {
1193 // Skip the switch body.
1194 // FIXME: This is not optimal recovery, but parsing the body is more
1195 // dangerous due to the presence of case and default statements, which
1196 // will have no place to connect back with the switch.
1197 if (Tok.is(tok::l_brace)) {
1199 SkipUntil(tok::r_brace);
1201 SkipUntil(tok::semi);
1205 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1206 // there is no compound stmt. C90 does not have this clause. We only do this
1207 // if the body isn't a compound statement to avoid push/pop in common cases.
1210 // The substatement in a selection-statement (each substatement, in the else
1211 // form of the if statement) implicitly defines a local scope.
1213 // See comments in ParseIfStatement for why we create a scope for the
1214 // condition and a new scope for substatement in C++.
1216 ParseScope InnerScope(this, Scope::DeclScope,
1217 C99orCXX && Tok.isNot(tok::l_brace));
1219 // Read the body statement.
1220 StmtResult Body(ParseStatement(TrailingElseLoc));
1226 if (Body.isInvalid()) {
1227 // FIXME: Remove the case statement list from the Switch statement.
1229 // Put the synthesized null statement on the same line as the end of switch
1231 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd();
1232 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
1235 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1238 /// ParseWhileStatement
1239 /// while-statement: [C99 6.8.5.1]
1240 /// 'while' '(' expression ')' statement
1241 /// [C++] 'while' '(' condition ')' statement
1242 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1243 assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1244 SourceLocation WhileLoc = Tok.getLocation();
1245 ConsumeToken(); // eat the 'while'.
1247 if (Tok.isNot(tok::l_paren)) {
1248 Diag(Tok, diag::err_expected_lparen_after) << "while";
1249 SkipUntil(tok::semi);
1253 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1255 // C99 6.8.5p5 - In C99, the while statement is a block. This is not
1256 // the case for C90. Start the loop scope.
1259 // A name introduced by a declaration in a condition is in scope from its
1260 // point of declaration until the end of the substatements controlled by the
1263 // Names declared in the for-init-statement, and in the condition of if,
1264 // while, for, and switch statements are local to the if, while, for, or
1265 // switch statement (including the controlled statement).
1267 unsigned ScopeFlags;
1269 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1270 Scope::DeclScope | Scope::ControlScope;
1272 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1273 ParseScope WhileScope(this, ScopeFlags);
1275 // Parse the condition.
1278 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true))
1281 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc));
1283 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1284 // there is no compound stmt. C90 does not have this clause. We only do this
1285 // if the body isn't a compound statement to avoid push/pop in common cases.
1288 // The substatement in an iteration-statement implicitly defines a local scope
1289 // which is entered and exited each time through the loop.
1291 // See comments in ParseIfStatement for why we create a scope for the
1292 // condition and a new scope for substatement in C++.
1294 ParseScope InnerScope(this, Scope::DeclScope,
1295 C99orCXX && Tok.isNot(tok::l_brace));
1297 // Read the body statement.
1298 StmtResult Body(ParseStatement(TrailingElseLoc));
1300 // Pop the body scope if needed.
1304 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid())
1307 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get());
1310 /// ParseDoStatement
1311 /// do-statement: [C99 6.8.5.2]
1312 /// 'do' statement 'while' '(' expression ')' ';'
1313 /// Note: this lets the caller parse the end ';'.
1314 StmtResult Parser::ParseDoStatement() {
1315 assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1316 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
1318 // C99 6.8.5p5 - In C99, the do statement is a block. This is not
1319 // the case for C90. Start the loop scope.
1320 unsigned ScopeFlags;
1321 if (getLangOpts().C99)
1322 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1324 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1326 ParseScope DoScope(this, ScopeFlags);
1328 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1329 // there is no compound stmt. C90 does not have this clause. We only do this
1330 // if the body isn't a compound statement to avoid push/pop in common cases.
1333 // The substatement in an iteration-statement implicitly defines a local scope
1334 // which is entered and exited each time through the loop.
1336 ParseScope InnerScope(this, Scope::DeclScope,
1337 (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
1338 Tok.isNot(tok::l_brace));
1340 // Read the body statement.
1341 StmtResult Body(ParseStatement());
1343 // Pop the body scope if needed.
1346 if (Tok.isNot(tok::kw_while)) {
1347 if (!Body.isInvalid()) {
1348 Diag(Tok, diag::err_expected_while);
1349 Diag(DoLoc, diag::note_matching) << "do";
1350 SkipUntil(tok::semi, StopBeforeMatch);
1354 SourceLocation WhileLoc = ConsumeToken();
1356 if (Tok.isNot(tok::l_paren)) {
1357 Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1358 SkipUntil(tok::semi, StopBeforeMatch);
1362 // Parse the parenthesized expression.
1363 BalancedDelimiterTracker T(*this, tok::l_paren);
1366 // A do-while expression is not a condition, so can't have attributes.
1367 DiagnoseAndSkipCXX11Attributes();
1369 ExprResult Cond = ParseExpression();
1373 if (Cond.isInvalid() || Body.isInvalid())
1376 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1377 Cond.get(), T.getCloseLocation());
1380 /// ParseForStatement
1381 /// for-statement: [C99 6.8.5.3]
1382 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1383 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1384 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1386 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement
1387 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1388 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1390 /// [C++] for-init-statement:
1391 /// [C++] expression-statement
1392 /// [C++] simple-declaration
1394 /// [C++0x] for-range-declaration:
1395 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
1396 /// [C++0x] for-range-initializer:
1397 /// [C++0x] expression
1398 /// [C++0x] braced-init-list [TODO]
1399 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1400 assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1401 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
1403 if (Tok.isNot(tok::l_paren)) {
1404 Diag(Tok, diag::err_expected_lparen_after) << "for";
1405 SkipUntil(tok::semi);
1409 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1410 getLangOpts().ObjC1;
1412 // C99 6.8.5p5 - In C99, the for statement is a block. This is not
1413 // the case for C90. Start the loop scope.
1416 // A name introduced by a declaration in a condition is in scope from its
1417 // point of declaration until the end of the substatements controlled by the
1420 // Names declared in the for-init-statement, and in the condition of if,
1421 // while, for, and switch statements are local to the if, while, for, or
1422 // switch statement (including the controlled statement).
1424 // Names declared in the for-init-statement are in the same declarative-region
1425 // as those declared in the condition.
1427 unsigned ScopeFlags;
1429 ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1430 Scope::DeclScope | Scope::ControlScope;
1432 ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1434 ParseScope ForScope(this, ScopeFlags);
1436 BalancedDelimiterTracker T(*this, tok::l_paren);
1441 bool ForEach = false, ForRange = false;
1442 StmtResult FirstPart;
1443 bool SecondPartIsInvalid = false;
1444 FullExprArg SecondPart(Actions);
1445 ExprResult Collection;
1446 ForRangeInit ForRangeInit;
1447 FullExprArg ThirdPart(Actions);
1448 Decl *SecondVar = 0;
1450 if (Tok.is(tok::code_completion)) {
1451 Actions.CodeCompleteOrdinaryName(getCurScope(),
1452 C99orCXXorObjC? Sema::PCC_ForInit
1453 : Sema::PCC_Expression);
1458 ParsedAttributesWithRange attrs(AttrFactory);
1459 MaybeParseCXX11Attributes(attrs);
1461 // Parse the first part of the for specifier.
1462 if (Tok.is(tok::semi)) { // for (;
1463 ProhibitAttributes(attrs);
1464 // no first part, eat the ';'.
1466 } else if (isForInitDeclaration()) { // for (int X = 4;
1467 // Parse declaration, which eats the ';'.
1468 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode?
1469 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1471 // In C++0x, "for (T NS:a" might not be a typo for ::
1472 bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1473 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1475 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1477 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext,
1478 DeclEnd, attrs, false,
1479 MightBeForRangeStmt ?
1481 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1483 if (ForRangeInit.ParsedForRangeDecl()) {
1484 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ?
1485 diag::warn_cxx98_compat_for_range : diag::ext_for_range);
1488 } else if (Tok.is(tok::semi)) { // for (int x = 4;
1490 } else if ((ForEach = isTokIdentifier_in())) {
1491 Actions.ActOnForEachDeclStmt(DG);
1492 // ObjC: for (id x in expr)
1493 ConsumeToken(); // consume 'in'
1495 if (Tok.is(tok::code_completion)) {
1496 Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1500 Collection = ParseExpression();
1502 Diag(Tok, diag::err_expected_semi_for);
1505 ProhibitAttributes(attrs);
1506 Value = ParseExpression();
1508 ForEach = isTokIdentifier_in();
1510 // Turn the expression into a stmt.
1511 if (!Value.isInvalid()) {
1513 FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1515 FirstPart = Actions.ActOnExprStmt(Value);
1518 if (Tok.is(tok::semi)) {
1520 } else if (ForEach) {
1521 ConsumeToken(); // consume 'in'
1523 if (Tok.is(tok::code_completion)) {
1524 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy());
1528 Collection = ParseExpression();
1529 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
1530 // User tried to write the reasonable, but ill-formed, for-range-statement
1531 // for (expr : expr) { ... }
1532 Diag(Tok, diag::err_for_range_expected_decl)
1533 << FirstPart.get()->getSourceRange();
1534 SkipUntil(tok::r_paren, StopBeforeMatch);
1535 SecondPartIsInvalid = true;
1537 if (!Value.isInvalid()) {
1538 Diag(Tok, diag::err_expected_semi_for);
1540 // Skip until semicolon or rparen, don't consume it.
1541 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1542 if (Tok.is(tok::semi))
1547 if (!ForEach && !ForRange) {
1548 assert(!SecondPart.get() && "Shouldn't have a second expression yet.");
1549 // Parse the second part of the for specifier.
1550 if (Tok.is(tok::semi)) { // for (...;;
1552 } else if (Tok.is(tok::r_paren)) {
1553 // missing both semicolons.
1556 if (getLangOpts().CPlusPlus)
1557 ParseCXXCondition(Second, SecondVar, ForLoc, true);
1559 Second = ParseExpression();
1560 if (!Second.isInvalid())
1561 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc,
1564 SecondPartIsInvalid = Second.isInvalid();
1565 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc);
1568 if (Tok.isNot(tok::semi)) {
1569 if (!SecondPartIsInvalid || SecondVar)
1570 Diag(Tok, diag::err_expected_semi_for);
1572 // Skip until semicolon or rparen, don't consume it.
1573 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1576 if (Tok.is(tok::semi)) {
1580 // Parse the third part of the for specifier.
1581 if (Tok.isNot(tok::r_paren)) { // for (...;...;)
1582 ExprResult Third = ParseExpression();
1583 // FIXME: The C++11 standard doesn't actually say that this is a
1584 // discarded-value expression, but it clearly should be.
1585 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take());
1591 // We need to perform most of the semantic analysis for a C++0x for-range
1592 // statememt before parsing the body, in order to be able to deduce the type
1593 // of an auto-typed loop variable.
1594 StmtResult ForRangeStmt;
1595 StmtResult ForEachStmt;
1598 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(),
1599 ForRangeInit.ColonLoc,
1600 ForRangeInit.RangeExpr.get(),
1601 T.getCloseLocation(),
1605 // Similarly, we need to do the semantic analysis for a for-range
1606 // statement immediately in order to close over temporaries correctly.
1607 } else if (ForEach) {
1608 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
1611 T.getCloseLocation());
1614 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if
1615 // there is no compound stmt. C90 does not have this clause. We only do this
1616 // if the body isn't a compound statement to avoid push/pop in common cases.
1619 // The substatement in an iteration-statement implicitly defines a local scope
1620 // which is entered and exited each time through the loop.
1622 // See comments in ParseIfStatement for why we create a scope for
1623 // for-init-statement/condition and a new scope for substatement in C++.
1625 ParseScope InnerScope(this, Scope::DeclScope,
1626 C99orCXXorObjC && Tok.isNot(tok::l_brace));
1628 // Read the body statement.
1629 StmtResult Body(ParseStatement(TrailingElseLoc));
1631 // Pop the body scope if needed.
1634 // Leave the for-scope.
1637 if (Body.isInvalid())
1641 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(),
1645 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take());
1647 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(),
1648 SecondPart, SecondVar, ThirdPart,
1649 T.getCloseLocation(), Body.take());
1652 /// ParseGotoStatement
1654 /// 'goto' identifier ';'
1655 /// [GNU] 'goto' '*' expression ';'
1657 /// Note: this lets the caller parse the end ';'.
1659 StmtResult Parser::ParseGotoStatement() {
1660 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
1661 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
1664 if (Tok.is(tok::identifier)) {
1665 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1667 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
1669 } else if (Tok.is(tok::star)) {
1670 // GNU indirect goto extension.
1671 Diag(Tok, diag::ext_gnu_indirect_goto);
1672 SourceLocation StarLoc = ConsumeToken();
1673 ExprResult R(ParseExpression());
1674 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1675 SkipUntil(tok::semi, StopBeforeMatch);
1678 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take());
1680 Diag(Tok, diag::err_expected_ident);
1687 /// ParseContinueStatement
1691 /// Note: this lets the caller parse the end ';'.
1693 StmtResult Parser::ParseContinueStatement() {
1694 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
1695 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
1698 /// ParseBreakStatement
1702 /// Note: this lets the caller parse the end ';'.
1704 StmtResult Parser::ParseBreakStatement() {
1705 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
1706 return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
1709 /// ParseReturnStatement
1711 /// 'return' expression[opt] ';'
1712 StmtResult Parser::ParseReturnStatement() {
1713 assert(Tok.is(tok::kw_return) && "Not a return stmt!");
1714 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
1717 if (Tok.isNot(tok::semi)) {
1718 if (Tok.is(tok::code_completion)) {
1719 Actions.CodeCompleteReturn(getCurScope());
1724 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
1725 R = ParseInitializer();
1727 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ?
1728 diag::warn_cxx98_compat_generalized_initializer_lists :
1729 diag::ext_generalized_initializer_lists)
1730 << R.get()->getSourceRange();
1732 R = ParseExpression();
1733 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
1734 SkipUntil(tok::semi, StopBeforeMatch);
1738 return Actions.ActOnReturnStmt(ReturnLoc, R.take());
1742 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
1744 SourceLocation AsmLoc;
1745 StringRef AsmString;
1747 /// The tokens we streamed into AsmString and handed off to MC.
1748 ArrayRef<Token> AsmToks;
1750 /// The offset of each token in AsmToks within AsmString.
1751 ArrayRef<unsigned> AsmTokOffsets;
1754 ClangAsmParserCallback(Parser &P, SourceLocation Loc,
1755 StringRef AsmString,
1756 ArrayRef<Token> Toks,
1757 ArrayRef<unsigned> Offsets)
1758 : TheParser(P), AsmLoc(Loc), AsmString(AsmString),
1759 AsmToks(Toks), AsmTokOffsets(Offsets) {
1760 assert(AsmToks.size() == AsmTokOffsets.size());
1763 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
1764 InlineAsmIdentifierInfo &Info,
1765 bool IsUnevaluatedContext) {
1766 // Collect the desired tokens.
1767 SmallVector<Token, 16> LineToks;
1768 const Token *FirstOrigToken = 0;
1769 findTokensForString(LineBuf, LineToks, FirstOrigToken);
1771 unsigned NumConsumedToks;
1773 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info,
1774 IsUnevaluatedContext);
1776 // If we consumed the entire line, tell MC that.
1777 // Also do this if we consumed nothing as a way of reporting failure.
1778 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
1779 // By not modifying LineBuf, we're implicitly consuming it all.
1781 // Otherwise, consume up to the original tokens.
1783 assert(FirstOrigToken && "not using original tokens?");
1785 // Since we're using original tokens, apply that offset.
1786 assert(FirstOrigToken[NumConsumedToks].getLocation()
1787 == LineToks[NumConsumedToks].getLocation());
1788 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
1789 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
1791 // The total length we've consumed is the relative offset
1792 // of the last token we consumed plus its length.
1793 unsigned TotalOffset = (AsmTokOffsets[LastIndex]
1794 + AsmToks[LastIndex].getLength()
1795 - AsmTokOffsets[FirstIndex]);
1796 LineBuf = LineBuf.substr(0, TotalOffset);
1799 // Initialize the "decl" with the lookup result.
1800 Info.OpDecl = static_cast<void*>(Result.take());
1804 bool LookupInlineAsmField(StringRef Base, StringRef Member,
1806 return TheParser.getActions().LookupInlineAsmField(Base, Member,
1810 static void DiagHandlerCallback(const llvm::SMDiagnostic &D,
1812 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D);
1816 /// Collect the appropriate tokens for the given string.
1817 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
1818 const Token *&FirstOrigToken) const {
1819 // For now, assert that the string we're working with is a substring
1820 // of what we gave to MC. This lets us use the original tokens.
1821 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) &&
1822 !std::less<const char*>()(AsmString.end(), Str.end()));
1824 // Try to find a token whose offset matches the first token.
1825 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
1826 const unsigned *FirstTokOffset
1827 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
1830 // For now, assert that the start of the string exactly
1831 // corresponds to the start of a token.
1832 assert(*FirstTokOffset == FirstCharOffset);
1834 // Use all the original tokens for this line. (We assume the
1835 // end of the line corresponds cleanly to a token break.)
1836 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
1837 FirstOrigToken = &AsmToks[FirstTokIndex];
1838 unsigned LastCharOffset = Str.end() - AsmString.begin();
1839 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
1840 if (AsmTokOffsets[i] >= LastCharOffset) break;
1841 TempToks.push_back(AsmToks[i]);
1845 void handleDiagnostic(const llvm::SMDiagnostic &D) {
1846 // Compute an offset into the inline asm buffer.
1847 // FIXME: This isn't right if .macro is involved (but hopefully, no
1848 // real-world code does that).
1849 const llvm::SourceMgr &LSM = *D.getSourceMgr();
1850 const llvm::MemoryBuffer *LBuf =
1851 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
1852 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
1854 // Figure out which token that offset points into.
1855 const unsigned *TokOffsetPtr =
1856 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
1857 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
1858 unsigned TokOffset = *TokOffsetPtr;
1860 // If we come up with an answer which seems sane, use it; otherwise,
1861 // just point at the __asm keyword.
1862 // FIXME: Assert the answer is sane once we handle .macro correctly.
1863 SourceLocation Loc = AsmLoc;
1864 if (TokIndex < AsmToks.size()) {
1865 const Token &Tok = AsmToks[TokIndex];
1866 Loc = Tok.getLocation();
1867 Loc = Loc.getLocWithOffset(Offset - TokOffset);
1869 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing)
1875 /// Parse an identifier in an MS-style inline assembly block.
1877 /// \param CastInfo - a void* so that we don't have to teach Parser.h
1878 /// about the actual type.
1879 ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1880 unsigned &NumLineToksConsumed,
1882 bool IsUnevaluatedContext) {
1883 llvm::InlineAsmIdentifierInfo &Info =
1884 *(llvm::InlineAsmIdentifierInfo *) CastInfo;
1886 // Push a fake token on the end so that we don't overrun the token
1887 // stream. We use ';' because it expression-parsing should never
1889 const tok::TokenKind EndOfStream = tok::semi;
1890 Token EndOfStreamTok;
1891 EndOfStreamTok.startToken();
1892 EndOfStreamTok.setKind(EndOfStream);
1893 LineToks.push_back(EndOfStreamTok);
1895 // Also copy the current token over.
1896 LineToks.push_back(Tok);
1898 PP.EnterTokenStream(LineToks.begin(),
1900 /*disable macros*/ true,
1901 /*owns tokens*/ false);
1903 // Clear the current token and advance to the first token in LineToks.
1906 // Parse an optional scope-specifier if we're in C++.
1908 if (getLangOpts().CPlusPlus) {
1909 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
1912 // Require an identifier here.
1913 SourceLocation TemplateKWLoc;
1915 bool Invalid = ParseUnqualifiedId(SS,
1916 /*EnteringContext=*/false,
1917 /*AllowDestructorName=*/false,
1918 /*AllowConstructorName=*/false,
1919 /*ObjectType=*/ ParsedType(),
1923 // If we've run into the poison token we inserted before, or there
1924 // was a parsing error, then claim the entire line.
1925 if (Invalid || Tok.is(EndOfStream)) {
1926 NumLineToksConsumed = LineToks.size() - 2;
1928 // Otherwise, claim up to the start of the next token.
1930 // Figure out how many tokens we are into LineToks.
1931 unsigned LineIndex = 0;
1932 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
1934 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
1937 NumLineToksConsumed = LineIndex;
1940 // Finally, restore the old parsing state by consuming all the
1941 // tokens we staged before, implicitly killing off the
1942 // token-lexer we pushed.
1943 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) {
1946 ConsumeToken(EndOfStream);
1948 // Leave LineToks in its original state.
1949 LineToks.pop_back();
1950 LineToks.pop_back();
1952 // Perform the lookup.
1953 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
1954 IsUnevaluatedContext);
1957 /// Turn a sequence of our tokens back into a string that we can hand
1958 /// to the MC asm parser.
1959 static bool buildMSAsmString(Preprocessor &PP,
1960 SourceLocation AsmLoc,
1961 ArrayRef<Token> AsmToks,
1962 SmallVectorImpl<unsigned> &TokOffsets,
1963 SmallString<512> &Asm) {
1964 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
1966 // Is this the start of a new assembly statement?
1967 bool isNewStatement = true;
1969 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
1970 const Token &Tok = AsmToks[i];
1972 // Start each new statement with a newline and a tab.
1973 if (!isNewStatement &&
1974 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
1976 isNewStatement = true;
1979 // Preserve the existence of leading whitespace except at the
1980 // start of a statement.
1981 if (!isNewStatement && Tok.hasLeadingSpace())
1984 // Remember the offset of this token.
1985 TokOffsets.push_back(Asm.size());
1987 // Don't actually write '__asm' into the assembly stream.
1988 if (Tok.is(tok::kw_asm)) {
1989 // Complain about __asm at the end of the stream.
1991 PP.Diag(AsmLoc, diag::err_asm_empty);
1998 // Append the spelling of the token.
1999 SmallString<32> SpellingBuffer;
2000 bool SpellingInvalid = false;
2001 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
2002 assert(!SpellingInvalid && "spelling was invalid after correct parse?");
2004 // We are no longer at the start of a statement.
2005 isNewStatement = false;
2008 // Ensure that the buffer is null-terminated.
2009 Asm.push_back('\0');
2012 assert(TokOffsets.size() == AsmToks.size());
2016 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
2017 /// this routine is called to collect the tokens for an MS asm statement.
2019 /// [MS] ms-asm-statement:
2021 /// ms-asm-block ms-asm-statement
2023 /// [MS] ms-asm-block:
2024 /// '__asm' ms-asm-line '\n'
2025 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
2027 /// [MS] ms-asm-instruction-block
2029 /// ms-asm-line '\n' ms-asm-instruction-block
2031 StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
2032 SourceManager &SrcMgr = PP.getSourceManager();
2033 SourceLocation EndLoc = AsmLoc;
2034 SmallVector<Token, 4> AsmToks;
2036 bool InBraces = false;
2037 unsigned short savedBraceCount = 0;
2038 bool InAsmComment = false;
2040 unsigned LineNo = 0;
2041 unsigned NumTokensRead = 0;
2042 SourceLocation LBraceLoc;
2044 if (Tok.is(tok::l_brace)) {
2045 // Braced inline asm: consume the opening brace.
2047 savedBraceCount = BraceCount;
2048 EndLoc = LBraceLoc = ConsumeBrace();
2051 // Single-line inline asm; compute which line it is on.
2052 std::pair<FileID, unsigned> ExpAsmLoc =
2053 SrcMgr.getDecomposedExpansionLoc(EndLoc);
2054 FID = ExpAsmLoc.first;
2055 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
2058 SourceLocation TokLoc = Tok.getLocation();
2060 // If we hit EOF, we're done, period.
2061 if (Tok.is(tok::eof))
2064 if (!InAsmComment && Tok.is(tok::semi)) {
2065 // A semicolon in an asm is the start of a comment.
2066 InAsmComment = true;
2068 // Compute which line the comment is on.
2069 std::pair<FileID, unsigned> ExpSemiLoc =
2070 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2071 FID = ExpSemiLoc.first;
2072 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
2074 } else if (!InBraces || InAsmComment) {
2075 // If end-of-line is significant, check whether this token is on a
2077 std::pair<FileID, unsigned> ExpLoc =
2078 SrcMgr.getDecomposedExpansionLoc(TokLoc);
2079 if (ExpLoc.first != FID ||
2080 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
2081 // If this is a single-line __asm, we're done.
2084 // We're no longer in a comment.
2085 InAsmComment = false;
2086 } else if (!InAsmComment && Tok.is(tok::r_brace)) {
2087 // Single-line asm always ends when a closing brace is seen.
2088 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what
2089 // does MSVC do here?
2093 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) &&
2094 BraceCount == (savedBraceCount + 1)) {
2095 // Consume the closing brace, and finish
2096 EndLoc = ConsumeBrace();
2100 // Consume the next token; make sure we don't modify the brace count etc.
2101 // if we are in a comment.
2106 AsmToks.push_back(Tok);
2109 TokLoc = Tok.getLocation();
2113 if (InBraces && BraceCount != savedBraceCount) {
2114 // __asm without closing brace (this can happen at EOF).
2115 Diag(Tok, diag::err_expected_rbrace);
2116 Diag(LBraceLoc, diag::note_matching) << "{";
2118 } else if (NumTokensRead == 0) {
2120 Diag(Tok, diag::err_expected_lbrace);
2124 // Okay, prepare to use MC to parse the assembly.
2125 SmallVector<StringRef, 4> ConstraintRefs;
2126 SmallVector<Expr*, 4> Exprs;
2127 SmallVector<StringRef, 4> ClobberRefs;
2129 // We need an actual supported target.
2130 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple();
2131 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
2132 const std::string &TT = TheTriple.getTriple();
2133 const llvm::Target *TheTarget = 0;
2134 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 &&
2135 ArchTy != llvm::Triple::x86_64);
2136 if (UnsupportedArch) {
2137 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
2140 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
2142 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
2145 // If we don't support assembly, or the assembly is empty, we don't
2146 // need to instantiate the AsmParser, etc.
2147 if (!TheTarget || AsmToks.empty()) {
2148 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(),
2149 /*NumOutputs*/ 0, /*NumInputs*/ 0,
2150 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2153 // Expand the tokens into a string buffer.
2154 SmallString<512> AsmString;
2155 SmallVector<unsigned, 8> TokOffsets;
2156 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
2159 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2160 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
2161 // Get the instruction descriptor.
2162 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
2163 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2164 OwningPtr<llvm::MCSubtargetInfo>
2165 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2167 llvm::SourceMgr TempSrcMgr;
2168 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
2169 llvm::MemoryBuffer *Buffer =
2170 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
2172 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2173 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2175 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
2176 OwningPtr<llvm::MCAsmParser>
2177 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
2178 OwningPtr<llvm::MCTargetAsmParser>
2179 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser, *MII));
2181 llvm::MCInstPrinter *IP =
2182 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
2184 // Change to the Intel dialect.
2185 Parser->setAssemblerDialect(1);
2186 Parser->setTargetParser(*TargetParser.get());
2187 Parser->setParsingInlineAsm(true);
2188 TargetParser->setParsingInlineAsm(true);
2190 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString,
2191 AsmToks, TokOffsets);
2192 TargetParser->setSemaCallback(&Callback);
2193 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
2196 unsigned NumOutputs;
2198 std::string AsmStringIR;
2199 SmallVector<std::pair<void *, bool>, 4> OpExprs;
2200 SmallVector<std::string, 4> Constraints;
2201 SmallVector<std::string, 4> Clobbers;
2202 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR,
2203 NumOutputs, NumInputs, OpExprs, Constraints,
2204 Clobbers, MII, IP, Callback))
2207 // Build the vector of clobber StringRefs.
2208 unsigned NumClobbers = Clobbers.size();
2209 ClobberRefs.resize(NumClobbers);
2210 for (unsigned i = 0; i != NumClobbers; ++i)
2211 ClobberRefs[i] = StringRef(Clobbers[i]);
2213 // Recast the void pointers and build the vector of constraint StringRefs.
2214 unsigned NumExprs = NumOutputs + NumInputs;
2215 ConstraintRefs.resize(NumExprs);
2216 Exprs.resize(NumExprs);
2217 for (unsigned i = 0, e = NumExprs; i != e; ++i) {
2218 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
2222 // Need address of variable.
2223 if (OpExprs[i].second)
2224 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr)
2227 ConstraintRefs[i] = StringRef(Constraints[i]);
2231 // FIXME: We should be passing source locations for better diagnostics.
2232 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR,
2233 NumOutputs, NumInputs,
2234 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
2237 /// ParseAsmStatement - Parse a GNU extended asm statement.
2239 /// gnu-asm-statement
2240 /// ms-asm-statement
2242 /// [GNU] gnu-asm-statement:
2243 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
2245 /// [GNU] asm-argument:
2246 /// asm-string-literal
2247 /// asm-string-literal ':' asm-operands[opt]
2248 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2249 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
2250 /// ':' asm-clobbers
2252 /// [GNU] asm-clobbers:
2253 /// asm-string-literal
2254 /// asm-clobbers ',' asm-string-literal
2256 StmtResult Parser::ParseAsmStatement(bool &msAsm) {
2257 assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
2258 SourceLocation AsmLoc = ConsumeToken();
2260 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
2261 !isTypeQualifier()) {
2263 return ParseMicrosoftAsmStatement(AsmLoc);
2265 DeclSpec DS(AttrFactory);
2266 SourceLocation Loc = Tok.getLocation();
2267 ParseTypeQualifierListOpt(DS, true, false);
2269 // GNU asms accept, but warn, about type-qualifiers other than volatile.
2270 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2271 Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
2272 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2273 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
2274 // FIXME: Once GCC supports _Atomic, check whether it permits it here.
2275 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
2276 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
2278 // Remember if this was a volatile asm.
2279 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
2280 if (Tok.isNot(tok::l_paren)) {
2281 Diag(Tok, diag::err_expected_lparen_after) << "asm";
2282 SkipUntil(tok::r_paren, StopAtSemi);
2285 BalancedDelimiterTracker T(*this, tok::l_paren);
2288 ExprResult AsmString(ParseAsmStringLiteral());
2289 if (AsmString.isInvalid()) {
2290 // Consume up to and including the closing paren.
2295 SmallVector<IdentifierInfo *, 4> Names;
2296 ExprVector Constraints;
2298 ExprVector Clobbers;
2300 if (Tok.is(tok::r_paren)) {
2301 // We have a simple asm expression like 'asm("foo")'.
2303 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
2304 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0,
2305 Constraints, Exprs, AsmString.take(),
2306 Clobbers, T.getCloseLocation());
2309 // Parse Outputs, if present.
2310 bool AteExtraColon = false;
2311 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2312 // In C++ mode, parse "::" like ": :".
2313 AteExtraColon = Tok.is(tok::coloncolon);
2316 if (!AteExtraColon &&
2317 ParseAsmOperandsOpt(Names, Constraints, Exprs))
2321 unsigned NumOutputs = Names.size();
2323 // Parse Inputs, if present.
2324 if (AteExtraColon ||
2325 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
2326 // In C++ mode, parse "::" like ": :".
2328 AteExtraColon = false;
2330 AteExtraColon = Tok.is(tok::coloncolon);
2334 if (!AteExtraColon &&
2335 ParseAsmOperandsOpt(Names, Constraints, Exprs))
2339 assert(Names.size() == Constraints.size() &&
2340 Constraints.size() == Exprs.size() &&
2341 "Input operand size mismatch!");
2343 unsigned NumInputs = Names.size() - NumOutputs;
2345 // Parse the clobbers, if present.
2346 if (AteExtraColon || Tok.is(tok::colon)) {
2350 // Parse the asm-string list for clobbers if present.
2351 if (Tok.isNot(tok::r_paren)) {
2353 ExprResult Clobber(ParseAsmStringLiteral());
2355 if (Clobber.isInvalid())
2358 Clobbers.push_back(Clobber.release());
2360 if (Tok.isNot(tok::comma)) break;
2367 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs,
2368 NumInputs, Names.data(), Constraints, Exprs,
2369 AsmString.take(), Clobbers,
2370 T.getCloseLocation());
2373 /// ParseAsmOperands - Parse the asm-operands production as used by
2374 /// asm-statement, assuming the leading ':' token was eaten.
2376 /// [GNU] asm-operands:
2378 /// asm-operands ',' asm-operand
2380 /// [GNU] asm-operand:
2381 /// asm-string-literal '(' expression ')'
2382 /// '[' identifier ']' asm-string-literal '(' expression ')'
2385 // FIXME: Avoid unnecessary std::string trashing.
2386 bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2387 SmallVectorImpl<Expr *> &Constraints,
2388 SmallVectorImpl<Expr *> &Exprs) {
2389 // 'asm-operands' isn't present?
2390 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
2394 // Read the [id] if present.
2395 if (Tok.is(tok::l_square)) {
2396 BalancedDelimiterTracker T(*this, tok::l_square);
2399 if (Tok.isNot(tok::identifier)) {
2400 Diag(Tok, diag::err_expected_ident);
2401 SkipUntil(tok::r_paren, StopAtSemi);
2405 IdentifierInfo *II = Tok.getIdentifierInfo();
2408 Names.push_back(II);
2413 ExprResult Constraint(ParseAsmStringLiteral());
2414 if (Constraint.isInvalid()) {
2415 SkipUntil(tok::r_paren, StopAtSemi);
2418 Constraints.push_back(Constraint.release());
2420 if (Tok.isNot(tok::l_paren)) {
2421 Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
2422 SkipUntil(tok::r_paren, StopAtSemi);
2426 // Read the parenthesized expression.
2427 BalancedDelimiterTracker T(*this, tok::l_paren);
2429 ExprResult Res(ParseExpression());
2431 if (Res.isInvalid()) {
2432 SkipUntil(tok::r_paren, StopAtSemi);
2435 Exprs.push_back(Res.release());
2436 // Eat the comma and continue parsing if it exists.
2437 if (Tok.isNot(tok::comma)) return false;
2442 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2443 assert(Tok.is(tok::l_brace));
2444 SourceLocation LBraceLoc = Tok.getLocation();
2446 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) &&
2447 trySkippingFunctionBody()) {
2449 return Actions.ActOnSkippedFunctionBody(Decl);
2452 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
2453 "parsing function body");
2455 // Do not enter a scope for the brace, as the arguments are in the same scope
2456 // (the function body) as the body itself. Instead, just read the statement
2457 // list and put it into a CompoundStmt for safe keeping.
2458 StmtResult FnBody(ParseCompoundStatementBody());
2460 // If the function body could not be parsed, make a bogus compoundstmt.
2461 if (FnBody.isInvalid()) {
2462 Sema::CompoundScopeRAII CompoundScope(Actions);
2463 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2467 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
2470 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
2472 /// function-try-block:
2473 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2475 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2476 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2477 SourceLocation TryLoc = ConsumeToken();
2479 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc,
2480 "parsing function try block");
2482 // Constructor initializer list?
2483 if (Tok.is(tok::colon))
2484 ParseConstructorInitializer(Decl);
2486 Actions.ActOnDefaultCtorInitializers(Decl);
2488 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) &&
2489 trySkippingFunctionBody()) {
2491 return Actions.ActOnSkippedFunctionBody(Decl);
2494 SourceLocation LBraceLoc = Tok.getLocation();
2495 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2496 // If we failed to parse the try-catch, we just give the function an empty
2497 // compound statement as the body.
2498 if (FnBody.isInvalid()) {
2499 Sema::CompoundScopeRAII CompoundScope(Actions);
2500 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2504 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
2507 bool Parser::trySkippingFunctionBody() {
2508 assert(Tok.is(tok::l_brace));
2509 assert(SkipFunctionBodies &&
2510 "Should only be called when SkipFunctionBodies is enabled");
2512 if (!PP.isCodeCompletionEnabled()) {
2514 SkipUntil(tok::r_brace);
2518 // We're in code-completion mode. Skip parsing for all function bodies unless
2519 // the body contains the code-completion point.
2520 TentativeParsingAction PA(*this);
2522 if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2531 /// ParseCXXTryBlock - Parse a C++ try-block.
2534 /// 'try' compound-statement handler-seq
2536 StmtResult Parser::ParseCXXTryBlock() {
2537 assert(Tok.is(tok::kw_try) && "Expected 'try'");
2539 SourceLocation TryLoc = ConsumeToken();
2540 return ParseCXXTryBlockCommon(TryLoc);
2543 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
2544 /// function-try-block.
2547 /// 'try' compound-statement handler-seq
2549 /// function-try-block:
2550 /// 'try' ctor-initializer[opt] compound-statement handler-seq
2553 /// handler handler-seq[opt]
2555 /// [Borland] try-block:
2556 /// 'try' compound-statement seh-except-block
2557 /// 'try' compound-statment seh-finally-block
2559 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2560 if (Tok.isNot(tok::l_brace))
2561 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2562 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2564 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
2565 Scope::DeclScope | Scope::TryScope |
2566 (FnTry ? Scope::FnTryCatchScope : 0)));
2567 if (TryBlock.isInvalid())
2570 // Borland allows SEH-handlers with 'try'
2572 if ((Tok.is(tok::identifier) &&
2573 Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2574 Tok.is(tok::kw___finally)) {
2575 // TODO: Factor into common return ParseSEHHandlerCommon(...)
2577 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2578 SourceLocation Loc = ConsumeToken();
2579 Handler = ParseSEHExceptBlock(Loc);
2582 SourceLocation Loc = ConsumeToken();
2583 Handler = ParseSEHFinallyBlock(Loc);
2585 if(Handler.isInvalid())
2588 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2594 StmtVector Handlers;
2596 // C++11 attributes can't appear here, despite this context seeming
2598 DiagnoseAndSkipCXX11Attributes();
2600 if (Tok.isNot(tok::kw_catch))
2601 return StmtError(Diag(Tok, diag::err_expected_catch));
2602 while (Tok.is(tok::kw_catch)) {
2603 StmtResult Handler(ParseCXXCatchBlock(FnTry));
2604 if (!Handler.isInvalid())
2605 Handlers.push_back(Handler.release());
2607 // Don't bother creating the full statement if we don't have any usable
2609 if (Handlers.empty())
2612 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(), Handlers);
2616 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2619 /// 'catch' '(' exception-declaration ')' compound-statement
2621 /// exception-declaration:
2622 /// attribute-specifier-seq[opt] type-specifier-seq declarator
2623 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2626 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2627 assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2629 SourceLocation CatchLoc = ConsumeToken();
2631 BalancedDelimiterTracker T(*this, tok::l_paren);
2632 if (T.expectAndConsume(diag::err_expected_lparen))
2636 // The name in a catch exception-declaration is local to the handler and
2637 // shall not be redeclared in the outermost block of the handler.
2638 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2639 (FnCatch ? Scope::FnTryCatchScope : 0));
2641 // exception-declaration is equivalent to '...' or a parameter-declaration
2642 // without default arguments.
2643 Decl *ExceptionDecl = 0;
2644 if (Tok.isNot(tok::ellipsis)) {
2645 ParsedAttributesWithRange Attributes(AttrFactory);
2646 MaybeParseCXX11Attributes(Attributes);
2648 DeclSpec DS(AttrFactory);
2649 DS.takeAttributesFrom(Attributes);
2651 if (ParseCXXTypeSpecifierSeq(DS))
2654 Declarator ExDecl(DS, Declarator::CXXCatchContext);
2655 ParseDeclarator(ExDecl);
2656 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2661 if (T.getCloseLocation().isInvalid())
2664 if (Tok.isNot(tok::l_brace))
2665 return StmtError(Diag(Tok, diag::err_expected_lbrace));
2667 // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2668 StmtResult Block(ParseCompoundStatement());
2669 if (Block.isInvalid())
2672 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take());
2675 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2676 IfExistsCondition Result;
2677 if (ParseMicrosoftIfExistsCondition(Result))
2680 // Handle dependent statements by parsing the braces as a compound statement.
2681 // This is not the same behavior as Visual C++, which don't treat this as a
2682 // compound statement, but for Clang's type checking we can't have anything
2683 // inside these braces escaping to the surrounding code.
2684 if (Result.Behavior == IEB_Dependent) {
2685 if (!Tok.is(tok::l_brace)) {
2686 Diag(Tok, diag::err_expected_lbrace);
2690 StmtResult Compound = ParseCompoundStatement();
2691 if (Compound.isInvalid())
2694 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2699 if (DepResult.isUsable())
2700 Stmts.push_back(DepResult.get());
2704 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2705 if (Braces.consumeOpen()) {
2706 Diag(Tok, diag::err_expected_lbrace);
2710 switch (Result.Behavior) {
2712 // Parse the statements below.
2716 llvm_unreachable("Dependent case handled above");
2723 // Condition is true, parse the statements.
2724 while (Tok.isNot(tok::r_brace)) {
2725 StmtResult R = ParseStatementOrDeclaration(Stmts, false);
2727 Stmts.push_back(R.release());
2729 Braces.consumeClose();