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