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