1 //===--- Parser.cpp - C Language Family 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 Parser interfaces. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Parse/Parser.h" 15 #include "RAIIObjectsForParser.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/Parse/ParseDiagnostic.h" 20 #include "clang/Sema/DeclSpec.h" 21 #include "clang/Sema/ParsedTemplate.h" 22 #include "clang/Sema/Scope.h" 23 #include "llvm/Support/raw_ostream.h" 24 using namespace clang; 25 26 27 namespace { 28 /// \brief A comment handler that passes comments found by the preprocessor 29 /// to the parser action. 30 class ActionCommentHandler : public CommentHandler { 31 Sema &S; 32 33 public: 34 explicit ActionCommentHandler(Sema &S) : S(S) { } 35 36 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) { 37 S.ActOnComment(Comment); 38 return false; 39 } 40 }; 41 } // end anonymous namespace 42 43 IdentifierInfo *Parser::getSEHExceptKeyword() { 44 // __except is accepted as a (contextual) keyword 45 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland)) 46 Ident__except = PP.getIdentifierInfo("__except"); 47 48 return Ident__except; 49 } 50 51 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies) 52 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()), 53 GreaterThanIsOperator(true), ColonIsSacred(false), 54 InMessageExpression(false), TemplateParameterDepth(0), 55 ParsingInObjCContainer(false) { 56 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies; 57 Tok.startToken(); 58 Tok.setKind(tok::eof); 59 Actions.CurScope = 0; 60 NumCachedScopes = 0; 61 ParenCount = BracketCount = BraceCount = 0; 62 CurParsedObjCImpl = 0; 63 64 // Add #pragma handlers. These are removed and destroyed in the 65 // destructor. 66 initializePragmaHandlers(); 67 68 CommentSemaHandler.reset(new ActionCommentHandler(actions)); 69 PP.addCommentHandler(CommentSemaHandler.get()); 70 71 PP.setCodeCompletionHandler(*this); 72 } 73 74 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) { 75 return Diags.Report(Loc, DiagID); 76 } 77 78 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) { 79 return Diag(Tok.getLocation(), DiagID); 80 } 81 82 /// \brief Emits a diagnostic suggesting parentheses surrounding a 83 /// given range. 84 /// 85 /// \param Loc The location where we'll emit the diagnostic. 86 /// \param DK The kind of diagnostic to emit. 87 /// \param ParenRange Source range enclosing code that should be parenthesized. 88 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK, 89 SourceRange ParenRange) { 90 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd()); 91 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 92 // We can't display the parentheses, so just dig the 93 // warning/error and return. 94 Diag(Loc, DK); 95 return; 96 } 97 98 Diag(Loc, DK) 99 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 100 << FixItHint::CreateInsertion(EndLoc, ")"); 101 } 102 103 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) { 104 switch (ExpectedTok) { 105 case tok::semi: 106 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ; 107 default: return false; 108 } 109 } 110 111 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID, 112 const char *Msg) { 113 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) { 114 ConsumeAnyToken(); 115 return false; 116 } 117 118 // Detect common single-character typos and resume. 119 if (IsCommonTypo(ExpectedTok, Tok)) { 120 SourceLocation Loc = Tok.getLocation(); 121 { 122 DiagnosticBuilder DB = Diag(Loc, DiagID); 123 DB << FixItHint::CreateReplacement( 124 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok)); 125 if (DiagID == diag::err_expected) 126 DB << ExpectedTok; 127 else if (DiagID == diag::err_expected_after) 128 DB << Msg << ExpectedTok; 129 else 130 DB << Msg; 131 } 132 133 // Pretend there wasn't a problem. 134 ConsumeAnyToken(); 135 return false; 136 } 137 138 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); 139 const char *Spelling = 0; 140 if (EndLoc.isValid()) 141 Spelling = tok::getPunctuatorSpelling(ExpectedTok); 142 143 DiagnosticBuilder DB = 144 Spelling 145 ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling) 146 : Diag(Tok, DiagID); 147 if (DiagID == diag::err_expected) 148 DB << ExpectedTok; 149 else if (DiagID == diag::err_expected_after) 150 DB << Msg << ExpectedTok; 151 else 152 DB << Msg; 153 154 return true; 155 } 156 157 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { 158 if (TryConsumeToken(tok::semi)) 159 return false; 160 161 if (Tok.is(tok::code_completion)) { 162 handleUnexpectedCodeCompletionToken(); 163 return false; 164 } 165 166 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && 167 NextToken().is(tok::semi)) { 168 Diag(Tok, diag::err_extraneous_token_before_semi) 169 << PP.getSpelling(Tok) 170 << FixItHint::CreateRemoval(Tok.getLocation()); 171 ConsumeAnyToken(); // The ')' or ']'. 172 ConsumeToken(); // The ';'. 173 return false; 174 } 175 176 return ExpectAndConsume(tok::semi, DiagID); 177 } 178 179 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) { 180 if (!Tok.is(tok::semi)) return; 181 182 bool HadMultipleSemis = false; 183 SourceLocation StartLoc = Tok.getLocation(); 184 SourceLocation EndLoc = Tok.getLocation(); 185 ConsumeToken(); 186 187 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) { 188 HadMultipleSemis = true; 189 EndLoc = Tok.getLocation(); 190 ConsumeToken(); 191 } 192 193 // C++11 allows extra semicolons at namespace scope, but not in any of the 194 // other contexts. 195 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) { 196 if (getLangOpts().CPlusPlus11) 197 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi) 198 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 199 else 200 Diag(StartLoc, diag::ext_extra_semi_cxx11) 201 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 202 return; 203 } 204 205 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis) 206 Diag(StartLoc, diag::ext_extra_semi) 207 << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST, 208 Actions.getASTContext().getPrintingPolicy()) 209 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 210 else 211 // A single semicolon is valid after a member function definition. 212 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def) 213 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 214 } 215 216 //===----------------------------------------------------------------------===// 217 // Error recovery. 218 //===----------------------------------------------------------------------===// 219 220 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) { 221 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0; 222 } 223 224 /// SkipUntil - Read tokens until we get to the specified token, then consume 225 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the 226 /// token will ever occur, this skips to the next token, or to some likely 227 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';' 228 /// character. 229 /// 230 /// If SkipUntil finds the specified token, it returns true, otherwise it 231 /// returns false. 232 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) { 233 // We always want this function to skip at least one token if the first token 234 // isn't T and if not at EOF. 235 bool isFirstTokenSkipped = true; 236 while (1) { 237 // If we found one of the tokens, stop and return true. 238 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) { 239 if (Tok.is(Toks[i])) { 240 if (HasFlagsSet(Flags, StopBeforeMatch)) { 241 // Noop, don't consume the token. 242 } else { 243 ConsumeAnyToken(); 244 } 245 return true; 246 } 247 } 248 249 // Important special case: The caller has given up and just wants us to 250 // skip the rest of the file. Do this without recursing, since we can 251 // get here precisely because the caller detected too much recursion. 252 if (Toks.size() == 1 && Toks[0] == tok::eof && 253 !HasFlagsSet(Flags, StopAtSemi) && 254 !HasFlagsSet(Flags, StopAtCodeCompletion)) { 255 while (Tok.isNot(tok::eof)) 256 ConsumeAnyToken(); 257 return true; 258 } 259 260 switch (Tok.getKind()) { 261 case tok::eof: 262 // Ran out of tokens. 263 return false; 264 265 case tok::annot_pragma_openmp_end: 266 // Stop before an OpenMP pragma boundary. 267 case tok::annot_module_begin: 268 case tok::annot_module_end: 269 case tok::annot_module_include: 270 // Stop before we change submodules. They generally indicate a "good" 271 // place to pick up parsing again (except in the special case where 272 // we're trying to skip to EOF). 273 return false; 274 275 case tok::code_completion: 276 if (!HasFlagsSet(Flags, StopAtCodeCompletion)) 277 handleUnexpectedCodeCompletionToken(); 278 return false; 279 280 case tok::l_paren: 281 // Recursively skip properly-nested parens. 282 ConsumeParen(); 283 if (HasFlagsSet(Flags, StopAtCodeCompletion)) 284 SkipUntil(tok::r_paren, StopAtCodeCompletion); 285 else 286 SkipUntil(tok::r_paren); 287 break; 288 case tok::l_square: 289 // Recursively skip properly-nested square brackets. 290 ConsumeBracket(); 291 if (HasFlagsSet(Flags, StopAtCodeCompletion)) 292 SkipUntil(tok::r_square, StopAtCodeCompletion); 293 else 294 SkipUntil(tok::r_square); 295 break; 296 case tok::l_brace: 297 // Recursively skip properly-nested braces. 298 ConsumeBrace(); 299 if (HasFlagsSet(Flags, StopAtCodeCompletion)) 300 SkipUntil(tok::r_brace, StopAtCodeCompletion); 301 else 302 SkipUntil(tok::r_brace); 303 break; 304 305 // Okay, we found a ']' or '}' or ')', which we think should be balanced. 306 // Since the user wasn't looking for this token (if they were, it would 307 // already be handled), this isn't balanced. If there is a LHS token at a 308 // higher level, we will assume that this matches the unbalanced token 309 // and return it. Otherwise, this is a spurious RHS token, which we skip. 310 case tok::r_paren: 311 if (ParenCount && !isFirstTokenSkipped) 312 return false; // Matches something. 313 ConsumeParen(); 314 break; 315 case tok::r_square: 316 if (BracketCount && !isFirstTokenSkipped) 317 return false; // Matches something. 318 ConsumeBracket(); 319 break; 320 case tok::r_brace: 321 if (BraceCount && !isFirstTokenSkipped) 322 return false; // Matches something. 323 ConsumeBrace(); 324 break; 325 326 case tok::string_literal: 327 case tok::wide_string_literal: 328 case tok::utf8_string_literal: 329 case tok::utf16_string_literal: 330 case tok::utf32_string_literal: 331 ConsumeStringToken(); 332 break; 333 334 case tok::semi: 335 if (HasFlagsSet(Flags, StopAtSemi)) 336 return false; 337 // FALL THROUGH. 338 default: 339 // Skip this token. 340 ConsumeToken(); 341 break; 342 } 343 isFirstTokenSkipped = false; 344 } 345 } 346 347 //===----------------------------------------------------------------------===// 348 // Scope manipulation 349 //===----------------------------------------------------------------------===// 350 351 /// EnterScope - Start a new scope. 352 void Parser::EnterScope(unsigned ScopeFlags) { 353 if (NumCachedScopes) { 354 Scope *N = ScopeCache[--NumCachedScopes]; 355 N->Init(getCurScope(), ScopeFlags); 356 Actions.CurScope = N; 357 } else { 358 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags); 359 } 360 } 361 362 /// ExitScope - Pop a scope off the scope stack. 363 void Parser::ExitScope() { 364 assert(getCurScope() && "Scope imbalance!"); 365 366 // Inform the actions module that this scope is going away if there are any 367 // decls in it. 368 if (!getCurScope()->decl_empty()) 369 Actions.ActOnPopScope(Tok.getLocation(), getCurScope()); 370 371 Scope *OldScope = getCurScope(); 372 Actions.CurScope = OldScope->getParent(); 373 374 if (NumCachedScopes == ScopeCacheSize) 375 delete OldScope; 376 else 377 ScopeCache[NumCachedScopes++] = OldScope; 378 } 379 380 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false, 381 /// this object does nothing. 382 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags, 383 bool ManageFlags) 384 : CurScope(ManageFlags ? Self->getCurScope() : 0) { 385 if (CurScope) { 386 OldFlags = CurScope->getFlags(); 387 CurScope->setFlags(ScopeFlags); 388 } 389 } 390 391 /// Restore the flags for the current scope to what they were before this 392 /// object overrode them. 393 Parser::ParseScopeFlags::~ParseScopeFlags() { 394 if (CurScope) 395 CurScope->setFlags(OldFlags); 396 } 397 398 399 //===----------------------------------------------------------------------===// 400 // C99 6.9: External Definitions. 401 //===----------------------------------------------------------------------===// 402 403 Parser::~Parser() { 404 // If we still have scopes active, delete the scope tree. 405 delete getCurScope(); 406 Actions.CurScope = 0; 407 408 // Free the scope cache. 409 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i) 410 delete ScopeCache[i]; 411 412 resetPragmaHandlers(); 413 414 PP.removeCommentHandler(CommentSemaHandler.get()); 415 416 PP.clearCodeCompletionHandler(); 417 418 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?"); 419 } 420 421 /// Initialize - Warm up the parser. 422 /// 423 void Parser::Initialize() { 424 // Create the translation unit scope. Install it as the current scope. 425 assert(getCurScope() == 0 && "A scope is already active?"); 426 EnterScope(Scope::DeclScope); 427 Actions.ActOnTranslationUnitScope(getCurScope()); 428 429 // Initialization for Objective-C context sensitive keywords recognition. 430 // Referenced in Parser::ParseObjCTypeQualifierList. 431 if (getLangOpts().ObjC1) { 432 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in"); 433 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out"); 434 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout"); 435 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway"); 436 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy"); 437 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref"); 438 } 439 440 Ident_instancetype = 0; 441 Ident_final = 0; 442 Ident_sealed = 0; 443 Ident_override = 0; 444 445 Ident_super = &PP.getIdentifierTable().get("super"); 446 447 if (getLangOpts().AltiVec) { 448 Ident_vector = &PP.getIdentifierTable().get("vector"); 449 Ident_pixel = &PP.getIdentifierTable().get("pixel"); 450 Ident_bool = &PP.getIdentifierTable().get("bool"); 451 } 452 453 Ident_introduced = 0; 454 Ident_deprecated = 0; 455 Ident_obsoleted = 0; 456 Ident_unavailable = 0; 457 458 Ident__except = 0; 459 460 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0; 461 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0; 462 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0; 463 464 if(getLangOpts().Borland) { 465 Ident__exception_info = PP.getIdentifierInfo("_exception_info"); 466 Ident___exception_info = PP.getIdentifierInfo("__exception_info"); 467 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation"); 468 Ident__exception_code = PP.getIdentifierInfo("_exception_code"); 469 Ident___exception_code = PP.getIdentifierInfo("__exception_code"); 470 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode"); 471 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination"); 472 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination"); 473 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination"); 474 475 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block); 476 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block); 477 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block); 478 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter); 479 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter); 480 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter); 481 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block); 482 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block); 483 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block); 484 } 485 486 Actions.Initialize(); 487 488 // Prime the lexer look-ahead. 489 ConsumeToken(); 490 } 491 492 namespace { 493 /// \brief RAIIObject to destroy the contents of a SmallVector of 494 /// TemplateIdAnnotation pointers and clear the vector. 495 class DestroyTemplateIdAnnotationsRAIIObj { 496 SmallVectorImpl<TemplateIdAnnotation *> &Container; 497 public: 498 DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *> 499 &Container) 500 : Container(Container) {} 501 502 ~DestroyTemplateIdAnnotationsRAIIObj() { 503 for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I = 504 Container.begin(), E = Container.end(); 505 I != E; ++I) 506 (*I)->Destroy(); 507 Container.clear(); 508 } 509 }; 510 } 511 512 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the 513 /// action tells us to. This returns true if the EOF was encountered. 514 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) { 515 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds); 516 517 // Skip over the EOF token, flagging end of previous input for incremental 518 // processing 519 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof)) 520 ConsumeToken(); 521 522 Result = DeclGroupPtrTy(); 523 switch (Tok.getKind()) { 524 case tok::annot_pragma_unused: 525 HandlePragmaUnused(); 526 return false; 527 528 case tok::annot_module_include: 529 Actions.ActOnModuleInclude(Tok.getLocation(), 530 reinterpret_cast<Module *>( 531 Tok.getAnnotationValue())); 532 ConsumeToken(); 533 return false; 534 535 case tok::annot_module_begin: 536 case tok::annot_module_end: 537 // FIXME: Update visibility based on the submodule we're in. 538 ConsumeToken(); 539 return false; 540 541 case tok::eof: 542 // Late template parsing can begin. 543 if (getLangOpts().DelayedTemplateParsing) 544 Actions.SetLateTemplateParser(LateTemplateParserCallback, this); 545 if (!PP.isIncrementalProcessingEnabled()) 546 Actions.ActOnEndOfTranslationUnit(); 547 //else don't tell Sema that we ended parsing: more input might come. 548 return true; 549 550 default: 551 break; 552 } 553 554 ParsedAttributesWithRange attrs(AttrFactory); 555 MaybeParseCXX11Attributes(attrs); 556 MaybeParseMicrosoftAttributes(attrs); 557 558 Result = ParseExternalDeclaration(attrs); 559 return false; 560 } 561 562 /// ParseExternalDeclaration: 563 /// 564 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl] 565 /// function-definition 566 /// declaration 567 /// [GNU] asm-definition 568 /// [GNU] __extension__ external-declaration 569 /// [OBJC] objc-class-definition 570 /// [OBJC] objc-class-declaration 571 /// [OBJC] objc-alias-declaration 572 /// [OBJC] objc-protocol-definition 573 /// [OBJC] objc-method-definition 574 /// [OBJC] @end 575 /// [C++] linkage-specification 576 /// [GNU] asm-definition: 577 /// simple-asm-expr ';' 578 /// [C++11] empty-declaration 579 /// [C++11] attribute-declaration 580 /// 581 /// [C++11] empty-declaration: 582 /// ';' 583 /// 584 /// [C++0x/GNU] 'extern' 'template' declaration 585 Parser::DeclGroupPtrTy 586 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs, 587 ParsingDeclSpec *DS) { 588 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds); 589 ParenBraceBracketBalancer BalancerRAIIObj(*this); 590 591 if (PP.isCodeCompletionReached()) { 592 cutOffParsing(); 593 return DeclGroupPtrTy(); 594 } 595 596 Decl *SingleDecl = 0; 597 switch (Tok.getKind()) { 598 case tok::annot_pragma_vis: 599 HandlePragmaVisibility(); 600 return DeclGroupPtrTy(); 601 case tok::annot_pragma_pack: 602 HandlePragmaPack(); 603 return DeclGroupPtrTy(); 604 case tok::annot_pragma_msstruct: 605 HandlePragmaMSStruct(); 606 return DeclGroupPtrTy(); 607 case tok::annot_pragma_align: 608 HandlePragmaAlign(); 609 return DeclGroupPtrTy(); 610 case tok::annot_pragma_weak: 611 HandlePragmaWeak(); 612 return DeclGroupPtrTy(); 613 case tok::annot_pragma_weakalias: 614 HandlePragmaWeakAlias(); 615 return DeclGroupPtrTy(); 616 case tok::annot_pragma_redefine_extname: 617 HandlePragmaRedefineExtname(); 618 return DeclGroupPtrTy(); 619 case tok::annot_pragma_fp_contract: 620 HandlePragmaFPContract(); 621 return DeclGroupPtrTy(); 622 case tok::annot_pragma_opencl_extension: 623 HandlePragmaOpenCLExtension(); 624 return DeclGroupPtrTy(); 625 case tok::annot_pragma_openmp: 626 ParseOpenMPDeclarativeDirective(); 627 return DeclGroupPtrTy(); 628 case tok::annot_pragma_ms_pointers_to_members: 629 HandlePragmaMSPointersToMembers(); 630 return DeclGroupPtrTy(); 631 case tok::annot_pragma_ms_vtordisp: 632 HandlePragmaMSVtorDisp(); 633 return DeclGroupPtrTy(); 634 case tok::semi: 635 // Either a C++11 empty-declaration or attribute-declaration. 636 SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(), 637 attrs.getList(), 638 Tok.getLocation()); 639 ConsumeExtraSemi(OutsideFunction); 640 break; 641 case tok::r_brace: 642 Diag(Tok, diag::err_extraneous_closing_brace); 643 ConsumeBrace(); 644 return DeclGroupPtrTy(); 645 case tok::eof: 646 Diag(Tok, diag::err_expected_external_declaration); 647 return DeclGroupPtrTy(); 648 case tok::kw___extension__: { 649 // __extension__ silences extension warnings in the subexpression. 650 ExtensionRAIIObject O(Diags); // Use RAII to do this. 651 ConsumeToken(); 652 return ParseExternalDeclaration(attrs); 653 } 654 case tok::kw_asm: { 655 ProhibitAttributes(attrs); 656 657 SourceLocation StartLoc = Tok.getLocation(); 658 SourceLocation EndLoc; 659 ExprResult Result(ParseSimpleAsm(&EndLoc)); 660 661 ExpectAndConsume(tok::semi, diag::err_expected_after, 662 "top-level asm block"); 663 664 if (Result.isInvalid()) 665 return DeclGroupPtrTy(); 666 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc); 667 break; 668 } 669 case tok::at: 670 return ParseObjCAtDirectives(); 671 case tok::minus: 672 case tok::plus: 673 if (!getLangOpts().ObjC1) { 674 Diag(Tok, diag::err_expected_external_declaration); 675 ConsumeToken(); 676 return DeclGroupPtrTy(); 677 } 678 SingleDecl = ParseObjCMethodDefinition(); 679 break; 680 case tok::code_completion: 681 Actions.CodeCompleteOrdinaryName(getCurScope(), 682 CurParsedObjCImpl? Sema::PCC_ObjCImplementation 683 : Sema::PCC_Namespace); 684 cutOffParsing(); 685 return DeclGroupPtrTy(); 686 case tok::kw_using: 687 case tok::kw_namespace: 688 case tok::kw_typedef: 689 case tok::kw_template: 690 case tok::kw_export: // As in 'export template' 691 case tok::kw_static_assert: 692 case tok::kw__Static_assert: 693 // A function definition cannot start with any of these keywords. 694 { 695 SourceLocation DeclEnd; 696 StmtVector Stmts; 697 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 698 } 699 700 case tok::kw_static: 701 // Parse (then ignore) 'static' prior to a template instantiation. This is 702 // a GCC extension that we intentionally do not support. 703 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) { 704 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 705 << 0; 706 SourceLocation DeclEnd; 707 StmtVector Stmts; 708 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 709 } 710 goto dont_know; 711 712 case tok::kw_inline: 713 if (getLangOpts().CPlusPlus) { 714 tok::TokenKind NextKind = NextToken().getKind(); 715 716 // Inline namespaces. Allowed as an extension even in C++03. 717 if (NextKind == tok::kw_namespace) { 718 SourceLocation DeclEnd; 719 StmtVector Stmts; 720 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 721 } 722 723 // Parse (then ignore) 'inline' prior to a template instantiation. This is 724 // a GCC extension that we intentionally do not support. 725 if (NextKind == tok::kw_template) { 726 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 727 << 1; 728 SourceLocation DeclEnd; 729 StmtVector Stmts; 730 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 731 } 732 } 733 goto dont_know; 734 735 case tok::kw_extern: 736 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) { 737 // Extern templates 738 SourceLocation ExternLoc = ConsumeToken(); 739 SourceLocation TemplateLoc = ConsumeToken(); 740 Diag(ExternLoc, getLangOpts().CPlusPlus11 ? 741 diag::warn_cxx98_compat_extern_template : 742 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc); 743 SourceLocation DeclEnd; 744 return Actions.ConvertDeclToDeclGroup( 745 ParseExplicitInstantiation(Declarator::FileContext, 746 ExternLoc, TemplateLoc, DeclEnd)); 747 } 748 goto dont_know; 749 750 case tok::kw___if_exists: 751 case tok::kw___if_not_exists: 752 ParseMicrosoftIfExistsExternalDeclaration(); 753 return DeclGroupPtrTy(); 754 755 default: 756 dont_know: 757 // We can't tell whether this is a function-definition or declaration yet. 758 return ParseDeclarationOrFunctionDefinition(attrs, DS); 759 } 760 761 // This routine returns a DeclGroup, if the thing we parsed only contains a 762 // single decl, convert it now. 763 return Actions.ConvertDeclToDeclGroup(SingleDecl); 764 } 765 766 /// \brief Determine whether the current token, if it occurs after a 767 /// declarator, continues a declaration or declaration list. 768 bool Parser::isDeclarationAfterDeclarator() { 769 // Check for '= delete' or '= default' 770 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) { 771 const Token &KW = NextToken(); 772 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete)) 773 return false; 774 } 775 776 return Tok.is(tok::equal) || // int X()= -> not a function def 777 Tok.is(tok::comma) || // int X(), -> not a function def 778 Tok.is(tok::semi) || // int X(); -> not a function def 779 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def 780 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def 781 (getLangOpts().CPlusPlus && 782 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++] 783 } 784 785 /// \brief Determine whether the current token, if it occurs after a 786 /// declarator, indicates the start of a function definition. 787 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) { 788 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator"); 789 if (Tok.is(tok::l_brace)) // int X() {} 790 return true; 791 792 // Handle K&R C argument lists: int X(f) int f; {} 793 if (!getLangOpts().CPlusPlus && 794 Declarator.getFunctionTypeInfo().isKNRPrototype()) 795 return isDeclarationSpecifier(); 796 797 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) { 798 const Token &KW = NextToken(); 799 return KW.is(tok::kw_default) || KW.is(tok::kw_delete); 800 } 801 802 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors) 803 Tok.is(tok::kw_try); // X() try { ... } 804 } 805 806 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or 807 /// a declaration. We can't tell which we have until we read up to the 808 /// compound-statement in function-definition. TemplateParams, if 809 /// non-NULL, provides the template parameters when we're parsing a 810 /// C++ template-declaration. 811 /// 812 /// function-definition: [C99 6.9.1] 813 /// decl-specs declarator declaration-list[opt] compound-statement 814 /// [C90] function-definition: [C99 6.7.1] - implicit int result 815 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 816 /// 817 /// declaration: [C99 6.7] 818 /// declaration-specifiers init-declarator-list[opt] ';' 819 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode] 820 /// [OMP] threadprivate-directive [TODO] 821 /// 822 Parser::DeclGroupPtrTy 823 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, 824 ParsingDeclSpec &DS, 825 AccessSpecifier AS) { 826 // Parse the common declaration-specifiers piece. 827 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level); 828 829 // If we had a free-standing type definition with a missing semicolon, we 830 // may get this far before the problem becomes obvious. 831 if (DS.hasTagDefinition() && 832 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level)) 833 return DeclGroupPtrTy(); 834 835 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 836 // declaration-specifiers init-declarator-list[opt] ';' 837 if (Tok.is(tok::semi)) { 838 ProhibitAttributes(attrs); 839 ConsumeToken(); 840 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS); 841 DS.complete(TheDecl); 842 return Actions.ConvertDeclToDeclGroup(TheDecl); 843 } 844 845 DS.takeAttributesFrom(attrs); 846 847 // ObjC2 allows prefix attributes on class interfaces and protocols. 848 // FIXME: This still needs better diagnostics. We should only accept 849 // attributes here, no types, etc. 850 if (getLangOpts().ObjC2 && Tok.is(tok::at)) { 851 SourceLocation AtLoc = ConsumeToken(); // the "@" 852 if (!Tok.isObjCAtKeyword(tok::objc_interface) && 853 !Tok.isObjCAtKeyword(tok::objc_protocol)) { 854 Diag(Tok, diag::err_objc_unexpected_attr); 855 SkipUntil(tok::semi); // FIXME: better skip? 856 return DeclGroupPtrTy(); 857 } 858 859 DS.abort(); 860 861 const char *PrevSpec = 0; 862 unsigned DiagID; 863 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID, 864 Actions.getASTContext().getPrintingPolicy())) 865 Diag(AtLoc, DiagID) << PrevSpec; 866 867 if (Tok.isObjCAtKeyword(tok::objc_protocol)) 868 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()); 869 870 return Actions.ConvertDeclToDeclGroup( 871 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes())); 872 } 873 874 // If the declspec consisted only of 'extern' and we have a string 875 // literal following it, this must be a C++ linkage specifier like 876 // 'extern "C"'. 877 if (getLangOpts().CPlusPlus && isTokenStringLiteral() && 878 DS.getStorageClassSpec() == DeclSpec::SCS_extern && 879 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) { 880 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext); 881 return Actions.ConvertDeclToDeclGroup(TheDecl); 882 } 883 884 return ParseDeclGroup(DS, Declarator::FileContext, true); 885 } 886 887 Parser::DeclGroupPtrTy 888 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs, 889 ParsingDeclSpec *DS, 890 AccessSpecifier AS) { 891 if (DS) { 892 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS); 893 } else { 894 ParsingDeclSpec PDS(*this); 895 // Must temporarily exit the objective-c container scope for 896 // parsing c constructs and re-enter objc container scope 897 // afterwards. 898 ObjCDeclContextSwitch ObjCDC(*this); 899 900 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS); 901 } 902 } 903 904 905 static inline bool isFunctionDeclaratorRequiringReturnTypeDeduction( 906 const Declarator &D) { 907 if (!D.isFunctionDeclarator() || !D.getDeclSpec().containsPlaceholderType()) 908 return false; 909 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 910 unsigned chunkIndex = E - I - 1; 911 const DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 912 if (DeclType.Kind == DeclaratorChunk::Function) { 913 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 914 if (!FTI.hasTrailingReturnType()) 915 return true; 916 QualType TrailingRetType = FTI.getTrailingReturnType().get(); 917 return TrailingRetType->getCanonicalTypeInternal() 918 ->getContainedAutoType(); 919 } 920 } 921 return false; 922 } 923 924 /// ParseFunctionDefinition - We parsed and verified that the specified 925 /// Declarator is well formed. If this is a K&R-style function, read the 926 /// parameters declaration-list, then start the compound-statement. 927 /// 928 /// function-definition: [C99 6.9.1] 929 /// decl-specs declarator declaration-list[opt] compound-statement 930 /// [C90] function-definition: [C99 6.7.1] - implicit int result 931 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 932 /// [C++] function-definition: [C++ 8.4] 933 /// decl-specifier-seq[opt] declarator ctor-initializer[opt] 934 /// function-body 935 /// [C++] function-definition: [C++ 8.4] 936 /// decl-specifier-seq[opt] declarator function-try-block 937 /// 938 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, 939 const ParsedTemplateInfo &TemplateInfo, 940 LateParsedAttrList *LateParsedAttrs) { 941 // Poison the SEH identifiers so they are flagged as illegal in function bodies 942 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 943 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 944 945 // If this is C90 and the declspecs were completely missing, fudge in an 946 // implicit int. We do this here because this is the only place where 947 // declaration-specifiers are completely optional in the grammar. 948 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) { 949 const char *PrevSpec; 950 unsigned DiagID; 951 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 952 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int, 953 D.getIdentifierLoc(), 954 PrevSpec, DiagID, 955 Policy); 956 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin()); 957 } 958 959 // If this declaration was formed with a K&R-style identifier list for the 960 // arguments, parse declarations for all of the args next. 961 // int foo(a,b) int a; float b; {} 962 if (FTI.isKNRPrototype()) 963 ParseKNRParamDeclarations(D); 964 965 // We should have either an opening brace or, in a C++ constructor, 966 // we may have a colon. 967 if (Tok.isNot(tok::l_brace) && 968 (!getLangOpts().CPlusPlus || 969 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && 970 Tok.isNot(tok::equal)))) { 971 Diag(Tok, diag::err_expected_fn_body); 972 973 // Skip over garbage, until we get to '{'. Don't eat the '{'. 974 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 975 976 // If we didn't find the '{', bail out. 977 if (Tok.isNot(tok::l_brace)) 978 return 0; 979 } 980 981 // Check to make sure that any normal attributes are allowed to be on 982 // a definition. Late parsed attributes are checked at the end. 983 if (Tok.isNot(tok::equal)) { 984 AttributeList *DtorAttrs = D.getAttributes(); 985 while (DtorAttrs) { 986 if (DtorAttrs->isKnownToGCC() && 987 !DtorAttrs->isCXX11Attribute()) { 988 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition) 989 << DtorAttrs->getName(); 990 } 991 DtorAttrs = DtorAttrs->getNext(); 992 } 993 } 994 995 // In delayed template parsing mode, for function template we consume the 996 // tokens and store them for late parsing at the end of the translation unit. 997 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) && 998 TemplateInfo.Kind == ParsedTemplateInfo::Template && 999 !D.getDeclSpec().isConstexprSpecified() && 1000 !isFunctionDeclaratorRequiringReturnTypeDeduction(D)) { 1001 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams); 1002 1003 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); 1004 Scope *ParentScope = getCurScope()->getParent(); 1005 1006 D.setFunctionDefinitionKind(FDK_Definition); 1007 Decl *DP = Actions.HandleDeclarator(ParentScope, D, 1008 TemplateParameterLists); 1009 D.complete(DP); 1010 D.getMutableDeclSpec().abort(); 1011 1012 CachedTokens Toks; 1013 LexTemplateFunctionForLateParsing(Toks); 1014 1015 if (DP) { 1016 FunctionDecl *FnD = DP->getAsFunction(); 1017 Actions.CheckForFunctionRedefinition(FnD); 1018 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks); 1019 } 1020 return DP; 1021 } 1022 else if (CurParsedObjCImpl && 1023 !TemplateInfo.TemplateParams && 1024 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || 1025 Tok.is(tok::colon)) && 1026 Actions.CurContext->isTranslationUnit()) { 1027 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); 1028 Scope *ParentScope = getCurScope()->getParent(); 1029 1030 D.setFunctionDefinitionKind(FDK_Definition); 1031 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D, 1032 MultiTemplateParamsArg()); 1033 D.complete(FuncDecl); 1034 D.getMutableDeclSpec().abort(); 1035 if (FuncDecl) { 1036 // Consume the tokens and store them for later parsing. 1037 StashAwayMethodOrFunctionBodyTokens(FuncDecl); 1038 CurParsedObjCImpl->HasCFunction = true; 1039 return FuncDecl; 1040 } 1041 } 1042 1043 // Enter a scope for the function body. 1044 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); 1045 1046 // Tell the actions module that we have entered a function definition with the 1047 // specified Declarator for the function. 1048 Decl *Res = TemplateInfo.TemplateParams? 1049 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(), 1050 *TemplateInfo.TemplateParams, D) 1051 : Actions.ActOnStartOfFunctionDef(getCurScope(), D); 1052 1053 // Break out of the ParsingDeclarator context before we parse the body. 1054 D.complete(Res); 1055 1056 // Break out of the ParsingDeclSpec context, too. This const_cast is 1057 // safe because we're always the sole owner. 1058 D.getMutableDeclSpec().abort(); 1059 1060 if (TryConsumeToken(tok::equal)) { 1061 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='"); 1062 Actions.ActOnFinishFunctionBody(Res, 0, false); 1063 1064 bool Delete = false; 1065 SourceLocation KWLoc; 1066 if (TryConsumeToken(tok::kw_delete, KWLoc)) { 1067 Diag(KWLoc, getLangOpts().CPlusPlus11 1068 ? diag::warn_cxx98_compat_deleted_function 1069 : diag::ext_deleted_function); 1070 Actions.SetDeclDeleted(Res, KWLoc); 1071 Delete = true; 1072 } else if (TryConsumeToken(tok::kw_default, KWLoc)) { 1073 Diag(KWLoc, getLangOpts().CPlusPlus11 1074 ? diag::warn_cxx98_compat_defaulted_function 1075 : diag::ext_defaulted_function); 1076 Actions.SetDeclDefaulted(Res, KWLoc); 1077 } else { 1078 llvm_unreachable("function definition after = not 'delete' or 'default'"); 1079 } 1080 1081 if (Tok.is(tok::comma)) { 1082 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) 1083 << Delete; 1084 SkipUntil(tok::semi); 1085 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after, 1086 Delete ? "delete" : "default")) { 1087 SkipUntil(tok::semi); 1088 } 1089 1090 return Res; 1091 } 1092 1093 if (Tok.is(tok::kw_try)) 1094 return ParseFunctionTryBlock(Res, BodyScope); 1095 1096 // If we have a colon, then we're probably parsing a C++ 1097 // ctor-initializer. 1098 if (Tok.is(tok::colon)) { 1099 ParseConstructorInitializer(Res); 1100 1101 // Recover from error. 1102 if (!Tok.is(tok::l_brace)) { 1103 BodyScope.Exit(); 1104 Actions.ActOnFinishFunctionBody(Res, 0); 1105 return Res; 1106 } 1107 } else 1108 Actions.ActOnDefaultCtorInitializers(Res); 1109 1110 // Late attributes are parsed in the same scope as the function body. 1111 if (LateParsedAttrs) 1112 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true); 1113 1114 return ParseFunctionStatementBody(Res, BodyScope); 1115 } 1116 1117 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides 1118 /// types for a function with a K&R-style identifier list for arguments. 1119 void Parser::ParseKNRParamDeclarations(Declarator &D) { 1120 // We know that the top-level of this declarator is a function. 1121 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 1122 1123 // Enter function-declaration scope, limiting any declarators to the 1124 // function prototype scope, including parameter declarators. 1125 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | 1126 Scope::FunctionDeclarationScope | Scope::DeclScope); 1127 1128 // Read all the argument declarations. 1129 while (isDeclarationSpecifier()) { 1130 SourceLocation DSStart = Tok.getLocation(); 1131 1132 // Parse the common declaration-specifiers piece. 1133 DeclSpec DS(AttrFactory); 1134 ParseDeclarationSpecifiers(DS); 1135 1136 // C99 6.9.1p6: 'each declaration in the declaration list shall have at 1137 // least one declarator'. 1138 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with 1139 // the declarations though. It's trivial to ignore them, really hard to do 1140 // anything else with them. 1141 if (TryConsumeToken(tok::semi)) { 1142 Diag(DSStart, diag::err_declaration_does_not_declare_param); 1143 continue; 1144 } 1145 1146 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other 1147 // than register. 1148 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1149 DS.getStorageClassSpec() != DeclSpec::SCS_register) { 1150 Diag(DS.getStorageClassSpecLoc(), 1151 diag::err_invalid_storage_class_in_func_decl); 1152 DS.ClearStorageClassSpecs(); 1153 } 1154 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) { 1155 Diag(DS.getThreadStorageClassSpecLoc(), 1156 diag::err_invalid_storage_class_in_func_decl); 1157 DS.ClearStorageClassSpecs(); 1158 } 1159 1160 // Parse the first declarator attached to this declspec. 1161 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext); 1162 ParseDeclarator(ParmDeclarator); 1163 1164 // Handle the full declarator list. 1165 while (1) { 1166 // If attributes are present, parse them. 1167 MaybeParseGNUAttributes(ParmDeclarator); 1168 1169 // Ask the actions module to compute the type for this declarator. 1170 Decl *Param = 1171 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 1172 1173 if (Param && 1174 // A missing identifier has already been diagnosed. 1175 ParmDeclarator.getIdentifier()) { 1176 1177 // Scan the argument list looking for the correct param to apply this 1178 // type. 1179 for (unsigned i = 0; ; ++i) { 1180 // C99 6.9.1p6: those declarators shall declare only identifiers from 1181 // the identifier list. 1182 if (i == FTI.NumParams) { 1183 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param) 1184 << ParmDeclarator.getIdentifier(); 1185 break; 1186 } 1187 1188 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) { 1189 // Reject redefinitions of parameters. 1190 if (FTI.Params[i].Param) { 1191 Diag(ParmDeclarator.getIdentifierLoc(), 1192 diag::err_param_redefinition) 1193 << ParmDeclarator.getIdentifier(); 1194 } else { 1195 FTI.Params[i].Param = Param; 1196 } 1197 break; 1198 } 1199 } 1200 } 1201 1202 // If we don't have a comma, it is either the end of the list (a ';') or 1203 // an error, bail out. 1204 if (Tok.isNot(tok::comma)) 1205 break; 1206 1207 ParmDeclarator.clear(); 1208 1209 // Consume the comma. 1210 ParmDeclarator.setCommaLoc(ConsumeToken()); 1211 1212 // Parse the next declarator. 1213 ParseDeclarator(ParmDeclarator); 1214 } 1215 1216 // Consume ';' and continue parsing. 1217 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) 1218 continue; 1219 1220 // Otherwise recover by skipping to next semi or mandatory function body. 1221 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch)) 1222 break; 1223 TryConsumeToken(tok::semi); 1224 } 1225 1226 // The actions module must verify that all arguments were declared. 1227 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation()); 1228 } 1229 1230 1231 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not 1232 /// allowed to be a wide string, and is not subject to character translation. 1233 /// 1234 /// [GNU] asm-string-literal: 1235 /// string-literal 1236 /// 1237 Parser::ExprResult Parser::ParseAsmStringLiteral() { 1238 switch (Tok.getKind()) { 1239 case tok::string_literal: 1240 break; 1241 case tok::utf8_string_literal: 1242 case tok::utf16_string_literal: 1243 case tok::utf32_string_literal: 1244 case tok::wide_string_literal: { 1245 SourceLocation L = Tok.getLocation(); 1246 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1247 << (Tok.getKind() == tok::wide_string_literal) 1248 << SourceRange(L, L); 1249 return ExprError(); 1250 } 1251 default: 1252 Diag(Tok, diag::err_expected_string_literal) 1253 << /*Source='in...'*/0 << "'asm'"; 1254 return ExprError(); 1255 } 1256 1257 return ParseStringLiteralExpression(); 1258 } 1259 1260 /// ParseSimpleAsm 1261 /// 1262 /// [GNU] simple-asm-expr: 1263 /// 'asm' '(' asm-string-literal ')' 1264 /// 1265 Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) { 1266 assert(Tok.is(tok::kw_asm) && "Not an asm!"); 1267 SourceLocation Loc = ConsumeToken(); 1268 1269 if (Tok.is(tok::kw_volatile)) { 1270 // Remove from the end of 'asm' to the end of 'volatile'. 1271 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc), 1272 PP.getLocForEndOfToken(Tok.getLocation())); 1273 1274 Diag(Tok, diag::warn_file_asm_volatile) 1275 << FixItHint::CreateRemoval(RemovalRange); 1276 ConsumeToken(); 1277 } 1278 1279 BalancedDelimiterTracker T(*this, tok::l_paren); 1280 if (T.consumeOpen()) { 1281 Diag(Tok, diag::err_expected_lparen_after) << "asm"; 1282 return ExprError(); 1283 } 1284 1285 ExprResult Result(ParseAsmStringLiteral()); 1286 1287 if (!Result.isInvalid()) { 1288 // Close the paren and get the location of the end bracket 1289 T.consumeClose(); 1290 if (EndLoc) 1291 *EndLoc = T.getCloseLocation(); 1292 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) { 1293 if (EndLoc) 1294 *EndLoc = Tok.getLocation(); 1295 ConsumeParen(); 1296 } 1297 1298 return Result; 1299 } 1300 1301 /// \brief Get the TemplateIdAnnotation from the token and put it in the 1302 /// cleanup pool so that it gets destroyed when parsing the current top level 1303 /// declaration is finished. 1304 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) { 1305 assert(tok.is(tok::annot_template_id) && "Expected template-id token"); 1306 TemplateIdAnnotation * 1307 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue()); 1308 return Id; 1309 } 1310 1311 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) { 1312 // Push the current token back into the token stream (or revert it if it is 1313 // cached) and use an annotation scope token for current token. 1314 if (PP.isBacktrackEnabled()) 1315 PP.RevertCachedTokens(1); 1316 else 1317 PP.EnterToken(Tok); 1318 Tok.setKind(tok::annot_cxxscope); 1319 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1320 Tok.setAnnotationRange(SS.getRange()); 1321 1322 // In case the tokens were cached, have Preprocessor replace them 1323 // with the annotation token. We don't need to do this if we've 1324 // just reverted back to a prior state. 1325 if (IsNewAnnotation) 1326 PP.AnnotateCachedTokens(Tok); 1327 } 1328 1329 /// \brief Attempt to classify the name at the current token position. This may 1330 /// form a type, scope or primary expression annotation, or replace the token 1331 /// with a typo-corrected keyword. This is only appropriate when the current 1332 /// name must refer to an entity which has already been declared. 1333 /// 1334 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&' 1335 /// and might possibly have a dependent nested name specifier. 1336 /// \param CCC Indicates how to perform typo-correction for this name. If NULL, 1337 /// no typo correction will be performed. 1338 Parser::AnnotatedNameKind 1339 Parser::TryAnnotateName(bool IsAddressOfOperand, 1340 CorrectionCandidateCallback *CCC) { 1341 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope)); 1342 1343 const bool EnteringContext = false; 1344 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1345 1346 CXXScopeSpec SS; 1347 if (getLangOpts().CPlusPlus && 1348 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1349 return ANK_Error; 1350 1351 if (Tok.isNot(tok::identifier) || SS.isInvalid()) { 1352 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS, 1353 !WasScopeAnnotation)) 1354 return ANK_Error; 1355 return ANK_Unresolved; 1356 } 1357 1358 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1359 SourceLocation NameLoc = Tok.getLocation(); 1360 1361 // FIXME: Move the tentative declaration logic into ClassifyName so we can 1362 // typo-correct to tentatively-declared identifiers. 1363 if (isTentativelyDeclared(Name)) { 1364 // Identifier has been tentatively declared, and thus cannot be resolved as 1365 // an expression. Fall back to annotating it as a type. 1366 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS, 1367 !WasScopeAnnotation)) 1368 return ANK_Error; 1369 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl; 1370 } 1371 1372 Token Next = NextToken(); 1373 1374 // Look up and classify the identifier. We don't perform any typo-correction 1375 // after a scope specifier, because in general we can't recover from typos 1376 // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to 1377 // jump back into scope specifier parsing). 1378 Sema::NameClassification Classification 1379 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next, 1380 IsAddressOfOperand, SS.isEmpty() ? CCC : 0); 1381 1382 switch (Classification.getKind()) { 1383 case Sema::NC_Error: 1384 return ANK_Error; 1385 1386 case Sema::NC_Keyword: 1387 // The identifier was typo-corrected to a keyword. 1388 Tok.setIdentifierInfo(Name); 1389 Tok.setKind(Name->getTokenID()); 1390 PP.TypoCorrectToken(Tok); 1391 if (SS.isNotEmpty()) 1392 AnnotateScopeToken(SS, !WasScopeAnnotation); 1393 // We've "annotated" this as a keyword. 1394 return ANK_Success; 1395 1396 case Sema::NC_Unknown: 1397 // It's not something we know about. Leave it unannotated. 1398 break; 1399 1400 case Sema::NC_Type: 1401 Tok.setKind(tok::annot_typename); 1402 setTypeAnnotation(Tok, Classification.getType()); 1403 Tok.setAnnotationEndLoc(NameLoc); 1404 if (SS.isNotEmpty()) 1405 Tok.setLocation(SS.getBeginLoc()); 1406 PP.AnnotateCachedTokens(Tok); 1407 return ANK_Success; 1408 1409 case Sema::NC_Expression: 1410 Tok.setKind(tok::annot_primary_expr); 1411 setExprAnnotation(Tok, Classification.getExpression()); 1412 Tok.setAnnotationEndLoc(NameLoc); 1413 if (SS.isNotEmpty()) 1414 Tok.setLocation(SS.getBeginLoc()); 1415 PP.AnnotateCachedTokens(Tok); 1416 return ANK_Success; 1417 1418 case Sema::NC_TypeTemplate: 1419 if (Next.isNot(tok::less)) { 1420 // This may be a type template being used as a template template argument. 1421 if (SS.isNotEmpty()) 1422 AnnotateScopeToken(SS, !WasScopeAnnotation); 1423 return ANK_TemplateName; 1424 } 1425 // Fall through. 1426 case Sema::NC_VarTemplate: 1427 case Sema::NC_FunctionTemplate: { 1428 // We have a type, variable or function template followed by '<'. 1429 ConsumeToken(); 1430 UnqualifiedId Id; 1431 Id.setIdentifier(Name, NameLoc); 1432 if (AnnotateTemplateIdToken( 1433 TemplateTy::make(Classification.getTemplateName()), 1434 Classification.getTemplateNameKind(), SS, SourceLocation(), Id)) 1435 return ANK_Error; 1436 return ANK_Success; 1437 } 1438 1439 case Sema::NC_NestedNameSpecifier: 1440 llvm_unreachable("already parsed nested name specifier"); 1441 } 1442 1443 // Unable to classify the name, but maybe we can annotate a scope specifier. 1444 if (SS.isNotEmpty()) 1445 AnnotateScopeToken(SS, !WasScopeAnnotation); 1446 return ANK_Unresolved; 1447 } 1448 1449 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) { 1450 assert(!Tok.is(tok::identifier) && !Tok.isAnnotation()); 1451 Diag(Tok, diag::ext_keyword_as_ident) 1452 << PP.getSpelling(Tok) 1453 << DisableKeyword; 1454 if (DisableKeyword) { 1455 IdentifierInfo *II = Tok.getIdentifierInfo(); 1456 ContextualKeywords[II] = Tok.getKind(); 1457 II->RevertTokenIDToIdentifier(); 1458 } 1459 Tok.setKind(tok::identifier); 1460 return true; 1461 } 1462 1463 bool Parser::TryIdentKeywordUpgrade() { 1464 assert(Tok.is(tok::identifier)); 1465 const IdentifierInfo *II = Tok.getIdentifierInfo(); 1466 assert(II->hasRevertedTokenIDToIdentifier()); 1467 // If we find that this is in fact the name of a type trait, 1468 // update the token kind in place and parse again to treat it as 1469 // the appropriate kind of type trait. 1470 llvm::SmallDenseMap<const IdentifierInfo *, tok::TokenKind>::iterator Known = 1471 ContextualKeywords.find(II); 1472 if (Known == ContextualKeywords.end()) 1473 return false; 1474 Tok.setKind(Known->second); 1475 return true; 1476 } 1477 1478 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 1479 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 1480 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 1481 /// with a single annotation token representing the typename or C++ scope 1482 /// respectively. 1483 /// This simplifies handling of C++ scope specifiers and allows efficient 1484 /// backtracking without the need to re-parse and resolve nested-names and 1485 /// typenames. 1486 /// It will mainly be called when we expect to treat identifiers as typenames 1487 /// (if they are typenames). For example, in C we do not expect identifiers 1488 /// inside expressions to be treated as typenames so it will not be called 1489 /// for expressions in C. 1490 /// The benefit for C/ObjC is that a typename will be annotated and 1491 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName 1492 /// will not be called twice, once to check whether we have a declaration 1493 /// specifier, and another one to get the actual type inside 1494 /// ParseDeclarationSpecifiers). 1495 /// 1496 /// This returns true if an error occurred. 1497 /// 1498 /// Note that this routine emits an error if you call it with ::new or ::delete 1499 /// as the current tokens, so only call it in contexts where these are invalid. 1500 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) { 1501 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) 1502 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) 1503 || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id)) 1504 && "Cannot be a type or scope token!"); 1505 1506 if (Tok.is(tok::kw_typename)) { 1507 // MSVC lets you do stuff like: 1508 // typename typedef T_::D D; 1509 // 1510 // We will consume the typedef token here and put it back after we have 1511 // parsed the first identifier, transforming it into something more like: 1512 // typename T_::D typedef D; 1513 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) { 1514 Token TypedefToken; 1515 PP.Lex(TypedefToken); 1516 bool Result = TryAnnotateTypeOrScopeToken(EnteringContext, NeedType); 1517 PP.EnterToken(Tok); 1518 Tok = TypedefToken; 1519 if (!Result) 1520 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename); 1521 return Result; 1522 } 1523 1524 // Parse a C++ typename-specifier, e.g., "typename T::type". 1525 // 1526 // typename-specifier: 1527 // 'typename' '::' [opt] nested-name-specifier identifier 1528 // 'typename' '::' [opt] nested-name-specifier template [opt] 1529 // simple-template-id 1530 SourceLocation TypenameLoc = ConsumeToken(); 1531 CXXScopeSpec SS; 1532 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(), 1533 /*EnteringContext=*/false, 1534 0, /*IsTypename*/true)) 1535 return true; 1536 if (!SS.isSet()) { 1537 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) || 1538 Tok.is(tok::annot_decltype)) { 1539 // Attempt to recover by skipping the invalid 'typename' 1540 if (Tok.is(tok::annot_decltype) || 1541 (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) && 1542 Tok.isAnnotation())) { 1543 unsigned DiagID = diag::err_expected_qualified_after_typename; 1544 // MS compatibility: MSVC permits using known types with typename. 1545 // e.g. "typedef typename T* pointer_type" 1546 if (getLangOpts().MicrosoftExt) 1547 DiagID = diag::warn_expected_qualified_after_typename; 1548 Diag(Tok.getLocation(), DiagID); 1549 return false; 1550 } 1551 } 1552 1553 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); 1554 return true; 1555 } 1556 1557 TypeResult Ty; 1558 if (Tok.is(tok::identifier)) { 1559 // FIXME: check whether the next token is '<', first! 1560 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1561 *Tok.getIdentifierInfo(), 1562 Tok.getLocation()); 1563 } else if (Tok.is(tok::annot_template_id)) { 1564 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1565 if (TemplateId->Kind != TNK_Type_template && 1566 TemplateId->Kind != TNK_Dependent_template_name) { 1567 Diag(Tok, diag::err_typename_refers_to_non_type_template) 1568 << Tok.getAnnotationRange(); 1569 return true; 1570 } 1571 1572 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1573 TemplateId->NumArgs); 1574 1575 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1576 TemplateId->TemplateKWLoc, 1577 TemplateId->Template, 1578 TemplateId->TemplateNameLoc, 1579 TemplateId->LAngleLoc, 1580 TemplateArgsPtr, 1581 TemplateId->RAngleLoc); 1582 } else { 1583 Diag(Tok, diag::err_expected_type_name_after_typename) 1584 << SS.getRange(); 1585 return true; 1586 } 1587 1588 SourceLocation EndLoc = Tok.getLastLoc(); 1589 Tok.setKind(tok::annot_typename); 1590 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get()); 1591 Tok.setAnnotationEndLoc(EndLoc); 1592 Tok.setLocation(TypenameLoc); 1593 PP.AnnotateCachedTokens(Tok); 1594 return false; 1595 } 1596 1597 // Remembers whether the token was originally a scope annotation. 1598 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1599 1600 CXXScopeSpec SS; 1601 if (getLangOpts().CPlusPlus) 1602 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1603 return true; 1604 1605 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType, 1606 SS, !WasScopeAnnotation); 1607 } 1608 1609 /// \brief Try to annotate a type or scope token, having already parsed an 1610 /// optional scope specifier. \p IsNewScope should be \c true unless the scope 1611 /// specifier was extracted from an existing tok::annot_cxxscope annotation. 1612 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext, 1613 bool NeedType, 1614 CXXScopeSpec &SS, 1615 bool IsNewScope) { 1616 if (Tok.is(tok::identifier)) { 1617 IdentifierInfo *CorrectedII = 0; 1618 // Determine whether the identifier is a type name. 1619 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(), 1620 Tok.getLocation(), getCurScope(), 1621 &SS, false, 1622 NextToken().is(tok::period), 1623 ParsedType(), 1624 /*IsCtorOrDtorName=*/false, 1625 /*NonTrivialTypeSourceInfo*/true, 1626 NeedType ? &CorrectedII : NULL)) { 1627 // A FixIt was applied as a result of typo correction 1628 if (CorrectedII) 1629 Tok.setIdentifierInfo(CorrectedII); 1630 // This is a typename. Replace the current token in-place with an 1631 // annotation type token. 1632 Tok.setKind(tok::annot_typename); 1633 setTypeAnnotation(Tok, Ty); 1634 Tok.setAnnotationEndLoc(Tok.getLocation()); 1635 if (SS.isNotEmpty()) // it was a C++ qualified type name. 1636 Tok.setLocation(SS.getBeginLoc()); 1637 1638 // In case the tokens were cached, have Preprocessor replace 1639 // them with the annotation token. 1640 PP.AnnotateCachedTokens(Tok); 1641 return false; 1642 } 1643 1644 if (!getLangOpts().CPlusPlus) { 1645 // If we're in C, we can't have :: tokens at all (the lexer won't return 1646 // them). If the identifier is not a type, then it can't be scope either, 1647 // just early exit. 1648 return false; 1649 } 1650 1651 // If this is a template-id, annotate with a template-id or type token. 1652 if (NextToken().is(tok::less)) { 1653 TemplateTy Template; 1654 UnqualifiedId TemplateName; 1655 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1656 bool MemberOfUnknownSpecialization; 1657 if (TemplateNameKind TNK 1658 = Actions.isTemplateName(getCurScope(), SS, 1659 /*hasTemplateKeyword=*/false, TemplateName, 1660 /*ObjectType=*/ ParsedType(), 1661 EnteringContext, 1662 Template, MemberOfUnknownSpecialization)) { 1663 // Consume the identifier. 1664 ConsumeToken(); 1665 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 1666 TemplateName)) { 1667 // If an unrecoverable error occurred, we need to return true here, 1668 // because the token stream is in a damaged state. We may not return 1669 // a valid identifier. 1670 return true; 1671 } 1672 } 1673 } 1674 1675 // The current token, which is either an identifier or a 1676 // template-id, is not part of the annotation. Fall through to 1677 // push that token back into the stream and complete the C++ scope 1678 // specifier annotation. 1679 } 1680 1681 if (Tok.is(tok::annot_template_id)) { 1682 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1683 if (TemplateId->Kind == TNK_Type_template) { 1684 // A template-id that refers to a type was parsed into a 1685 // template-id annotation in a context where we weren't allowed 1686 // to produce a type annotation token. Update the template-id 1687 // annotation token to a type annotation token now. 1688 AnnotateTemplateIdTokenAsType(); 1689 return false; 1690 } 1691 } 1692 1693 if (SS.isEmpty()) 1694 return false; 1695 1696 // A C++ scope specifier that isn't followed by a typename. 1697 AnnotateScopeToken(SS, IsNewScope); 1698 return false; 1699 } 1700 1701 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only 1702 /// annotates C++ scope specifiers and template-ids. This returns 1703 /// true if there was an error that could not be recovered from. 1704 /// 1705 /// Note that this routine emits an error if you call it with ::new or ::delete 1706 /// as the current tokens, so only call it in contexts where these are invalid. 1707 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { 1708 assert(getLangOpts().CPlusPlus && 1709 "Call sites of this function should be guarded by checking for C++"); 1710 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 1711 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || 1712 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!"); 1713 1714 CXXScopeSpec SS; 1715 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1716 return true; 1717 if (SS.isEmpty()) 1718 return false; 1719 1720 AnnotateScopeToken(SS, true); 1721 return false; 1722 } 1723 1724 bool Parser::isTokenEqualOrEqualTypo() { 1725 tok::TokenKind Kind = Tok.getKind(); 1726 switch (Kind) { 1727 default: 1728 return false; 1729 case tok::ampequal: // &= 1730 case tok::starequal: // *= 1731 case tok::plusequal: // += 1732 case tok::minusequal: // -= 1733 case tok::exclaimequal: // != 1734 case tok::slashequal: // /= 1735 case tok::percentequal: // %= 1736 case tok::lessequal: // <= 1737 case tok::lesslessequal: // <<= 1738 case tok::greaterequal: // >= 1739 case tok::greatergreaterequal: // >>= 1740 case tok::caretequal: // ^= 1741 case tok::pipeequal: // |= 1742 case tok::equalequal: // == 1743 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal) 1744 << Kind 1745 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "="); 1746 case tok::equal: 1747 return true; 1748 } 1749 } 1750 1751 SourceLocation Parser::handleUnexpectedCodeCompletionToken() { 1752 assert(Tok.is(tok::code_completion)); 1753 PrevTokLocation = Tok.getLocation(); 1754 1755 for (Scope *S = getCurScope(); S; S = S->getParent()) { 1756 if (S->getFlags() & Scope::FnScope) { 1757 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction); 1758 cutOffParsing(); 1759 return PrevTokLocation; 1760 } 1761 1762 if (S->getFlags() & Scope::ClassScope) { 1763 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); 1764 cutOffParsing(); 1765 return PrevTokLocation; 1766 } 1767 } 1768 1769 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); 1770 cutOffParsing(); 1771 return PrevTokLocation; 1772 } 1773 1774 // Anchor the Parser::FieldCallback vtable to this translation unit. 1775 // We use a spurious method instead of the destructor because 1776 // destroying FieldCallbacks can actually be slightly 1777 // performance-sensitive. 1778 void Parser::FieldCallback::_anchor() { 1779 } 1780 1781 // Code-completion pass-through functions 1782 1783 void Parser::CodeCompleteDirective(bool InConditional) { 1784 Actions.CodeCompletePreprocessorDirective(InConditional); 1785 } 1786 1787 void Parser::CodeCompleteInConditionalExclusion() { 1788 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope()); 1789 } 1790 1791 void Parser::CodeCompleteMacroName(bool IsDefinition) { 1792 Actions.CodeCompletePreprocessorMacroName(IsDefinition); 1793 } 1794 1795 void Parser::CodeCompletePreprocessorExpression() { 1796 Actions.CodeCompletePreprocessorExpression(); 1797 } 1798 1799 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro, 1800 MacroInfo *MacroInfo, 1801 unsigned ArgumentIndex) { 1802 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 1803 ArgumentIndex); 1804 } 1805 1806 void Parser::CodeCompleteNaturalLanguage() { 1807 Actions.CodeCompleteNaturalLanguage(); 1808 } 1809 1810 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { 1811 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) && 1812 "Expected '__if_exists' or '__if_not_exists'"); 1813 Result.IsIfExists = Tok.is(tok::kw___if_exists); 1814 Result.KeywordLoc = ConsumeToken(); 1815 1816 BalancedDelimiterTracker T(*this, tok::l_paren); 1817 if (T.consumeOpen()) { 1818 Diag(Tok, diag::err_expected_lparen_after) 1819 << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); 1820 return true; 1821 } 1822 1823 // Parse nested-name-specifier. 1824 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(), 1825 /*EnteringContext=*/false); 1826 1827 // Check nested-name specifier. 1828 if (Result.SS.isInvalid()) { 1829 T.skipToEnd(); 1830 return true; 1831 } 1832 1833 // Parse the unqualified-id. 1834 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused. 1835 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(), 1836 TemplateKWLoc, Result.Name)) { 1837 T.skipToEnd(); 1838 return true; 1839 } 1840 1841 if (T.consumeClose()) 1842 return true; 1843 1844 // Check if the symbol exists. 1845 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, 1846 Result.IsIfExists, Result.SS, 1847 Result.Name)) { 1848 case Sema::IER_Exists: 1849 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip; 1850 break; 1851 1852 case Sema::IER_DoesNotExist: 1853 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip; 1854 break; 1855 1856 case Sema::IER_Dependent: 1857 Result.Behavior = IEB_Dependent; 1858 break; 1859 1860 case Sema::IER_Error: 1861 return true; 1862 } 1863 1864 return false; 1865 } 1866 1867 void Parser::ParseMicrosoftIfExistsExternalDeclaration() { 1868 IfExistsCondition Result; 1869 if (ParseMicrosoftIfExistsCondition(Result)) 1870 return; 1871 1872 BalancedDelimiterTracker Braces(*this, tok::l_brace); 1873 if (Braces.consumeOpen()) { 1874 Diag(Tok, diag::err_expected) << tok::l_brace; 1875 return; 1876 } 1877 1878 switch (Result.Behavior) { 1879 case IEB_Parse: 1880 // Parse declarations below. 1881 break; 1882 1883 case IEB_Dependent: 1884 llvm_unreachable("Cannot have a dependent external declaration"); 1885 1886 case IEB_Skip: 1887 Braces.skipToEnd(); 1888 return; 1889 } 1890 1891 // Parse the declarations. 1892 // FIXME: Support module import within __if_exists? 1893 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 1894 ParsedAttributesWithRange attrs(AttrFactory); 1895 MaybeParseCXX11Attributes(attrs); 1896 MaybeParseMicrosoftAttributes(attrs); 1897 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs); 1898 if (Result && !getCurScope()->getParent()) 1899 Actions.getASTConsumer().HandleTopLevelDecl(Result.get()); 1900 } 1901 Braces.consumeClose(); 1902 } 1903 1904 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) { 1905 assert(Tok.isObjCAtKeyword(tok::objc_import) && 1906 "Improper start to module import"); 1907 SourceLocation ImportLoc = ConsumeToken(); 1908 1909 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1910 1911 // Parse the module path. 1912 do { 1913 if (!Tok.is(tok::identifier)) { 1914 if (Tok.is(tok::code_completion)) { 1915 Actions.CodeCompleteModuleImport(ImportLoc, Path); 1916 ConsumeCodeCompletionToken(); 1917 SkipUntil(tok::semi); 1918 return DeclGroupPtrTy(); 1919 } 1920 1921 Diag(Tok, diag::err_module_expected_ident); 1922 SkipUntil(tok::semi); 1923 return DeclGroupPtrTy(); 1924 } 1925 1926 // Record this part of the module path. 1927 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); 1928 ConsumeToken(); 1929 1930 if (Tok.is(tok::period)) { 1931 ConsumeToken(); 1932 continue; 1933 } 1934 1935 break; 1936 } while (true); 1937 1938 if (PP.hadModuleLoaderFatalFailure()) { 1939 // With a fatal failure in the module loader, we abort parsing. 1940 cutOffParsing(); 1941 return DeclGroupPtrTy(); 1942 } 1943 1944 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path); 1945 ExpectAndConsumeSemi(diag::err_module_expected_semi); 1946 if (Import.isInvalid()) 1947 return DeclGroupPtrTy(); 1948 1949 return Actions.ConvertDeclToDeclGroup(Import.get()); 1950 } 1951 1952 bool BalancedDelimiterTracker::diagnoseOverflow() { 1953 P.Diag(P.Tok, diag::err_bracket_depth_exceeded) 1954 << P.getLangOpts().BracketDepth; 1955 P.Diag(P.Tok, diag::note_bracket_depth); 1956 P.cutOffParsing(); 1957 return true; 1958 } 1959 1960 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, 1961 const char *Msg, 1962 tok::TokenKind SkipToTok) { 1963 LOpen = P.Tok.getLocation(); 1964 if (P.ExpectAndConsume(Kind, DiagID, Msg)) { 1965 if (SkipToTok != tok::unknown) 1966 P.SkipUntil(SkipToTok, Parser::StopAtSemi); 1967 return true; 1968 } 1969 1970 if (getDepth() < MaxDepth) 1971 return false; 1972 1973 return diagnoseOverflow(); 1974 } 1975 1976 bool BalancedDelimiterTracker::diagnoseMissingClose() { 1977 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter"); 1978 1979 P.Diag(P.Tok, diag::err_expected) << Close; 1980 P.Diag(LOpen, diag::note_matching) << Kind; 1981 1982 // If we're not already at some kind of closing bracket, skip to our closing 1983 // token. 1984 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) && 1985 P.Tok.isNot(tok::r_square) && 1986 P.SkipUntil(Close, FinalToken, 1987 Parser::StopAtSemi | Parser::StopBeforeMatch) && 1988 P.Tok.is(Close)) 1989 LClose = P.ConsumeAnyToken(); 1990 return true; 1991 } 1992 1993 void BalancedDelimiterTracker::skipToEnd() { 1994 P.SkipUntil(Close, Parser::StopBeforeMatch); 1995 consumeClose(); 1996 } 1997