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