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