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