1 //===--- Parser.cpp - C Language Family Parser ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Parser interfaces. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Parse/Parser.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/DeclTemplate.h" 17 #include "clang/Basic/FileManager.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 #include "llvm/Support/Path.h" 24 using namespace clang; 25 26 27 namespace { 28 /// A comment handler that passes comments found by the preprocessor 29 /// to the parser action. 30 class ActionCommentHandler : public CommentHandler { 31 Sema &S; 32 33 public: 34 explicit ActionCommentHandler(Sema &S) : S(S) { } 35 36 bool HandleComment(Preprocessor &PP, SourceRange Comment) override { 37 S.ActOnComment(Comment); 38 return false; 39 } 40 }; 41 } // end anonymous namespace 42 43 IdentifierInfo *Parser::getSEHExceptKeyword() { 44 // __except is accepted as a (contextual) keyword 45 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland)) 46 Ident__except = PP.getIdentifierInfo("__except"); 47 48 return Ident__except; 49 } 50 51 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies) 52 : PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions), 53 Diags(PP.getDiagnostics()), GreaterThanIsOperator(true), 54 ColonIsSacred(false), InMessageExpression(false), 55 TemplateParameterDepth(0), ParsingInObjCContainer(false) { 56 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies; 57 Tok.startToken(); 58 Tok.setKind(tok::eof); 59 Actions.CurScope = nullptr; 60 NumCachedScopes = 0; 61 CurParsedObjCImpl = nullptr; 62 63 // Add #pragma handlers. These are removed and destroyed in the 64 // destructor. 65 initializePragmaHandlers(); 66 67 CommentSemaHandler.reset(new ActionCommentHandler(actions)); 68 PP.addCommentHandler(CommentSemaHandler.get()); 69 70 PP.setCodeCompletionHandler(*this); 71 } 72 73 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) { 74 return Diags.Report(Loc, DiagID); 75 } 76 77 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) { 78 return Diag(Tok.getLocation(), DiagID); 79 } 80 81 /// Emits a diagnostic suggesting parentheses surrounding a 82 /// given range. 83 /// 84 /// \param Loc The location where we'll emit the diagnostic. 85 /// \param DK The kind of diagnostic to emit. 86 /// \param ParenRange Source range enclosing code that should be parenthesized. 87 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK, 88 SourceRange ParenRange) { 89 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd()); 90 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 91 // We can't display the parentheses, so just dig the 92 // warning/error and return. 93 Diag(Loc, DK); 94 return; 95 } 96 97 Diag(Loc, DK) 98 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 99 << FixItHint::CreateInsertion(EndLoc, ")"); 100 } 101 102 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) { 103 switch (ExpectedTok) { 104 case tok::semi: 105 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ; 106 default: return false; 107 } 108 } 109 110 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID, 111 StringRef Msg) { 112 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) { 113 ConsumeAnyToken(); 114 return false; 115 } 116 117 // Detect common single-character typos and resume. 118 if (IsCommonTypo(ExpectedTok, Tok)) { 119 SourceLocation Loc = Tok.getLocation(); 120 { 121 DiagnosticBuilder DB = Diag(Loc, DiagID); 122 DB << FixItHint::CreateReplacement( 123 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok)); 124 if (DiagID == diag::err_expected) 125 DB << ExpectedTok; 126 else if (DiagID == diag::err_expected_after) 127 DB << Msg << ExpectedTok; 128 else 129 DB << Msg; 130 } 131 132 // Pretend there wasn't a problem. 133 ConsumeAnyToken(); 134 return false; 135 } 136 137 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); 138 const char *Spelling = nullptr; 139 if (EndLoc.isValid()) 140 Spelling = tok::getPunctuatorSpelling(ExpectedTok); 141 142 DiagnosticBuilder DB = 143 Spelling 144 ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling) 145 : Diag(Tok, DiagID); 146 if (DiagID == diag::err_expected) 147 DB << ExpectedTok; 148 else if (DiagID == diag::err_expected_after) 149 DB << Msg << ExpectedTok; 150 else 151 DB << Msg; 152 153 return true; 154 } 155 156 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { 157 if (TryConsumeToken(tok::semi)) 158 return false; 159 160 if (Tok.is(tok::code_completion)) { 161 handleUnexpectedCodeCompletionToken(); 162 return false; 163 } 164 165 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && 166 NextToken().is(tok::semi)) { 167 Diag(Tok, diag::err_extraneous_token_before_semi) 168 << PP.getSpelling(Tok) 169 << FixItHint::CreateRemoval(Tok.getLocation()); 170 ConsumeAnyToken(); // The ')' or ']'. 171 ConsumeToken(); // The ';'. 172 return false; 173 } 174 175 return ExpectAndConsume(tok::semi, DiagID); 176 } 177 178 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) { 179 if (!Tok.is(tok::semi)) return; 180 181 bool HadMultipleSemis = false; 182 SourceLocation StartLoc = Tok.getLocation(); 183 SourceLocation EndLoc = Tok.getLocation(); 184 ConsumeToken(); 185 186 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) { 187 HadMultipleSemis = true; 188 EndLoc = Tok.getLocation(); 189 ConsumeToken(); 190 } 191 192 // C++11 allows extra semicolons at namespace scope, but not in any of the 193 // other contexts. 194 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) { 195 if (getLangOpts().CPlusPlus11) 196 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi) 197 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 198 else 199 Diag(StartLoc, diag::ext_extra_semi_cxx11) 200 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 201 return; 202 } 203 204 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis) 205 Diag(StartLoc, diag::ext_extra_semi) 206 << Kind << DeclSpec::getSpecifierName(TST, 207 Actions.getASTContext().getPrintingPolicy()) 208 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 209 else 210 // A single semicolon is valid after a member function definition. 211 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def) 212 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 213 } 214 215 bool Parser::expectIdentifier() { 216 if (Tok.is(tok::identifier)) 217 return false; 218 if (const auto *II = Tok.getIdentifierInfo()) { 219 if (II->isCPlusPlusKeyword(getLangOpts())) { 220 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword) 221 << tok::identifier << Tok.getIdentifierInfo(); 222 // Objective-C++: Recover by treating this keyword as a valid identifier. 223 return false; 224 } 225 } 226 Diag(Tok, diag::err_expected) << tok::identifier; 227 return true; 228 } 229 230 void Parser::checkCompoundToken(SourceLocation FirstTokLoc, 231 tok::TokenKind FirstTokKind, CompoundToken Op) { 232 if (FirstTokLoc.isInvalid()) 233 return; 234 SourceLocation SecondTokLoc = Tok.getLocation(); 235 236 // If either token is in a macro, we expect both tokens to come from the same 237 // macro expansion. 238 if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) && 239 PP.getSourceManager().getFileID(FirstTokLoc) != 240 PP.getSourceManager().getFileID(SecondTokLoc)) { 241 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro) 242 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind() 243 << static_cast<int>(Op) << SourceRange(FirstTokLoc); 244 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here) 245 << (FirstTokKind == Tok.getKind()) << Tok.getKind() 246 << SourceRange(SecondTokLoc); 247 return; 248 } 249 250 // We expect the tokens to abut. 251 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) { 252 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc); 253 if (SpaceLoc.isInvalid()) 254 SpaceLoc = FirstTokLoc; 255 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace) 256 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind() 257 << static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc); 258 return; 259 } 260 } 261 262 //===----------------------------------------------------------------------===// 263 // Error recovery. 264 //===----------------------------------------------------------------------===// 265 266 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) { 267 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0; 268 } 269 270 /// SkipUntil - Read tokens until we get to the specified token, then consume 271 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the 272 /// token will ever occur, this skips to the next token, or to some likely 273 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';' 274 /// character. 275 /// 276 /// If SkipUntil finds the specified token, it returns true, otherwise it 277 /// returns false. 278 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) { 279 // We always want this function to skip at least one token if the first token 280 // isn't T and if not at EOF. 281 bool isFirstTokenSkipped = true; 282 while (true) { 283 // If we found one of the tokens, stop and return true. 284 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) { 285 if (Tok.is(Toks[i])) { 286 if (HasFlagsSet(Flags, StopBeforeMatch)) { 287 // Noop, don't consume the token. 288 } else { 289 ConsumeAnyToken(); 290 } 291 return true; 292 } 293 } 294 295 // Important special case: The caller has given up and just wants us to 296 // skip the rest of the file. Do this without recursing, since we can 297 // get here precisely because the caller detected too much recursion. 298 if (Toks.size() == 1 && Toks[0] == tok::eof && 299 !HasFlagsSet(Flags, StopAtSemi) && 300 !HasFlagsSet(Flags, StopAtCodeCompletion)) { 301 while (Tok.isNot(tok::eof)) 302 ConsumeAnyToken(); 303 return true; 304 } 305 306 switch (Tok.getKind()) { 307 case tok::eof: 308 // Ran out of tokens. 309 return false; 310 311 case tok::annot_pragma_openmp: 312 case tok::annot_attr_openmp: 313 case tok::annot_pragma_openmp_end: 314 // Stop before an OpenMP pragma boundary. 315 if (OpenMPDirectiveParsing) 316 return false; 317 ConsumeAnnotationToken(); 318 break; 319 case tok::annot_module_begin: 320 case tok::annot_module_end: 321 case tok::annot_module_include: 322 // Stop before we change submodules. They generally indicate a "good" 323 // place to pick up parsing again (except in the special case where 324 // we're trying to skip to EOF). 325 return false; 326 327 case tok::code_completion: 328 if (!HasFlagsSet(Flags, StopAtCodeCompletion)) 329 handleUnexpectedCodeCompletionToken(); 330 return false; 331 332 case tok::l_paren: 333 // Recursively skip properly-nested parens. 334 ConsumeParen(); 335 if (HasFlagsSet(Flags, StopAtCodeCompletion)) 336 SkipUntil(tok::r_paren, StopAtCodeCompletion); 337 else 338 SkipUntil(tok::r_paren); 339 break; 340 case tok::l_square: 341 // Recursively skip properly-nested square brackets. 342 ConsumeBracket(); 343 if (HasFlagsSet(Flags, StopAtCodeCompletion)) 344 SkipUntil(tok::r_square, StopAtCodeCompletion); 345 else 346 SkipUntil(tok::r_square); 347 break; 348 case tok::l_brace: 349 // Recursively skip properly-nested braces. 350 ConsumeBrace(); 351 if (HasFlagsSet(Flags, StopAtCodeCompletion)) 352 SkipUntil(tok::r_brace, StopAtCodeCompletion); 353 else 354 SkipUntil(tok::r_brace); 355 break; 356 case tok::question: 357 // Recursively skip ? ... : pairs; these function as brackets. But 358 // still stop at a semicolon if requested. 359 ConsumeToken(); 360 SkipUntil(tok::colon, 361 SkipUntilFlags(unsigned(Flags) & 362 unsigned(StopAtCodeCompletion | StopAtSemi))); 363 break; 364 365 // Okay, we found a ']' or '}' or ')', which we think should be balanced. 366 // Since the user wasn't looking for this token (if they were, it would 367 // already be handled), this isn't balanced. If there is a LHS token at a 368 // higher level, we will assume that this matches the unbalanced token 369 // and return it. Otherwise, this is a spurious RHS token, which we skip. 370 case tok::r_paren: 371 if (ParenCount && !isFirstTokenSkipped) 372 return false; // Matches something. 373 ConsumeParen(); 374 break; 375 case tok::r_square: 376 if (BracketCount && !isFirstTokenSkipped) 377 return false; // Matches something. 378 ConsumeBracket(); 379 break; 380 case tok::r_brace: 381 if (BraceCount && !isFirstTokenSkipped) 382 return false; // Matches something. 383 ConsumeBrace(); 384 break; 385 386 case tok::semi: 387 if (HasFlagsSet(Flags, StopAtSemi)) 388 return false; 389 LLVM_FALLTHROUGH; 390 default: 391 // Skip this token. 392 ConsumeAnyToken(); 393 break; 394 } 395 isFirstTokenSkipped = false; 396 } 397 } 398 399 //===----------------------------------------------------------------------===// 400 // Scope manipulation 401 //===----------------------------------------------------------------------===// 402 403 /// EnterScope - Start a new scope. 404 void Parser::EnterScope(unsigned ScopeFlags) { 405 if (NumCachedScopes) { 406 Scope *N = ScopeCache[--NumCachedScopes]; 407 N->Init(getCurScope(), ScopeFlags); 408 Actions.CurScope = N; 409 } else { 410 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags); 411 } 412 } 413 414 /// ExitScope - Pop a scope off the scope stack. 415 void Parser::ExitScope() { 416 assert(getCurScope() && "Scope imbalance!"); 417 418 // Inform the actions module that this scope is going away if there are any 419 // decls in it. 420 Actions.ActOnPopScope(Tok.getLocation(), getCurScope()); 421 422 Scope *OldScope = getCurScope(); 423 Actions.CurScope = OldScope->getParent(); 424 425 if (NumCachedScopes == ScopeCacheSize) 426 delete OldScope; 427 else 428 ScopeCache[NumCachedScopes++] = OldScope; 429 } 430 431 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false, 432 /// this object does nothing. 433 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags, 434 bool ManageFlags) 435 : CurScope(ManageFlags ? Self->getCurScope() : nullptr) { 436 if (CurScope) { 437 OldFlags = CurScope->getFlags(); 438 CurScope->setFlags(ScopeFlags); 439 } 440 } 441 442 /// Restore the flags for the current scope to what they were before this 443 /// object overrode them. 444 Parser::ParseScopeFlags::~ParseScopeFlags() { 445 if (CurScope) 446 CurScope->setFlags(OldFlags); 447 } 448 449 450 //===----------------------------------------------------------------------===// 451 // C99 6.9: External Definitions. 452 //===----------------------------------------------------------------------===// 453 454 Parser::~Parser() { 455 // If we still have scopes active, delete the scope tree. 456 delete getCurScope(); 457 Actions.CurScope = nullptr; 458 459 // Free the scope cache. 460 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i) 461 delete ScopeCache[i]; 462 463 resetPragmaHandlers(); 464 465 PP.removeCommentHandler(CommentSemaHandler.get()); 466 467 PP.clearCodeCompletionHandler(); 468 469 DestroyTemplateIds(); 470 } 471 472 /// Initialize - Warm up the parser. 473 /// 474 void Parser::Initialize() { 475 // Create the translation unit scope. Install it as the current scope. 476 assert(getCurScope() == nullptr && "A scope is already active?"); 477 EnterScope(Scope::DeclScope); 478 Actions.ActOnTranslationUnitScope(getCurScope()); 479 480 // Initialization for Objective-C context sensitive keywords recognition. 481 // Referenced in Parser::ParseObjCTypeQualifierList. 482 if (getLangOpts().ObjC) { 483 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in"); 484 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out"); 485 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout"); 486 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway"); 487 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy"); 488 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref"); 489 ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull"); 490 ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable"); 491 ObjCTypeQuals[objc_null_unspecified] 492 = &PP.getIdentifierTable().get("null_unspecified"); 493 } 494 495 Ident_instancetype = nullptr; 496 Ident_final = nullptr; 497 Ident_sealed = nullptr; 498 Ident_abstract = nullptr; 499 Ident_override = nullptr; 500 Ident_GNU_final = nullptr; 501 Ident_import = nullptr; 502 Ident_module = nullptr; 503 504 Ident_super = &PP.getIdentifierTable().get("super"); 505 506 Ident_vector = nullptr; 507 Ident_bool = nullptr; 508 Ident_Bool = nullptr; 509 Ident_pixel = nullptr; 510 if (getLangOpts().AltiVec || getLangOpts().ZVector) { 511 Ident_vector = &PP.getIdentifierTable().get("vector"); 512 Ident_bool = &PP.getIdentifierTable().get("bool"); 513 Ident_Bool = &PP.getIdentifierTable().get("_Bool"); 514 } 515 if (getLangOpts().AltiVec) 516 Ident_pixel = &PP.getIdentifierTable().get("pixel"); 517 518 Ident_introduced = nullptr; 519 Ident_deprecated = nullptr; 520 Ident_obsoleted = nullptr; 521 Ident_unavailable = nullptr; 522 Ident_strict = nullptr; 523 Ident_replacement = nullptr; 524 525 Ident_language = Ident_defined_in = Ident_generated_declaration = nullptr; 526 527 Ident__except = nullptr; 528 529 Ident__exception_code = Ident__exception_info = nullptr; 530 Ident__abnormal_termination = Ident___exception_code = nullptr; 531 Ident___exception_info = Ident___abnormal_termination = nullptr; 532 Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr; 533 Ident_AbnormalTermination = nullptr; 534 535 if(getLangOpts().Borland) { 536 Ident__exception_info = PP.getIdentifierInfo("_exception_info"); 537 Ident___exception_info = PP.getIdentifierInfo("__exception_info"); 538 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation"); 539 Ident__exception_code = PP.getIdentifierInfo("_exception_code"); 540 Ident___exception_code = PP.getIdentifierInfo("__exception_code"); 541 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode"); 542 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination"); 543 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination"); 544 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination"); 545 546 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block); 547 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block); 548 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block); 549 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter); 550 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter); 551 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter); 552 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block); 553 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block); 554 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block); 555 } 556 557 if (getLangOpts().CPlusPlusModules) { 558 Ident_import = PP.getIdentifierInfo("import"); 559 Ident_module = PP.getIdentifierInfo("module"); 560 } 561 562 Actions.Initialize(); 563 564 // Prime the lexer look-ahead. 565 ConsumeToken(); 566 } 567 568 void Parser::DestroyTemplateIds() { 569 for (TemplateIdAnnotation *Id : TemplateIds) 570 Id->Destroy(); 571 TemplateIds.clear(); 572 } 573 574 /// Parse the first top-level declaration in a translation unit. 575 /// 576 /// translation-unit: 577 /// [C] external-declaration 578 /// [C] translation-unit external-declaration 579 /// [C++] top-level-declaration-seq[opt] 580 /// [C++20] global-module-fragment[opt] module-declaration 581 /// top-level-declaration-seq[opt] private-module-fragment[opt] 582 /// 583 /// Note that in C, it is an error if there is no first declaration. 584 bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, 585 Sema::ModuleImportState &ImportState) { 586 Actions.ActOnStartOfTranslationUnit(); 587 588 // For C++20 modules, a module decl must be the first in the TU. We also 589 // need to track module imports. 590 ImportState = Sema::ModuleImportState::FirstDecl; 591 bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState); 592 593 // C11 6.9p1 says translation units must have at least one top-level 594 // declaration. C++ doesn't have this restriction. We also don't want to 595 // complain if we have a precompiled header, although technically if the PCH 596 // is empty we should still emit the (pedantic) diagnostic. 597 // If the main file is a header, we're only pretending it's a TU; don't warn. 598 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() && 599 !getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile) 600 Diag(diag::ext_empty_translation_unit); 601 602 return NoTopLevelDecls; 603 } 604 605 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the 606 /// action tells us to. This returns true if the EOF was encountered. 607 /// 608 /// top-level-declaration: 609 /// declaration 610 /// [C++20] module-import-declaration 611 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result, 612 Sema::ModuleImportState &ImportState) { 613 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this); 614 615 // Skip over the EOF token, flagging end of previous input for incremental 616 // processing 617 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof)) 618 ConsumeToken(); 619 620 Result = nullptr; 621 switch (Tok.getKind()) { 622 case tok::annot_pragma_unused: 623 HandlePragmaUnused(); 624 return false; 625 626 case tok::kw_export: 627 switch (NextToken().getKind()) { 628 case tok::kw_module: 629 goto module_decl; 630 631 // Note: no need to handle kw_import here. We only form kw_import under 632 // the Modules TS, and in that case 'export import' is parsed as an 633 // export-declaration containing an import-declaration. 634 635 // Recognize context-sensitive C++20 'export module' and 'export import' 636 // declarations. 637 case tok::identifier: { 638 IdentifierInfo *II = NextToken().getIdentifierInfo(); 639 if ((II == Ident_module || II == Ident_import) && 640 GetLookAheadToken(2).isNot(tok::coloncolon)) { 641 if (II == Ident_module) 642 goto module_decl; 643 else 644 goto import_decl; 645 } 646 break; 647 } 648 649 default: 650 break; 651 } 652 break; 653 654 case tok::kw_module: 655 module_decl: 656 Result = ParseModuleDecl(ImportState); 657 return false; 658 659 case tok::kw_import: 660 import_decl: { 661 Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState); 662 Result = Actions.ConvertDeclToDeclGroup(ImportDecl); 663 return false; 664 } 665 666 case tok::annot_module_include: 667 Actions.ActOnModuleInclude(Tok.getLocation(), 668 reinterpret_cast<Module *>( 669 Tok.getAnnotationValue())); 670 ConsumeAnnotationToken(); 671 return false; 672 673 case tok::annot_module_begin: 674 Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>( 675 Tok.getAnnotationValue())); 676 ConsumeAnnotationToken(); 677 ImportState = Sema::ModuleImportState::NotACXX20Module; 678 return false; 679 680 case tok::annot_module_end: 681 Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>( 682 Tok.getAnnotationValue())); 683 ConsumeAnnotationToken(); 684 ImportState = Sema::ModuleImportState::NotACXX20Module; 685 return false; 686 687 case tok::eof: 688 // Check whether -fmax-tokens= was reached. 689 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) { 690 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total) 691 << PP.getTokenCount() << PP.getMaxTokens(); 692 SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc(); 693 if (OverrideLoc.isValid()) { 694 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override); 695 } 696 } 697 698 // Late template parsing can begin. 699 Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this); 700 if (!PP.isIncrementalProcessingEnabled()) 701 Actions.ActOnEndOfTranslationUnit(); 702 //else don't tell Sema that we ended parsing: more input might come. 703 return true; 704 705 case tok::identifier: 706 // C++2a [basic.link]p3: 707 // A token sequence beginning with 'export[opt] module' or 708 // 'export[opt] import' and not immediately followed by '::' 709 // is never interpreted as the declaration of a top-level-declaration. 710 if ((Tok.getIdentifierInfo() == Ident_module || 711 Tok.getIdentifierInfo() == Ident_import) && 712 NextToken().isNot(tok::coloncolon)) { 713 if (Tok.getIdentifierInfo() == Ident_module) 714 goto module_decl; 715 else 716 goto import_decl; 717 } 718 break; 719 720 default: 721 break; 722 } 723 724 ParsedAttributes attrs(AttrFactory); 725 MaybeParseCXX11Attributes(attrs); 726 727 Result = ParseExternalDeclaration(attrs); 728 // An empty Result might mean a line with ';' or some parsing error, ignore 729 // it. 730 if (Result) { 731 if (ImportState == Sema::ModuleImportState::FirstDecl) 732 // First decl was not modular. 733 ImportState = Sema::ModuleImportState::NotACXX20Module; 734 else if (ImportState == Sema::ModuleImportState::ImportAllowed) 735 // Non-imports disallow further imports. 736 ImportState = Sema::ModuleImportState::ImportFinished; 737 } 738 return false; 739 } 740 741 /// ParseExternalDeclaration: 742 /// 743 /// The `Attrs` that are passed in are C++11 attributes and appertain to the 744 /// declaration. 745 /// 746 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl] 747 /// function-definition 748 /// declaration 749 /// [GNU] asm-definition 750 /// [GNU] __extension__ external-declaration 751 /// [OBJC] objc-class-definition 752 /// [OBJC] objc-class-declaration 753 /// [OBJC] objc-alias-declaration 754 /// [OBJC] objc-protocol-definition 755 /// [OBJC] objc-method-definition 756 /// [OBJC] @end 757 /// [C++] linkage-specification 758 /// [GNU] asm-definition: 759 /// simple-asm-expr ';' 760 /// [C++11] empty-declaration 761 /// [C++11] attribute-declaration 762 /// 763 /// [C++11] empty-declaration: 764 /// ';' 765 /// 766 /// [C++0x/GNU] 'extern' 'template' declaration 767 /// 768 /// [Modules-TS] module-import-declaration 769 /// 770 Parser::DeclGroupPtrTy Parser::ParseExternalDeclaration(ParsedAttributes &Attrs, 771 ParsingDeclSpec *DS) { 772 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this); 773 ParenBraceBracketBalancer BalancerRAIIObj(*this); 774 775 if (PP.isCodeCompletionReached()) { 776 cutOffParsing(); 777 return nullptr; 778 } 779 780 Decl *SingleDecl = nullptr; 781 switch (Tok.getKind()) { 782 case tok::annot_pragma_vis: 783 HandlePragmaVisibility(); 784 return nullptr; 785 case tok::annot_pragma_pack: 786 HandlePragmaPack(); 787 return nullptr; 788 case tok::annot_pragma_msstruct: 789 HandlePragmaMSStruct(); 790 return nullptr; 791 case tok::annot_pragma_align: 792 HandlePragmaAlign(); 793 return nullptr; 794 case tok::annot_pragma_weak: 795 HandlePragmaWeak(); 796 return nullptr; 797 case tok::annot_pragma_weakalias: 798 HandlePragmaWeakAlias(); 799 return nullptr; 800 case tok::annot_pragma_redefine_extname: 801 HandlePragmaRedefineExtname(); 802 return nullptr; 803 case tok::annot_pragma_fp_contract: 804 HandlePragmaFPContract(); 805 return nullptr; 806 case tok::annot_pragma_fenv_access: 807 case tok::annot_pragma_fenv_access_ms: 808 HandlePragmaFEnvAccess(); 809 return nullptr; 810 case tok::annot_pragma_fenv_round: 811 HandlePragmaFEnvRound(); 812 return nullptr; 813 case tok::annot_pragma_float_control: 814 HandlePragmaFloatControl(); 815 return nullptr; 816 case tok::annot_pragma_fp: 817 HandlePragmaFP(); 818 break; 819 case tok::annot_pragma_opencl_extension: 820 HandlePragmaOpenCLExtension(); 821 return nullptr; 822 case tok::annot_attr_openmp: 823 case tok::annot_pragma_openmp: { 824 AccessSpecifier AS = AS_none; 825 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs); 826 } 827 case tok::annot_pragma_ms_pointers_to_members: 828 HandlePragmaMSPointersToMembers(); 829 return nullptr; 830 case tok::annot_pragma_ms_vtordisp: 831 HandlePragmaMSVtorDisp(); 832 return nullptr; 833 case tok::annot_pragma_ms_pragma: 834 HandlePragmaMSPragma(); 835 return nullptr; 836 case tok::annot_pragma_dump: 837 HandlePragmaDump(); 838 return nullptr; 839 case tok::annot_pragma_attribute: 840 HandlePragmaAttribute(); 841 return nullptr; 842 case tok::semi: 843 // Either a C++11 empty-declaration or attribute-declaration. 844 SingleDecl = 845 Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation()); 846 ConsumeExtraSemi(OutsideFunction); 847 break; 848 case tok::r_brace: 849 Diag(Tok, diag::err_extraneous_closing_brace); 850 ConsumeBrace(); 851 return nullptr; 852 case tok::eof: 853 Diag(Tok, diag::err_expected_external_declaration); 854 return nullptr; 855 case tok::kw___extension__: { 856 // __extension__ silences extension warnings in the subexpression. 857 ExtensionRAIIObject O(Diags); // Use RAII to do this. 858 ConsumeToken(); 859 return ParseExternalDeclaration(Attrs); 860 } 861 case tok::kw_asm: { 862 ProhibitAttributes(Attrs); 863 864 SourceLocation StartLoc = Tok.getLocation(); 865 SourceLocation EndLoc; 866 867 ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc)); 868 869 // Check if GNU-style InlineAsm is disabled. 870 // Empty asm string is allowed because it will not introduce 871 // any assembly code. 872 if (!(getLangOpts().GNUAsm || Result.isInvalid())) { 873 const auto *SL = cast<StringLiteral>(Result.get()); 874 if (!SL->getString().trim().empty()) 875 Diag(StartLoc, diag::err_gnu_inline_asm_disabled); 876 } 877 878 ExpectAndConsume(tok::semi, diag::err_expected_after, 879 "top-level asm block"); 880 881 if (Result.isInvalid()) 882 return nullptr; 883 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc); 884 break; 885 } 886 case tok::at: 887 return ParseObjCAtDirectives(Attrs); 888 case tok::minus: 889 case tok::plus: 890 if (!getLangOpts().ObjC) { 891 Diag(Tok, diag::err_expected_external_declaration); 892 ConsumeToken(); 893 return nullptr; 894 } 895 SingleDecl = ParseObjCMethodDefinition(); 896 break; 897 case tok::code_completion: 898 cutOffParsing(); 899 if (CurParsedObjCImpl) { 900 // Code-complete Objective-C methods even without leading '-'/'+' prefix. 901 Actions.CodeCompleteObjCMethodDecl(getCurScope(), 902 /*IsInstanceMethod=*/None, 903 /*ReturnType=*/nullptr); 904 } 905 Actions.CodeCompleteOrdinaryName( 906 getCurScope(), 907 CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace); 908 return nullptr; 909 case tok::kw_import: { 910 Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module; 911 if (getLangOpts().CPlusPlusModules) { 912 llvm_unreachable("not expecting a c++20 import here"); 913 ProhibitAttributes(Attrs); 914 } 915 SingleDecl = ParseModuleImport(SourceLocation(), IS); 916 } break; 917 case tok::kw_export: 918 if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) { 919 ProhibitAttributes(Attrs); 920 SingleDecl = ParseExportDeclaration(); 921 break; 922 } 923 // This must be 'export template'. Parse it so we can diagnose our lack 924 // of support. 925 LLVM_FALLTHROUGH; 926 case tok::kw_using: 927 case tok::kw_namespace: 928 case tok::kw_typedef: 929 case tok::kw_template: 930 case tok::kw_static_assert: 931 case tok::kw__Static_assert: 932 // A function definition cannot start with any of these keywords. 933 { 934 SourceLocation DeclEnd; 935 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory); 936 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs, 937 EmptyDeclSpecAttrs); 938 } 939 940 case tok::kw_static: 941 // Parse (then ignore) 'static' prior to a template instantiation. This is 942 // a GCC extension that we intentionally do not support. 943 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) { 944 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 945 << 0; 946 SourceLocation DeclEnd; 947 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory); 948 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs, 949 EmptyDeclSpecAttrs); 950 } 951 goto dont_know; 952 953 case tok::kw_inline: 954 if (getLangOpts().CPlusPlus) { 955 tok::TokenKind NextKind = NextToken().getKind(); 956 957 // Inline namespaces. Allowed as an extension even in C++03. 958 if (NextKind == tok::kw_namespace) { 959 SourceLocation DeclEnd; 960 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory); 961 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs, 962 EmptyDeclSpecAttrs); 963 } 964 965 // Parse (then ignore) 'inline' prior to a template instantiation. This is 966 // a GCC extension that we intentionally do not support. 967 if (NextKind == tok::kw_template) { 968 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 969 << 1; 970 SourceLocation DeclEnd; 971 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory); 972 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs, 973 EmptyDeclSpecAttrs); 974 } 975 } 976 goto dont_know; 977 978 case tok::kw_extern: 979 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) { 980 // Extern templates 981 SourceLocation ExternLoc = ConsumeToken(); 982 SourceLocation TemplateLoc = ConsumeToken(); 983 Diag(ExternLoc, getLangOpts().CPlusPlus11 ? 984 diag::warn_cxx98_compat_extern_template : 985 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc); 986 SourceLocation DeclEnd; 987 return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation( 988 DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, Attrs)); 989 } 990 goto dont_know; 991 992 case tok::kw___if_exists: 993 case tok::kw___if_not_exists: 994 ParseMicrosoftIfExistsExternalDeclaration(); 995 return nullptr; 996 997 case tok::kw_module: 998 Diag(Tok, diag::err_unexpected_module_decl); 999 SkipUntil(tok::semi); 1000 return nullptr; 1001 1002 default: 1003 dont_know: 1004 if (Tok.isEditorPlaceholder()) { 1005 ConsumeToken(); 1006 return nullptr; 1007 } 1008 // We can't tell whether this is a function-definition or declaration yet. 1009 return ParseDeclarationOrFunctionDefinition(Attrs, DS); 1010 } 1011 1012 // This routine returns a DeclGroup, if the thing we parsed only contains a 1013 // single decl, convert it now. 1014 return Actions.ConvertDeclToDeclGroup(SingleDecl); 1015 } 1016 1017 /// Determine whether the current token, if it occurs after a 1018 /// declarator, continues a declaration or declaration list. 1019 bool Parser::isDeclarationAfterDeclarator() { 1020 // Check for '= delete' or '= default' 1021 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) { 1022 const Token &KW = NextToken(); 1023 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete)) 1024 return false; 1025 } 1026 1027 return Tok.is(tok::equal) || // int X()= -> not a function def 1028 Tok.is(tok::comma) || // int X(), -> not a function def 1029 Tok.is(tok::semi) || // int X(); -> not a function def 1030 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def 1031 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def 1032 (getLangOpts().CPlusPlus && 1033 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++] 1034 } 1035 1036 /// Determine whether the current token, if it occurs after a 1037 /// declarator, indicates the start of a function definition. 1038 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) { 1039 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator"); 1040 if (Tok.is(tok::l_brace)) // int X() {} 1041 return true; 1042 1043 // Handle K&R C argument lists: int X(f) int f; {} 1044 if (!getLangOpts().CPlusPlus && 1045 Declarator.getFunctionTypeInfo().isKNRPrototype()) 1046 return isDeclarationSpecifier(); 1047 1048 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) { 1049 const Token &KW = NextToken(); 1050 return KW.is(tok::kw_default) || KW.is(tok::kw_delete); 1051 } 1052 1053 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors) 1054 Tok.is(tok::kw_try); // X() try { ... } 1055 } 1056 1057 /// Parse either a function-definition or a declaration. We can't tell which 1058 /// we have until we read up to the compound-statement in function-definition. 1059 /// TemplateParams, if non-NULL, provides the template parameters when we're 1060 /// parsing a C++ template-declaration. 1061 /// 1062 /// function-definition: [C99 6.9.1] 1063 /// decl-specs declarator declaration-list[opt] compound-statement 1064 /// [C90] function-definition: [C99 6.7.1] - implicit int result 1065 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 1066 /// 1067 /// declaration: [C99 6.7] 1068 /// declaration-specifiers init-declarator-list[opt] ';' 1069 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode] 1070 /// [OMP] threadprivate-directive 1071 /// [OMP] allocate-directive [TODO] 1072 /// 1073 Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal( 1074 ParsedAttributes &Attrs, ParsingDeclSpec &DS, AccessSpecifier AS) { 1075 MaybeParseMicrosoftAttributes(DS.getAttributes()); 1076 // Parse the common declaration-specifiers piece. 1077 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, 1078 DeclSpecContext::DSC_top_level); 1079 1080 // If we had a free-standing type definition with a missing semicolon, we 1081 // may get this far before the problem becomes obvious. 1082 if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition( 1083 DS, AS, DeclSpecContext::DSC_top_level)) 1084 return nullptr; 1085 1086 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 1087 // declaration-specifiers init-declarator-list[opt] ';' 1088 if (Tok.is(tok::semi)) { 1089 auto LengthOfTSTToken = [](DeclSpec::TST TKind) { 1090 assert(DeclSpec::isDeclRep(TKind)); 1091 switch(TKind) { 1092 case DeclSpec::TST_class: 1093 return 5; 1094 case DeclSpec::TST_struct: 1095 return 6; 1096 case DeclSpec::TST_union: 1097 return 5; 1098 case DeclSpec::TST_enum: 1099 return 4; 1100 case DeclSpec::TST_interface: 1101 return 9; 1102 default: 1103 llvm_unreachable("we only expect to get the length of the class/struct/union/enum"); 1104 } 1105 1106 }; 1107 // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]' 1108 SourceLocation CorrectLocationForAttributes = 1109 DeclSpec::isDeclRep(DS.getTypeSpecType()) 1110 ? DS.getTypeSpecTypeLoc().getLocWithOffset( 1111 LengthOfTSTToken(DS.getTypeSpecType())) 1112 : SourceLocation(); 1113 ProhibitAttributes(Attrs, CorrectLocationForAttributes); 1114 ConsumeToken(); 1115 RecordDecl *AnonRecord = nullptr; 1116 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec( 1117 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord); 1118 DS.complete(TheDecl); 1119 if (AnonRecord) { 1120 Decl* decls[] = {AnonRecord, TheDecl}; 1121 return Actions.BuildDeclaratorGroup(decls); 1122 } 1123 return Actions.ConvertDeclToDeclGroup(TheDecl); 1124 } 1125 1126 // ObjC2 allows prefix attributes on class interfaces and protocols. 1127 // FIXME: This still needs better diagnostics. We should only accept 1128 // attributes here, no types, etc. 1129 if (getLangOpts().ObjC && Tok.is(tok::at)) { 1130 SourceLocation AtLoc = ConsumeToken(); // the "@" 1131 if (!Tok.isObjCAtKeyword(tok::objc_interface) && 1132 !Tok.isObjCAtKeyword(tok::objc_protocol) && 1133 !Tok.isObjCAtKeyword(tok::objc_implementation)) { 1134 Diag(Tok, diag::err_objc_unexpected_attr); 1135 SkipUntil(tok::semi); 1136 return nullptr; 1137 } 1138 1139 DS.abort(); 1140 DS.takeAttributesFrom(Attrs); 1141 1142 const char *PrevSpec = nullptr; 1143 unsigned DiagID; 1144 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID, 1145 Actions.getASTContext().getPrintingPolicy())) 1146 Diag(AtLoc, DiagID) << PrevSpec; 1147 1148 if (Tok.isObjCAtKeyword(tok::objc_protocol)) 1149 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()); 1150 1151 if (Tok.isObjCAtKeyword(tok::objc_implementation)) 1152 return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes()); 1153 1154 return Actions.ConvertDeclToDeclGroup( 1155 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes())); 1156 } 1157 1158 // If the declspec consisted only of 'extern' and we have a string 1159 // literal following it, this must be a C++ linkage specifier like 1160 // 'extern "C"'. 1161 if (getLangOpts().CPlusPlus && isTokenStringLiteral() && 1162 DS.getStorageClassSpec() == DeclSpec::SCS_extern && 1163 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) { 1164 ProhibitAttributes(Attrs); 1165 Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File); 1166 return Actions.ConvertDeclToDeclGroup(TheDecl); 1167 } 1168 1169 return ParseDeclGroup(DS, DeclaratorContext::File, Attrs); 1170 } 1171 1172 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition( 1173 ParsedAttributes &Attrs, ParsingDeclSpec *DS, AccessSpecifier AS) { 1174 if (DS) { 1175 return ParseDeclOrFunctionDefInternal(Attrs, *DS, AS); 1176 } else { 1177 ParsingDeclSpec PDS(*this); 1178 // Must temporarily exit the objective-c container scope for 1179 // parsing c constructs and re-enter objc container scope 1180 // afterwards. 1181 ObjCDeclContextSwitch ObjCDC(*this); 1182 1183 return ParseDeclOrFunctionDefInternal(Attrs, PDS, AS); 1184 } 1185 } 1186 1187 /// ParseFunctionDefinition - We parsed and verified that the specified 1188 /// Declarator is well formed. If this is a K&R-style function, read the 1189 /// parameters declaration-list, then start the compound-statement. 1190 /// 1191 /// function-definition: [C99 6.9.1] 1192 /// decl-specs declarator declaration-list[opt] compound-statement 1193 /// [C90] function-definition: [C99 6.7.1] - implicit int result 1194 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 1195 /// [C++] function-definition: [C++ 8.4] 1196 /// decl-specifier-seq[opt] declarator ctor-initializer[opt] 1197 /// function-body 1198 /// [C++] function-definition: [C++ 8.4] 1199 /// decl-specifier-seq[opt] declarator function-try-block 1200 /// 1201 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, 1202 const ParsedTemplateInfo &TemplateInfo, 1203 LateParsedAttrList *LateParsedAttrs) { 1204 // Poison SEH identifiers so they are flagged as illegal in function bodies. 1205 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 1206 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 1207 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 1208 1209 // If this is C89 and the declspecs were completely missing, fudge in an 1210 // implicit int. We do this here because this is the only place where 1211 // declaration-specifiers are completely optional in the grammar. 1212 if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) { 1213 Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier) 1214 << D.getDeclSpec().getSourceRange(); 1215 const char *PrevSpec; 1216 unsigned DiagID; 1217 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 1218 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int, 1219 D.getIdentifierLoc(), 1220 PrevSpec, DiagID, 1221 Policy); 1222 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin()); 1223 } 1224 1225 // If this declaration was formed with a K&R-style identifier list for the 1226 // arguments, parse declarations for all of the args next. 1227 // int foo(a,b) int a; float b; {} 1228 if (FTI.isKNRPrototype()) 1229 ParseKNRParamDeclarations(D); 1230 1231 // We should have either an opening brace or, in a C++ constructor, 1232 // we may have a colon. 1233 if (Tok.isNot(tok::l_brace) && 1234 (!getLangOpts().CPlusPlus || 1235 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && 1236 Tok.isNot(tok::equal)))) { 1237 Diag(Tok, diag::err_expected_fn_body); 1238 1239 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1240 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 1241 1242 // If we didn't find the '{', bail out. 1243 if (Tok.isNot(tok::l_brace)) 1244 return nullptr; 1245 } 1246 1247 // Check to make sure that any normal attributes are allowed to be on 1248 // a definition. Late parsed attributes are checked at the end. 1249 if (Tok.isNot(tok::equal)) { 1250 for (const ParsedAttr &AL : D.getAttributes()) 1251 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax()) 1252 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL; 1253 } 1254 1255 // In delayed template parsing mode, for function template we consume the 1256 // tokens and store them for late parsing at the end of the translation unit. 1257 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) && 1258 TemplateInfo.Kind == ParsedTemplateInfo::Template && 1259 Actions.canDelayFunctionBody(D)) { 1260 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams); 1261 1262 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1263 Scope::CompoundStmtScope); 1264 Scope *ParentScope = getCurScope()->getParent(); 1265 1266 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 1267 Decl *DP = Actions.HandleDeclarator(ParentScope, D, 1268 TemplateParameterLists); 1269 D.complete(DP); 1270 D.getMutableDeclSpec().abort(); 1271 1272 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) && 1273 trySkippingFunctionBody()) { 1274 BodyScope.Exit(); 1275 return Actions.ActOnSkippedFunctionBody(DP); 1276 } 1277 1278 CachedTokens Toks; 1279 LexTemplateFunctionForLateParsing(Toks); 1280 1281 if (DP) { 1282 FunctionDecl *FnD = DP->getAsFunction(); 1283 Actions.CheckForFunctionRedefinition(FnD); 1284 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks); 1285 } 1286 return DP; 1287 } 1288 else if (CurParsedObjCImpl && 1289 !TemplateInfo.TemplateParams && 1290 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || 1291 Tok.is(tok::colon)) && 1292 Actions.CurContext->isTranslationUnit()) { 1293 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1294 Scope::CompoundStmtScope); 1295 Scope *ParentScope = getCurScope()->getParent(); 1296 1297 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 1298 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D, 1299 MultiTemplateParamsArg()); 1300 D.complete(FuncDecl); 1301 D.getMutableDeclSpec().abort(); 1302 if (FuncDecl) { 1303 // Consume the tokens and store them for later parsing. 1304 StashAwayMethodOrFunctionBodyTokens(FuncDecl); 1305 CurParsedObjCImpl->HasCFunction = true; 1306 return FuncDecl; 1307 } 1308 // FIXME: Should we really fall through here? 1309 } 1310 1311 // Enter a scope for the function body. 1312 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1313 Scope::CompoundStmtScope); 1314 1315 // Parse function body eagerly if it is either '= delete;' or '= default;' as 1316 // ActOnStartOfFunctionDef needs to know whether the function is deleted. 1317 Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other; 1318 SourceLocation KWLoc; 1319 if (TryConsumeToken(tok::equal)) { 1320 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='"); 1321 1322 if (TryConsumeToken(tok::kw_delete, KWLoc)) { 1323 Diag(KWLoc, getLangOpts().CPlusPlus11 1324 ? diag::warn_cxx98_compat_defaulted_deleted_function 1325 : diag::ext_defaulted_deleted_function) 1326 << 1 /* deleted */; 1327 BodyKind = Sema::FnBodyKind::Delete; 1328 } else if (TryConsumeToken(tok::kw_default, KWLoc)) { 1329 Diag(KWLoc, getLangOpts().CPlusPlus11 1330 ? diag::warn_cxx98_compat_defaulted_deleted_function 1331 : diag::ext_defaulted_deleted_function) 1332 << 0 /* defaulted */; 1333 BodyKind = Sema::FnBodyKind::Default; 1334 } else { 1335 llvm_unreachable("function definition after = not 'delete' or 'default'"); 1336 } 1337 1338 if (Tok.is(tok::comma)) { 1339 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) 1340 << (BodyKind == Sema::FnBodyKind::Delete); 1341 SkipUntil(tok::semi); 1342 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after, 1343 BodyKind == Sema::FnBodyKind::Delete 1344 ? "delete" 1345 : "default")) { 1346 SkipUntil(tok::semi); 1347 } 1348 } 1349 1350 // Tell the actions module that we have entered a function definition with the 1351 // specified Declarator for the function. 1352 Sema::SkipBodyInfo SkipBody; 1353 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D, 1354 TemplateInfo.TemplateParams 1355 ? *TemplateInfo.TemplateParams 1356 : MultiTemplateParamsArg(), 1357 &SkipBody, BodyKind); 1358 1359 if (SkipBody.ShouldSkip) { 1360 // Do NOT enter SkipFunctionBody if we already consumed the tokens. 1361 if (BodyKind == Sema::FnBodyKind::Other) 1362 SkipFunctionBody(); 1363 1364 return Res; 1365 } 1366 1367 // Break out of the ParsingDeclarator context before we parse the body. 1368 D.complete(Res); 1369 1370 // Break out of the ParsingDeclSpec context, too. This const_cast is 1371 // safe because we're always the sole owner. 1372 D.getMutableDeclSpec().abort(); 1373 1374 if (BodyKind != Sema::FnBodyKind::Other) { 1375 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind); 1376 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr; 1377 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false); 1378 return Res; 1379 } 1380 1381 // With abbreviated function templates - we need to explicitly add depth to 1382 // account for the implicit template parameter list induced by the template. 1383 if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res)) 1384 if (Template->isAbbreviated() && 1385 Template->getTemplateParameters()->getParam(0)->isImplicit()) 1386 // First template parameter is implicit - meaning no explicit template 1387 // parameter list was specified. 1388 CurTemplateDepthTracker.addDepth(1); 1389 1390 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) && 1391 trySkippingFunctionBody()) { 1392 BodyScope.Exit(); 1393 Actions.ActOnSkippedFunctionBody(Res); 1394 return Actions.ActOnFinishFunctionBody(Res, nullptr, false); 1395 } 1396 1397 if (Tok.is(tok::kw_try)) 1398 return ParseFunctionTryBlock(Res, BodyScope); 1399 1400 // If we have a colon, then we're probably parsing a C++ 1401 // ctor-initializer. 1402 if (Tok.is(tok::colon)) { 1403 ParseConstructorInitializer(Res); 1404 1405 // Recover from error. 1406 if (!Tok.is(tok::l_brace)) { 1407 BodyScope.Exit(); 1408 Actions.ActOnFinishFunctionBody(Res, nullptr); 1409 return Res; 1410 } 1411 } else 1412 Actions.ActOnDefaultCtorInitializers(Res); 1413 1414 // Late attributes are parsed in the same scope as the function body. 1415 if (LateParsedAttrs) 1416 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true); 1417 1418 return ParseFunctionStatementBody(Res, BodyScope); 1419 } 1420 1421 void Parser::SkipFunctionBody() { 1422 if (Tok.is(tok::equal)) { 1423 SkipUntil(tok::semi); 1424 return; 1425 } 1426 1427 bool IsFunctionTryBlock = Tok.is(tok::kw_try); 1428 if (IsFunctionTryBlock) 1429 ConsumeToken(); 1430 1431 CachedTokens Skipped; 1432 if (ConsumeAndStoreFunctionPrologue(Skipped)) 1433 SkipMalformedDecl(); 1434 else { 1435 SkipUntil(tok::r_brace); 1436 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) { 1437 SkipUntil(tok::l_brace); 1438 SkipUntil(tok::r_brace); 1439 } 1440 } 1441 } 1442 1443 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides 1444 /// types for a function with a K&R-style identifier list for arguments. 1445 void Parser::ParseKNRParamDeclarations(Declarator &D) { 1446 // We know that the top-level of this declarator is a function. 1447 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 1448 1449 // Enter function-declaration scope, limiting any declarators to the 1450 // function prototype scope, including parameter declarators. 1451 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | 1452 Scope::FunctionDeclarationScope | Scope::DeclScope); 1453 1454 // Read all the argument declarations. 1455 while (isDeclarationSpecifier()) { 1456 SourceLocation DSStart = Tok.getLocation(); 1457 1458 // Parse the common declaration-specifiers piece. 1459 DeclSpec DS(AttrFactory); 1460 ParseDeclarationSpecifiers(DS); 1461 1462 // C99 6.9.1p6: 'each declaration in the declaration list shall have at 1463 // least one declarator'. 1464 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with 1465 // the declarations though. It's trivial to ignore them, really hard to do 1466 // anything else with them. 1467 if (TryConsumeToken(tok::semi)) { 1468 Diag(DSStart, diag::err_declaration_does_not_declare_param); 1469 continue; 1470 } 1471 1472 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other 1473 // than register. 1474 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1475 DS.getStorageClassSpec() != DeclSpec::SCS_register) { 1476 Diag(DS.getStorageClassSpecLoc(), 1477 diag::err_invalid_storage_class_in_func_decl); 1478 DS.ClearStorageClassSpecs(); 1479 } 1480 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) { 1481 Diag(DS.getThreadStorageClassSpecLoc(), 1482 diag::err_invalid_storage_class_in_func_decl); 1483 DS.ClearStorageClassSpecs(); 1484 } 1485 1486 // Parse the first declarator attached to this declspec. 1487 Declarator ParmDeclarator(DS, ParsedAttributesView::none(), 1488 DeclaratorContext::KNRTypeList); 1489 ParseDeclarator(ParmDeclarator); 1490 1491 // Handle the full declarator list. 1492 while (true) { 1493 // If attributes are present, parse them. 1494 MaybeParseGNUAttributes(ParmDeclarator); 1495 1496 // Ask the actions module to compute the type for this declarator. 1497 Decl *Param = 1498 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 1499 1500 if (Param && 1501 // A missing identifier has already been diagnosed. 1502 ParmDeclarator.getIdentifier()) { 1503 1504 // Scan the argument list looking for the correct param to apply this 1505 // type. 1506 for (unsigned i = 0; ; ++i) { 1507 // C99 6.9.1p6: those declarators shall declare only identifiers from 1508 // the identifier list. 1509 if (i == FTI.NumParams) { 1510 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param) 1511 << ParmDeclarator.getIdentifier(); 1512 break; 1513 } 1514 1515 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) { 1516 // Reject redefinitions of parameters. 1517 if (FTI.Params[i].Param) { 1518 Diag(ParmDeclarator.getIdentifierLoc(), 1519 diag::err_param_redefinition) 1520 << ParmDeclarator.getIdentifier(); 1521 } else { 1522 FTI.Params[i].Param = Param; 1523 } 1524 break; 1525 } 1526 } 1527 } 1528 1529 // If we don't have a comma, it is either the end of the list (a ';') or 1530 // an error, bail out. 1531 if (Tok.isNot(tok::comma)) 1532 break; 1533 1534 ParmDeclarator.clear(); 1535 1536 // Consume the comma. 1537 ParmDeclarator.setCommaLoc(ConsumeToken()); 1538 1539 // Parse the next declarator. 1540 ParseDeclarator(ParmDeclarator); 1541 } 1542 1543 // Consume ';' and continue parsing. 1544 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) 1545 continue; 1546 1547 // Otherwise recover by skipping to next semi or mandatory function body. 1548 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch)) 1549 break; 1550 TryConsumeToken(tok::semi); 1551 } 1552 1553 // The actions module must verify that all arguments were declared. 1554 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation()); 1555 } 1556 1557 1558 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not 1559 /// allowed to be a wide string, and is not subject to character translation. 1560 /// Unlike GCC, we also diagnose an empty string literal when parsing for an 1561 /// asm label as opposed to an asm statement, because such a construct does not 1562 /// behave well. 1563 /// 1564 /// [GNU] asm-string-literal: 1565 /// string-literal 1566 /// 1567 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) { 1568 if (!isTokenStringLiteral()) { 1569 Diag(Tok, diag::err_expected_string_literal) 1570 << /*Source='in...'*/0 << "'asm'"; 1571 return ExprError(); 1572 } 1573 1574 ExprResult AsmString(ParseStringLiteralExpression()); 1575 if (!AsmString.isInvalid()) { 1576 const auto *SL = cast<StringLiteral>(AsmString.get()); 1577 if (!SL->isOrdinary()) { 1578 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1579 << SL->isWide() 1580 << SL->getSourceRange(); 1581 return ExprError(); 1582 } 1583 if (ForAsmLabel && SL->getString().empty()) { 1584 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1585 << 2 /* an empty */ << SL->getSourceRange(); 1586 return ExprError(); 1587 } 1588 } 1589 return AsmString; 1590 } 1591 1592 /// ParseSimpleAsm 1593 /// 1594 /// [GNU] simple-asm-expr: 1595 /// 'asm' '(' asm-string-literal ')' 1596 /// 1597 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) { 1598 assert(Tok.is(tok::kw_asm) && "Not an asm!"); 1599 SourceLocation Loc = ConsumeToken(); 1600 1601 if (isGNUAsmQualifier(Tok)) { 1602 // Remove from the end of 'asm' to the end of the asm qualifier. 1603 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc), 1604 PP.getLocForEndOfToken(Tok.getLocation())); 1605 Diag(Tok, diag::err_global_asm_qualifier_ignored) 1606 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok)) 1607 << FixItHint::CreateRemoval(RemovalRange); 1608 ConsumeToken(); 1609 } 1610 1611 BalancedDelimiterTracker T(*this, tok::l_paren); 1612 if (T.consumeOpen()) { 1613 Diag(Tok, diag::err_expected_lparen_after) << "asm"; 1614 return ExprError(); 1615 } 1616 1617 ExprResult Result(ParseAsmStringLiteral(ForAsmLabel)); 1618 1619 if (!Result.isInvalid()) { 1620 // Close the paren and get the location of the end bracket 1621 T.consumeClose(); 1622 if (EndLoc) 1623 *EndLoc = T.getCloseLocation(); 1624 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) { 1625 if (EndLoc) 1626 *EndLoc = Tok.getLocation(); 1627 ConsumeParen(); 1628 } 1629 1630 return Result; 1631 } 1632 1633 /// Get the TemplateIdAnnotation from the token and put it in the 1634 /// cleanup pool so that it gets destroyed when parsing the current top level 1635 /// declaration is finished. 1636 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) { 1637 assert(tok.is(tok::annot_template_id) && "Expected template-id token"); 1638 TemplateIdAnnotation * 1639 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue()); 1640 return Id; 1641 } 1642 1643 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) { 1644 // Push the current token back into the token stream (or revert it if it is 1645 // cached) and use an annotation scope token for current token. 1646 if (PP.isBacktrackEnabled()) 1647 PP.RevertCachedTokens(1); 1648 else 1649 PP.EnterToken(Tok, /*IsReinject=*/true); 1650 Tok.setKind(tok::annot_cxxscope); 1651 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1652 Tok.setAnnotationRange(SS.getRange()); 1653 1654 // In case the tokens were cached, have Preprocessor replace them 1655 // with the annotation token. We don't need to do this if we've 1656 // just reverted back to a prior state. 1657 if (IsNewAnnotation) 1658 PP.AnnotateCachedTokens(Tok); 1659 } 1660 1661 /// Attempt to classify the name at the current token position. This may 1662 /// form a type, scope or primary expression annotation, or replace the token 1663 /// with a typo-corrected keyword. This is only appropriate when the current 1664 /// name must refer to an entity which has already been declared. 1665 /// 1666 /// \param CCC Indicates how to perform typo-correction for this name. If NULL, 1667 /// no typo correction will be performed. 1668 Parser::AnnotatedNameKind 1669 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC) { 1670 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope)); 1671 1672 const bool EnteringContext = false; 1673 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1674 1675 CXXScopeSpec SS; 1676 if (getLangOpts().CPlusPlus && 1677 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1678 /*ObjectHasErrors=*/false, 1679 EnteringContext)) 1680 return ANK_Error; 1681 1682 if (Tok.isNot(tok::identifier) || SS.isInvalid()) { 1683 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation)) 1684 return ANK_Error; 1685 return ANK_Unresolved; 1686 } 1687 1688 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1689 SourceLocation NameLoc = Tok.getLocation(); 1690 1691 // FIXME: Move the tentative declaration logic into ClassifyName so we can 1692 // typo-correct to tentatively-declared identifiers. 1693 if (isTentativelyDeclared(Name)) { 1694 // Identifier has been tentatively declared, and thus cannot be resolved as 1695 // an expression. Fall back to annotating it as a type. 1696 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation)) 1697 return ANK_Error; 1698 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl; 1699 } 1700 1701 Token Next = NextToken(); 1702 1703 // Look up and classify the identifier. We don't perform any typo-correction 1704 // after a scope specifier, because in general we can't recover from typos 1705 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to 1706 // jump back into scope specifier parsing). 1707 Sema::NameClassification Classification = Actions.ClassifyName( 1708 getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr); 1709 1710 // If name lookup found nothing and we guessed that this was a template name, 1711 // double-check before committing to that interpretation. C++20 requires that 1712 // we interpret this as a template-id if it can be, but if it can't be, then 1713 // this is an error recovery case. 1714 if (Classification.getKind() == Sema::NC_UndeclaredTemplate && 1715 isTemplateArgumentList(1) == TPResult::False) { 1716 // It's not a template-id; re-classify without the '<' as a hint. 1717 Token FakeNext = Next; 1718 FakeNext.setKind(tok::unknown); 1719 Classification = 1720 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext, 1721 SS.isEmpty() ? CCC : nullptr); 1722 } 1723 1724 switch (Classification.getKind()) { 1725 case Sema::NC_Error: 1726 return ANK_Error; 1727 1728 case Sema::NC_Keyword: 1729 // The identifier was typo-corrected to a keyword. 1730 Tok.setIdentifierInfo(Name); 1731 Tok.setKind(Name->getTokenID()); 1732 PP.TypoCorrectToken(Tok); 1733 if (SS.isNotEmpty()) 1734 AnnotateScopeToken(SS, !WasScopeAnnotation); 1735 // We've "annotated" this as a keyword. 1736 return ANK_Success; 1737 1738 case Sema::NC_Unknown: 1739 // It's not something we know about. Leave it unannotated. 1740 break; 1741 1742 case Sema::NC_Type: { 1743 if (TryAltiVecVectorToken()) 1744 // vector has been found as a type id when altivec is enabled but 1745 // this is followed by a declaration specifier so this is really the 1746 // altivec vector token. Leave it unannotated. 1747 break; 1748 SourceLocation BeginLoc = NameLoc; 1749 if (SS.isNotEmpty()) 1750 BeginLoc = SS.getBeginLoc(); 1751 1752 /// An Objective-C object type followed by '<' is a specialization of 1753 /// a parameterized class type or a protocol-qualified type. 1754 ParsedType Ty = Classification.getType(); 1755 if (getLangOpts().ObjC && NextToken().is(tok::less) && 1756 (Ty.get()->isObjCObjectType() || 1757 Ty.get()->isObjCObjectPointerType())) { 1758 // Consume the name. 1759 SourceLocation IdentifierLoc = ConsumeToken(); 1760 SourceLocation NewEndLoc; 1761 TypeResult NewType 1762 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, 1763 /*consumeLastToken=*/false, 1764 NewEndLoc); 1765 if (NewType.isUsable()) 1766 Ty = NewType.get(); 1767 else if (Tok.is(tok::eof)) // Nothing to do here, bail out... 1768 return ANK_Error; 1769 } 1770 1771 Tok.setKind(tok::annot_typename); 1772 setTypeAnnotation(Tok, Ty); 1773 Tok.setAnnotationEndLoc(Tok.getLocation()); 1774 Tok.setLocation(BeginLoc); 1775 PP.AnnotateCachedTokens(Tok); 1776 return ANK_Success; 1777 } 1778 1779 case Sema::NC_OverloadSet: 1780 Tok.setKind(tok::annot_overload_set); 1781 setExprAnnotation(Tok, Classification.getExpression()); 1782 Tok.setAnnotationEndLoc(NameLoc); 1783 if (SS.isNotEmpty()) 1784 Tok.setLocation(SS.getBeginLoc()); 1785 PP.AnnotateCachedTokens(Tok); 1786 return ANK_Success; 1787 1788 case Sema::NC_NonType: 1789 if (TryAltiVecVectorToken()) 1790 // vector has been found as a non-type id when altivec is enabled but 1791 // this is followed by a declaration specifier so this is really the 1792 // altivec vector token. Leave it unannotated. 1793 break; 1794 Tok.setKind(tok::annot_non_type); 1795 setNonTypeAnnotation(Tok, Classification.getNonTypeDecl()); 1796 Tok.setLocation(NameLoc); 1797 Tok.setAnnotationEndLoc(NameLoc); 1798 PP.AnnotateCachedTokens(Tok); 1799 if (SS.isNotEmpty()) 1800 AnnotateScopeToken(SS, !WasScopeAnnotation); 1801 return ANK_Success; 1802 1803 case Sema::NC_UndeclaredNonType: 1804 case Sema::NC_DependentNonType: 1805 Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType 1806 ? tok::annot_non_type_undeclared 1807 : tok::annot_non_type_dependent); 1808 setIdentifierAnnotation(Tok, Name); 1809 Tok.setLocation(NameLoc); 1810 Tok.setAnnotationEndLoc(NameLoc); 1811 PP.AnnotateCachedTokens(Tok); 1812 if (SS.isNotEmpty()) 1813 AnnotateScopeToken(SS, !WasScopeAnnotation); 1814 return ANK_Success; 1815 1816 case Sema::NC_TypeTemplate: 1817 if (Next.isNot(tok::less)) { 1818 // This may be a type template being used as a template template argument. 1819 if (SS.isNotEmpty()) 1820 AnnotateScopeToken(SS, !WasScopeAnnotation); 1821 return ANK_TemplateName; 1822 } 1823 LLVM_FALLTHROUGH; 1824 case Sema::NC_VarTemplate: 1825 case Sema::NC_FunctionTemplate: 1826 case Sema::NC_UndeclaredTemplate: { 1827 // We have a type, variable or function template followed by '<'. 1828 ConsumeToken(); 1829 UnqualifiedId Id; 1830 Id.setIdentifier(Name, NameLoc); 1831 if (AnnotateTemplateIdToken( 1832 TemplateTy::make(Classification.getTemplateName()), 1833 Classification.getTemplateNameKind(), SS, SourceLocation(), Id)) 1834 return ANK_Error; 1835 return ANK_Success; 1836 } 1837 case Sema::NC_Concept: { 1838 UnqualifiedId Id; 1839 Id.setIdentifier(Name, NameLoc); 1840 if (Next.is(tok::less)) 1841 // We have a concept name followed by '<'. Consume the identifier token so 1842 // we reach the '<' and annotate it. 1843 ConsumeToken(); 1844 if (AnnotateTemplateIdToken( 1845 TemplateTy::make(Classification.getTemplateName()), 1846 Classification.getTemplateNameKind(), SS, SourceLocation(), Id, 1847 /*AllowTypeAnnotation=*/false, /*TypeConstraint=*/true)) 1848 return ANK_Error; 1849 return ANK_Success; 1850 } 1851 } 1852 1853 // Unable to classify the name, but maybe we can annotate a scope specifier. 1854 if (SS.isNotEmpty()) 1855 AnnotateScopeToken(SS, !WasScopeAnnotation); 1856 return ANK_Unresolved; 1857 } 1858 1859 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) { 1860 assert(Tok.isNot(tok::identifier)); 1861 Diag(Tok, diag::ext_keyword_as_ident) 1862 << PP.getSpelling(Tok) 1863 << DisableKeyword; 1864 if (DisableKeyword) 1865 Tok.getIdentifierInfo()->revertTokenIDToIdentifier(); 1866 Tok.setKind(tok::identifier); 1867 return true; 1868 } 1869 1870 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 1871 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 1872 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 1873 /// with a single annotation token representing the typename or C++ scope 1874 /// respectively. 1875 /// This simplifies handling of C++ scope specifiers and allows efficient 1876 /// backtracking without the need to re-parse and resolve nested-names and 1877 /// typenames. 1878 /// It will mainly be called when we expect to treat identifiers as typenames 1879 /// (if they are typenames). For example, in C we do not expect identifiers 1880 /// inside expressions to be treated as typenames so it will not be called 1881 /// for expressions in C. 1882 /// The benefit for C/ObjC is that a typename will be annotated and 1883 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName 1884 /// will not be called twice, once to check whether we have a declaration 1885 /// specifier, and another one to get the actual type inside 1886 /// ParseDeclarationSpecifiers). 1887 /// 1888 /// This returns true if an error occurred. 1889 /// 1890 /// Note that this routine emits an error if you call it with ::new or ::delete 1891 /// as the current tokens, so only call it in contexts where these are invalid. 1892 bool Parser::TryAnnotateTypeOrScopeToken() { 1893 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 1894 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) || 1895 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) || 1896 Tok.is(tok::kw___super)) && 1897 "Cannot be a type or scope token!"); 1898 1899 if (Tok.is(tok::kw_typename)) { 1900 // MSVC lets you do stuff like: 1901 // typename typedef T_::D D; 1902 // 1903 // We will consume the typedef token here and put it back after we have 1904 // parsed the first identifier, transforming it into something more like: 1905 // typename T_::D typedef D; 1906 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) { 1907 Token TypedefToken; 1908 PP.Lex(TypedefToken); 1909 bool Result = TryAnnotateTypeOrScopeToken(); 1910 PP.EnterToken(Tok, /*IsReinject=*/true); 1911 Tok = TypedefToken; 1912 if (!Result) 1913 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename); 1914 return Result; 1915 } 1916 1917 // Parse a C++ typename-specifier, e.g., "typename T::type". 1918 // 1919 // typename-specifier: 1920 // 'typename' '::' [opt] nested-name-specifier identifier 1921 // 'typename' '::' [opt] nested-name-specifier template [opt] 1922 // simple-template-id 1923 SourceLocation TypenameLoc = ConsumeToken(); 1924 CXXScopeSpec SS; 1925 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1926 /*ObjectHasErrors=*/false, 1927 /*EnteringContext=*/false, nullptr, 1928 /*IsTypename*/ true)) 1929 return true; 1930 if (SS.isEmpty()) { 1931 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) || 1932 Tok.is(tok::annot_decltype)) { 1933 // Attempt to recover by skipping the invalid 'typename' 1934 if (Tok.is(tok::annot_decltype) || 1935 (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) { 1936 unsigned DiagID = diag::err_expected_qualified_after_typename; 1937 // MS compatibility: MSVC permits using known types with typename. 1938 // e.g. "typedef typename T* pointer_type" 1939 if (getLangOpts().MicrosoftExt) 1940 DiagID = diag::warn_expected_qualified_after_typename; 1941 Diag(Tok.getLocation(), DiagID); 1942 return false; 1943 } 1944 } 1945 if (Tok.isEditorPlaceholder()) 1946 return true; 1947 1948 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); 1949 return true; 1950 } 1951 1952 TypeResult Ty; 1953 if (Tok.is(tok::identifier)) { 1954 // FIXME: check whether the next token is '<', first! 1955 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1956 *Tok.getIdentifierInfo(), 1957 Tok.getLocation()); 1958 } else if (Tok.is(tok::annot_template_id)) { 1959 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1960 if (!TemplateId->mightBeType()) { 1961 Diag(Tok, diag::err_typename_refers_to_non_type_template) 1962 << Tok.getAnnotationRange(); 1963 return true; 1964 } 1965 1966 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1967 TemplateId->NumArgs); 1968 1969 Ty = TemplateId->isInvalid() 1970 ? TypeError() 1971 : Actions.ActOnTypenameType( 1972 getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc, 1973 TemplateId->Template, TemplateId->Name, 1974 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, 1975 TemplateArgsPtr, TemplateId->RAngleLoc); 1976 } else { 1977 Diag(Tok, diag::err_expected_type_name_after_typename) 1978 << SS.getRange(); 1979 return true; 1980 } 1981 1982 SourceLocation EndLoc = Tok.getLastLoc(); 1983 Tok.setKind(tok::annot_typename); 1984 setTypeAnnotation(Tok, Ty); 1985 Tok.setAnnotationEndLoc(EndLoc); 1986 Tok.setLocation(TypenameLoc); 1987 PP.AnnotateCachedTokens(Tok); 1988 return false; 1989 } 1990 1991 // Remembers whether the token was originally a scope annotation. 1992 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1993 1994 CXXScopeSpec SS; 1995 if (getLangOpts().CPlusPlus) 1996 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1997 /*ObjectHasErrors=*/false, 1998 /*EnteringContext*/ false)) 1999 return true; 2000 2001 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation); 2002 } 2003 2004 /// Try to annotate a type or scope token, having already parsed an 2005 /// optional scope specifier. \p IsNewScope should be \c true unless the scope 2006 /// specifier was extracted from an existing tok::annot_cxxscope annotation. 2007 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, 2008 bool IsNewScope) { 2009 if (Tok.is(tok::identifier)) { 2010 // Determine whether the identifier is a type name. 2011 if (ParsedType Ty = Actions.getTypeName( 2012 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS, 2013 false, NextToken().is(tok::period), nullptr, 2014 /*IsCtorOrDtorName=*/false, 2015 /*NonTrivialTypeSourceInfo*/true, 2016 /*IsClassTemplateDeductionContext*/true)) { 2017 SourceLocation BeginLoc = Tok.getLocation(); 2018 if (SS.isNotEmpty()) // it was a C++ qualified type name. 2019 BeginLoc = SS.getBeginLoc(); 2020 2021 /// An Objective-C object type followed by '<' is a specialization of 2022 /// a parameterized class type or a protocol-qualified type. 2023 if (getLangOpts().ObjC && NextToken().is(tok::less) && 2024 (Ty.get()->isObjCObjectType() || 2025 Ty.get()->isObjCObjectPointerType())) { 2026 // Consume the name. 2027 SourceLocation IdentifierLoc = ConsumeToken(); 2028 SourceLocation NewEndLoc; 2029 TypeResult NewType 2030 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, 2031 /*consumeLastToken=*/false, 2032 NewEndLoc); 2033 if (NewType.isUsable()) 2034 Ty = NewType.get(); 2035 else if (Tok.is(tok::eof)) // Nothing to do here, bail out... 2036 return false; 2037 } 2038 2039 // This is a typename. Replace the current token in-place with an 2040 // annotation type token. 2041 Tok.setKind(tok::annot_typename); 2042 setTypeAnnotation(Tok, Ty); 2043 Tok.setAnnotationEndLoc(Tok.getLocation()); 2044 Tok.setLocation(BeginLoc); 2045 2046 // In case the tokens were cached, have Preprocessor replace 2047 // them with the annotation token. 2048 PP.AnnotateCachedTokens(Tok); 2049 return false; 2050 } 2051 2052 if (!getLangOpts().CPlusPlus) { 2053 // If we're in C, we can't have :: tokens at all (the lexer won't return 2054 // them). If the identifier is not a type, then it can't be scope either, 2055 // just early exit. 2056 return false; 2057 } 2058 2059 // If this is a template-id, annotate with a template-id or type token. 2060 // FIXME: This appears to be dead code. We already have formed template-id 2061 // tokens when parsing the scope specifier; this can never form a new one. 2062 if (NextToken().is(tok::less)) { 2063 TemplateTy Template; 2064 UnqualifiedId TemplateName; 2065 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 2066 bool MemberOfUnknownSpecialization; 2067 if (TemplateNameKind TNK = Actions.isTemplateName( 2068 getCurScope(), SS, 2069 /*hasTemplateKeyword=*/false, TemplateName, 2070 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template, 2071 MemberOfUnknownSpecialization)) { 2072 // Only annotate an undeclared template name as a template-id if the 2073 // following tokens have the form of a template argument list. 2074 if (TNK != TNK_Undeclared_template || 2075 isTemplateArgumentList(1) != TPResult::False) { 2076 // Consume the identifier. 2077 ConsumeToken(); 2078 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 2079 TemplateName)) { 2080 // If an unrecoverable error occurred, we need to return true here, 2081 // because the token stream is in a damaged state. We may not 2082 // return a valid identifier. 2083 return true; 2084 } 2085 } 2086 } 2087 } 2088 2089 // The current token, which is either an identifier or a 2090 // template-id, is not part of the annotation. Fall through to 2091 // push that token back into the stream and complete the C++ scope 2092 // specifier annotation. 2093 } 2094 2095 if (Tok.is(tok::annot_template_id)) { 2096 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2097 if (TemplateId->Kind == TNK_Type_template) { 2098 // A template-id that refers to a type was parsed into a 2099 // template-id annotation in a context where we weren't allowed 2100 // to produce a type annotation token. Update the template-id 2101 // annotation token to a type annotation token now. 2102 AnnotateTemplateIdTokenAsType(SS); 2103 return false; 2104 } 2105 } 2106 2107 if (SS.isEmpty()) 2108 return false; 2109 2110 // A C++ scope specifier that isn't followed by a typename. 2111 AnnotateScopeToken(SS, IsNewScope); 2112 return false; 2113 } 2114 2115 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only 2116 /// annotates C++ scope specifiers and template-ids. This returns 2117 /// true if there was an error that could not be recovered from. 2118 /// 2119 /// Note that this routine emits an error if you call it with ::new or ::delete 2120 /// as the current tokens, so only call it in contexts where these are invalid. 2121 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { 2122 assert(getLangOpts().CPlusPlus && 2123 "Call sites of this function should be guarded by checking for C++"); 2124 assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!"); 2125 2126 CXXScopeSpec SS; 2127 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 2128 /*ObjectHasErrors=*/false, 2129 EnteringContext)) 2130 return true; 2131 if (SS.isEmpty()) 2132 return false; 2133 2134 AnnotateScopeToken(SS, true); 2135 return false; 2136 } 2137 2138 bool Parser::isTokenEqualOrEqualTypo() { 2139 tok::TokenKind Kind = Tok.getKind(); 2140 switch (Kind) { 2141 default: 2142 return false; 2143 case tok::ampequal: // &= 2144 case tok::starequal: // *= 2145 case tok::plusequal: // += 2146 case tok::minusequal: // -= 2147 case tok::exclaimequal: // != 2148 case tok::slashequal: // /= 2149 case tok::percentequal: // %= 2150 case tok::lessequal: // <= 2151 case tok::lesslessequal: // <<= 2152 case tok::greaterequal: // >= 2153 case tok::greatergreaterequal: // >>= 2154 case tok::caretequal: // ^= 2155 case tok::pipeequal: // |= 2156 case tok::equalequal: // == 2157 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal) 2158 << Kind 2159 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "="); 2160 LLVM_FALLTHROUGH; 2161 case tok::equal: 2162 return true; 2163 } 2164 } 2165 2166 SourceLocation Parser::handleUnexpectedCodeCompletionToken() { 2167 assert(Tok.is(tok::code_completion)); 2168 PrevTokLocation = Tok.getLocation(); 2169 2170 for (Scope *S = getCurScope(); S; S = S->getParent()) { 2171 if (S->isFunctionScope()) { 2172 cutOffParsing(); 2173 Actions.CodeCompleteOrdinaryName(getCurScope(), 2174 Sema::PCC_RecoveryInFunction); 2175 return PrevTokLocation; 2176 } 2177 2178 if (S->isClassScope()) { 2179 cutOffParsing(); 2180 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); 2181 return PrevTokLocation; 2182 } 2183 } 2184 2185 cutOffParsing(); 2186 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); 2187 return PrevTokLocation; 2188 } 2189 2190 // Code-completion pass-through functions 2191 2192 void Parser::CodeCompleteDirective(bool InConditional) { 2193 Actions.CodeCompletePreprocessorDirective(InConditional); 2194 } 2195 2196 void Parser::CodeCompleteInConditionalExclusion() { 2197 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope()); 2198 } 2199 2200 void Parser::CodeCompleteMacroName(bool IsDefinition) { 2201 Actions.CodeCompletePreprocessorMacroName(IsDefinition); 2202 } 2203 2204 void Parser::CodeCompletePreprocessorExpression() { 2205 Actions.CodeCompletePreprocessorExpression(); 2206 } 2207 2208 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro, 2209 MacroInfo *MacroInfo, 2210 unsigned ArgumentIndex) { 2211 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 2212 ArgumentIndex); 2213 } 2214 2215 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) { 2216 Actions.CodeCompleteIncludedFile(Dir, IsAngled); 2217 } 2218 2219 void Parser::CodeCompleteNaturalLanguage() { 2220 Actions.CodeCompleteNaturalLanguage(); 2221 } 2222 2223 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { 2224 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) && 2225 "Expected '__if_exists' or '__if_not_exists'"); 2226 Result.IsIfExists = Tok.is(tok::kw___if_exists); 2227 Result.KeywordLoc = ConsumeToken(); 2228 2229 BalancedDelimiterTracker T(*this, tok::l_paren); 2230 if (T.consumeOpen()) { 2231 Diag(Tok, diag::err_expected_lparen_after) 2232 << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); 2233 return true; 2234 } 2235 2236 // Parse nested-name-specifier. 2237 if (getLangOpts().CPlusPlus) 2238 ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr, 2239 /*ObjectHasErrors=*/false, 2240 /*EnteringContext=*/false); 2241 2242 // Check nested-name specifier. 2243 if (Result.SS.isInvalid()) { 2244 T.skipToEnd(); 2245 return true; 2246 } 2247 2248 // Parse the unqualified-id. 2249 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused. 2250 if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr, 2251 /*ObjectHadErrors=*/false, /*EnteringContext*/ false, 2252 /*AllowDestructorName*/ true, 2253 /*AllowConstructorName*/ true, 2254 /*AllowDeductionGuide*/ false, &TemplateKWLoc, 2255 Result.Name)) { 2256 T.skipToEnd(); 2257 return true; 2258 } 2259 2260 if (T.consumeClose()) 2261 return true; 2262 2263 // Check if the symbol exists. 2264 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, 2265 Result.IsIfExists, Result.SS, 2266 Result.Name)) { 2267 case Sema::IER_Exists: 2268 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip; 2269 break; 2270 2271 case Sema::IER_DoesNotExist: 2272 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip; 2273 break; 2274 2275 case Sema::IER_Dependent: 2276 Result.Behavior = IEB_Dependent; 2277 break; 2278 2279 case Sema::IER_Error: 2280 return true; 2281 } 2282 2283 return false; 2284 } 2285 2286 void Parser::ParseMicrosoftIfExistsExternalDeclaration() { 2287 IfExistsCondition Result; 2288 if (ParseMicrosoftIfExistsCondition(Result)) 2289 return; 2290 2291 BalancedDelimiterTracker Braces(*this, tok::l_brace); 2292 if (Braces.consumeOpen()) { 2293 Diag(Tok, diag::err_expected) << tok::l_brace; 2294 return; 2295 } 2296 2297 switch (Result.Behavior) { 2298 case IEB_Parse: 2299 // Parse declarations below. 2300 break; 2301 2302 case IEB_Dependent: 2303 llvm_unreachable("Cannot have a dependent external declaration"); 2304 2305 case IEB_Skip: 2306 Braces.skipToEnd(); 2307 return; 2308 } 2309 2310 // Parse the declarations. 2311 // FIXME: Support module import within __if_exists? 2312 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 2313 ParsedAttributes Attrs(AttrFactory); 2314 MaybeParseCXX11Attributes(Attrs); 2315 DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs); 2316 if (Result && !getCurScope()->getParent()) 2317 Actions.getASTConsumer().HandleTopLevelDecl(Result.get()); 2318 } 2319 Braces.consumeClose(); 2320 } 2321 2322 /// Parse a declaration beginning with the 'module' keyword or C++20 2323 /// context-sensitive keyword (optionally preceded by 'export'). 2324 /// 2325 /// module-declaration: [Modules TS + P0629R0] 2326 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';' 2327 /// 2328 /// global-module-fragment: [C++2a] 2329 /// 'module' ';' top-level-declaration-seq[opt] 2330 /// module-declaration: [C++2a] 2331 /// 'export'[opt] 'module' module-name module-partition[opt] 2332 /// attribute-specifier-seq[opt] ';' 2333 /// private-module-fragment: [C++2a] 2334 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt] 2335 Parser::DeclGroupPtrTy 2336 Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) { 2337 SourceLocation StartLoc = Tok.getLocation(); 2338 2339 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export) 2340 ? Sema::ModuleDeclKind::Interface 2341 : Sema::ModuleDeclKind::Implementation; 2342 2343 assert( 2344 (Tok.is(tok::kw_module) || 2345 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) && 2346 "not a module declaration"); 2347 SourceLocation ModuleLoc = ConsumeToken(); 2348 2349 // Attributes appear after the module name, not before. 2350 // FIXME: Suggest moving the attributes later with a fixit. 2351 DiagnoseAndSkipCXX11Attributes(); 2352 2353 // Parse a global-module-fragment, if present. 2354 if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) { 2355 SourceLocation SemiLoc = ConsumeToken(); 2356 if (ImportState != Sema::ModuleImportState::FirstDecl) { 2357 Diag(StartLoc, diag::err_global_module_introducer_not_at_start) 2358 << SourceRange(StartLoc, SemiLoc); 2359 return nullptr; 2360 } 2361 if (MDK == Sema::ModuleDeclKind::Interface) { 2362 Diag(StartLoc, diag::err_module_fragment_exported) 2363 << /*global*/0 << FixItHint::CreateRemoval(StartLoc); 2364 } 2365 ImportState = Sema::ModuleImportState::GlobalFragment; 2366 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc); 2367 } 2368 2369 // Parse a private-module-fragment, if present. 2370 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) && 2371 NextToken().is(tok::kw_private)) { 2372 if (MDK == Sema::ModuleDeclKind::Interface) { 2373 Diag(StartLoc, diag::err_module_fragment_exported) 2374 << /*private*/1 << FixItHint::CreateRemoval(StartLoc); 2375 } 2376 ConsumeToken(); 2377 SourceLocation PrivateLoc = ConsumeToken(); 2378 DiagnoseAndSkipCXX11Attributes(); 2379 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi); 2380 ImportState = Sema::ModuleImportState::PrivateFragment; 2381 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc); 2382 } 2383 2384 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2385 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false)) 2386 return nullptr; 2387 2388 // Parse the optional module-partition. 2389 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition; 2390 if (Tok.is(tok::colon)) { 2391 SourceLocation ColonLoc = ConsumeToken(); 2392 if (!getLangOpts().CPlusPlusModules) 2393 Diag(ColonLoc, diag::err_unsupported_module_partition) 2394 << SourceRange(ColonLoc, Partition.back().second); 2395 // Recover by ignoring the partition name. 2396 else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false)) 2397 return nullptr; 2398 } 2399 2400 // We don't support any module attributes yet; just parse them and diagnose. 2401 ParsedAttributes Attrs(AttrFactory); 2402 MaybeParseCXX11Attributes(Attrs); 2403 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr, 2404 /*DiagnoseEmptyAttrs=*/false, 2405 /*WarnOnUnknownAttrs=*/true); 2406 2407 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2408 2409 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition, 2410 ImportState); 2411 } 2412 2413 /// Parse a module import declaration. This is essentially the same for 2414 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the 2415 /// trailing optional attributes (in C++). 2416 /// 2417 /// [ObjC] @import declaration: 2418 /// '@' 'import' module-name ';' 2419 /// [ModTS] module-import-declaration: 2420 /// 'import' module-name attribute-specifier-seq[opt] ';' 2421 /// [C++20] module-import-declaration: 2422 /// 'export'[opt] 'import' module-name 2423 /// attribute-specifier-seq[opt] ';' 2424 /// 'export'[opt] 'import' module-partition 2425 /// attribute-specifier-seq[opt] ';' 2426 /// 'export'[opt] 'import' header-name 2427 /// attribute-specifier-seq[opt] ';' 2428 Decl *Parser::ParseModuleImport(SourceLocation AtLoc, 2429 Sema::ModuleImportState &ImportState) { 2430 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc; 2431 2432 SourceLocation ExportLoc; 2433 TryConsumeToken(tok::kw_export, ExportLoc); 2434 2435 assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier) 2436 : Tok.isObjCAtKeyword(tok::objc_import)) && 2437 "Improper start to module import"); 2438 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import); 2439 SourceLocation ImportLoc = ConsumeToken(); 2440 2441 // For C++20 modules, we can have "name" or ":Partition name" as valid input. 2442 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2443 bool IsPartition = false; 2444 Module *HeaderUnit = nullptr; 2445 if (Tok.is(tok::header_name)) { 2446 // This is a header import that the preprocessor decided we should skip 2447 // because it was malformed in some way. Parse and ignore it; it's already 2448 // been diagnosed. 2449 ConsumeToken(); 2450 } else if (Tok.is(tok::annot_header_unit)) { 2451 // This is a header import that the preprocessor mapped to a module import. 2452 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue()); 2453 ConsumeAnnotationToken(); 2454 } else if (Tok.is(tok::colon)) { 2455 SourceLocation ColonLoc = ConsumeToken(); 2456 if (!getLangOpts().CPlusPlusModules) 2457 Diag(ColonLoc, diag::err_unsupported_module_partition) 2458 << SourceRange(ColonLoc, Path.back().second); 2459 // Recover by leaving partition empty. 2460 else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true)) 2461 return nullptr; 2462 else 2463 IsPartition = true; 2464 } else { 2465 if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true)) 2466 return nullptr; 2467 } 2468 2469 ParsedAttributes Attrs(AttrFactory); 2470 MaybeParseCXX11Attributes(Attrs); 2471 // We don't support any module import attributes yet. 2472 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr, 2473 /*DiagnoseEmptyAttrs=*/false, 2474 /*WarnOnUnknownAttrs=*/true); 2475 2476 if (PP.hadModuleLoaderFatalFailure()) { 2477 // With a fatal failure in the module loader, we abort parsing. 2478 cutOffParsing(); 2479 return nullptr; 2480 } 2481 2482 // Diagnose mis-imports. 2483 bool SeenError = true; 2484 switch (ImportState) { 2485 case Sema::ModuleImportState::ImportAllowed: 2486 SeenError = false; 2487 break; 2488 case Sema::ModuleImportState::FirstDecl: 2489 case Sema::ModuleImportState::NotACXX20Module: 2490 // We can only import a partition within a module purview. 2491 if (IsPartition) 2492 Diag(ImportLoc, diag::err_partition_import_outside_module); 2493 else 2494 SeenError = false; 2495 break; 2496 case Sema::ModuleImportState::GlobalFragment: 2497 // We can only have pre-processor directives in the global module 2498 // fragment. We cannot import a named modules here, however we have a 2499 // header unit import. 2500 if (!HeaderUnit || HeaderUnit->Kind != Module::ModuleKind::ModuleHeaderUnit) 2501 Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 0; 2502 else 2503 SeenError = false; 2504 break; 2505 case Sema::ModuleImportState::ImportFinished: 2506 if (getLangOpts().CPlusPlusModules) 2507 Diag(ImportLoc, diag::err_import_not_allowed_here); 2508 else 2509 SeenError = false; 2510 break; 2511 case Sema::ModuleImportState::PrivateFragment: 2512 Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 1; 2513 break; 2514 } 2515 if (SeenError) { 2516 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2517 return nullptr; 2518 } 2519 2520 DeclResult Import; 2521 if (HeaderUnit) 2522 Import = 2523 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit); 2524 else if (!Path.empty()) 2525 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path, 2526 IsPartition); 2527 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2528 if (Import.isInvalid()) 2529 return nullptr; 2530 2531 // Using '@import' in framework headers requires modules to be enabled so that 2532 // the header is parseable. Emit a warning to make the user aware. 2533 if (IsObjCAtImport && AtLoc.isValid()) { 2534 auto &SrcMgr = PP.getSourceManager(); 2535 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc)); 2536 if (FE && llvm::sys::path::parent_path(FE->getDir().getName()) 2537 .endswith(".framework")) 2538 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header); 2539 } 2540 2541 return Import.get(); 2542 } 2543 2544 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same 2545 /// grammar). 2546 /// 2547 /// module-name: 2548 /// module-name-qualifier[opt] identifier 2549 /// module-name-qualifier: 2550 /// module-name-qualifier[opt] identifier '.' 2551 bool Parser::ParseModuleName( 2552 SourceLocation UseLoc, 2553 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, 2554 bool IsImport) { 2555 // Parse the module path. 2556 while (true) { 2557 if (!Tok.is(tok::identifier)) { 2558 if (Tok.is(tok::code_completion)) { 2559 cutOffParsing(); 2560 Actions.CodeCompleteModuleImport(UseLoc, Path); 2561 return true; 2562 } 2563 2564 Diag(Tok, diag::err_module_expected_ident) << IsImport; 2565 SkipUntil(tok::semi); 2566 return true; 2567 } 2568 2569 // Record this part of the module path. 2570 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); 2571 ConsumeToken(); 2572 2573 if (Tok.isNot(tok::period)) 2574 return false; 2575 2576 ConsumeToken(); 2577 } 2578 } 2579 2580 /// Try recover parser when module annotation appears where it must not 2581 /// be found. 2582 /// \returns false if the recover was successful and parsing may be continued, or 2583 /// true if parser must bail out to top level and handle the token there. 2584 bool Parser::parseMisplacedModuleImport() { 2585 while (true) { 2586 switch (Tok.getKind()) { 2587 case tok::annot_module_end: 2588 // If we recovered from a misplaced module begin, we expect to hit a 2589 // misplaced module end too. Stay in the current context when this 2590 // happens. 2591 if (MisplacedModuleBeginCount) { 2592 --MisplacedModuleBeginCount; 2593 Actions.ActOnModuleEnd(Tok.getLocation(), 2594 reinterpret_cast<Module *>( 2595 Tok.getAnnotationValue())); 2596 ConsumeAnnotationToken(); 2597 continue; 2598 } 2599 // Inform caller that recovery failed, the error must be handled at upper 2600 // level. This will generate the desired "missing '}' at end of module" 2601 // diagnostics on the way out. 2602 return true; 2603 case tok::annot_module_begin: 2604 // Recover by entering the module (Sema will diagnose). 2605 Actions.ActOnModuleBegin(Tok.getLocation(), 2606 reinterpret_cast<Module *>( 2607 Tok.getAnnotationValue())); 2608 ConsumeAnnotationToken(); 2609 ++MisplacedModuleBeginCount; 2610 continue; 2611 case tok::annot_module_include: 2612 // Module import found where it should not be, for instance, inside a 2613 // namespace. Recover by importing the module. 2614 Actions.ActOnModuleInclude(Tok.getLocation(), 2615 reinterpret_cast<Module *>( 2616 Tok.getAnnotationValue())); 2617 ConsumeAnnotationToken(); 2618 // If there is another module import, process it. 2619 continue; 2620 default: 2621 return false; 2622 } 2623 } 2624 return false; 2625 } 2626 2627 bool BalancedDelimiterTracker::diagnoseOverflow() { 2628 P.Diag(P.Tok, diag::err_bracket_depth_exceeded) 2629 << P.getLangOpts().BracketDepth; 2630 P.Diag(P.Tok, diag::note_bracket_depth); 2631 P.cutOffParsing(); 2632 return true; 2633 } 2634 2635 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, 2636 const char *Msg, 2637 tok::TokenKind SkipToTok) { 2638 LOpen = P.Tok.getLocation(); 2639 if (P.ExpectAndConsume(Kind, DiagID, Msg)) { 2640 if (SkipToTok != tok::unknown) 2641 P.SkipUntil(SkipToTok, Parser::StopAtSemi); 2642 return true; 2643 } 2644 2645 if (getDepth() < P.getLangOpts().BracketDepth) 2646 return false; 2647 2648 return diagnoseOverflow(); 2649 } 2650 2651 bool BalancedDelimiterTracker::diagnoseMissingClose() { 2652 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter"); 2653 2654 if (P.Tok.is(tok::annot_module_end)) 2655 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close; 2656 else 2657 P.Diag(P.Tok, diag::err_expected) << Close; 2658 P.Diag(LOpen, diag::note_matching) << Kind; 2659 2660 // If we're not already at some kind of closing bracket, skip to our closing 2661 // token. 2662 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) && 2663 P.Tok.isNot(tok::r_square) && 2664 P.SkipUntil(Close, FinalToken, 2665 Parser::StopAtSemi | Parser::StopBeforeMatch) && 2666 P.Tok.is(Close)) 2667 LClose = P.ConsumeAnyToken(); 2668 return true; 2669 } 2670 2671 void BalancedDelimiterTracker::skipToEnd() { 2672 P.SkipUntil(Close, Parser::StopBeforeMatch); 2673 consumeClose(); 2674 } 2675