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 ParsedAttributesWithRange 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 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl] 744 /// function-definition 745 /// declaration 746 /// [GNU] asm-definition 747 /// [GNU] __extension__ external-declaration 748 /// [OBJC] objc-class-definition 749 /// [OBJC] objc-class-declaration 750 /// [OBJC] objc-alias-declaration 751 /// [OBJC] objc-protocol-definition 752 /// [OBJC] objc-method-definition 753 /// [OBJC] @end 754 /// [C++] linkage-specification 755 /// [GNU] asm-definition: 756 /// simple-asm-expr ';' 757 /// [C++11] empty-declaration 758 /// [C++11] attribute-declaration 759 /// 760 /// [C++11] empty-declaration: 761 /// ';' 762 /// 763 /// [C++0x/GNU] 'extern' 'template' declaration 764 /// 765 /// [Modules-TS] module-import-declaration 766 /// 767 Parser::DeclGroupPtrTy 768 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs, 769 ParsingDeclSpec *DS) { 770 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this); 771 ParenBraceBracketBalancer BalancerRAIIObj(*this); 772 773 if (PP.isCodeCompletionReached()) { 774 cutOffParsing(); 775 return nullptr; 776 } 777 778 Decl *SingleDecl = nullptr; 779 switch (Tok.getKind()) { 780 case tok::annot_pragma_vis: 781 HandlePragmaVisibility(); 782 return nullptr; 783 case tok::annot_pragma_pack: 784 HandlePragmaPack(); 785 return nullptr; 786 case tok::annot_pragma_msstruct: 787 HandlePragmaMSStruct(); 788 return nullptr; 789 case tok::annot_pragma_align: 790 HandlePragmaAlign(); 791 return nullptr; 792 case tok::annot_pragma_weak: 793 HandlePragmaWeak(); 794 return nullptr; 795 case tok::annot_pragma_weakalias: 796 HandlePragmaWeakAlias(); 797 return nullptr; 798 case tok::annot_pragma_redefine_extname: 799 HandlePragmaRedefineExtname(); 800 return nullptr; 801 case tok::annot_pragma_fp_contract: 802 HandlePragmaFPContract(); 803 return nullptr; 804 case tok::annot_pragma_fenv_access: 805 case tok::annot_pragma_fenv_access_ms: 806 HandlePragmaFEnvAccess(); 807 return nullptr; 808 case tok::annot_pragma_fenv_round: 809 HandlePragmaFEnvRound(); 810 return nullptr; 811 case tok::annot_pragma_float_control: 812 HandlePragmaFloatControl(); 813 return nullptr; 814 case tok::annot_pragma_fp: 815 HandlePragmaFP(); 816 break; 817 case tok::annot_pragma_opencl_extension: 818 HandlePragmaOpenCLExtension(); 819 return nullptr; 820 case tok::annot_attr_openmp: 821 case tok::annot_pragma_openmp: { 822 AccessSpecifier AS = AS_none; 823 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs); 824 } 825 case tok::annot_pragma_ms_pointers_to_members: 826 HandlePragmaMSPointersToMembers(); 827 return nullptr; 828 case tok::annot_pragma_ms_vtordisp: 829 HandlePragmaMSVtorDisp(); 830 return nullptr; 831 case tok::annot_pragma_ms_pragma: 832 HandlePragmaMSPragma(); 833 return nullptr; 834 case tok::annot_pragma_dump: 835 HandlePragmaDump(); 836 return nullptr; 837 case tok::annot_pragma_attribute: 838 HandlePragmaAttribute(); 839 return nullptr; 840 case tok::semi: 841 // Either a C++11 empty-declaration or attribute-declaration. 842 SingleDecl = 843 Actions.ActOnEmptyDeclaration(getCurScope(), attrs, Tok.getLocation()); 844 ConsumeExtraSemi(OutsideFunction); 845 break; 846 case tok::r_brace: 847 Diag(Tok, diag::err_extraneous_closing_brace); 848 ConsumeBrace(); 849 return nullptr; 850 case tok::eof: 851 Diag(Tok, diag::err_expected_external_declaration); 852 return nullptr; 853 case tok::kw___extension__: { 854 // __extension__ silences extension warnings in the subexpression. 855 ExtensionRAIIObject O(Diags); // Use RAII to do this. 856 ConsumeToken(); 857 return ParseExternalDeclaration(attrs); 858 } 859 case tok::kw_asm: { 860 ProhibitAttributes(attrs); 861 862 SourceLocation StartLoc = Tok.getLocation(); 863 SourceLocation EndLoc; 864 865 ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc)); 866 867 // Check if GNU-style InlineAsm is disabled. 868 // Empty asm string is allowed because it will not introduce 869 // any assembly code. 870 if (!(getLangOpts().GNUAsm || Result.isInvalid())) { 871 const auto *SL = cast<StringLiteral>(Result.get()); 872 if (!SL->getString().trim().empty()) 873 Diag(StartLoc, diag::err_gnu_inline_asm_disabled); 874 } 875 876 ExpectAndConsume(tok::semi, diag::err_expected_after, 877 "top-level asm block"); 878 879 if (Result.isInvalid()) 880 return nullptr; 881 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc); 882 break; 883 } 884 case tok::at: 885 return ParseObjCAtDirectives(attrs); 886 case tok::minus: 887 case tok::plus: 888 if (!getLangOpts().ObjC) { 889 Diag(Tok, diag::err_expected_external_declaration); 890 ConsumeToken(); 891 return nullptr; 892 } 893 SingleDecl = ParseObjCMethodDefinition(); 894 break; 895 case tok::code_completion: 896 cutOffParsing(); 897 if (CurParsedObjCImpl) { 898 // Code-complete Objective-C methods even without leading '-'/'+' prefix. 899 Actions.CodeCompleteObjCMethodDecl(getCurScope(), 900 /*IsInstanceMethod=*/None, 901 /*ReturnType=*/nullptr); 902 } 903 Actions.CodeCompleteOrdinaryName( 904 getCurScope(), 905 CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace); 906 return nullptr; 907 case tok::kw_import: { 908 Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module; 909 if (getLangOpts().CPlusPlusModules) { 910 llvm_unreachable("not expecting a c++20 import here"); 911 ProhibitAttributes(attrs); 912 } 913 SingleDecl = ParseModuleImport(SourceLocation(), IS); 914 } break; 915 case tok::kw_export: 916 if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) { 917 ProhibitAttributes(attrs); 918 SingleDecl = ParseExportDeclaration(); 919 break; 920 } 921 // This must be 'export template'. Parse it so we can diagnose our lack 922 // of support. 923 LLVM_FALLTHROUGH; 924 case tok::kw_using: 925 case tok::kw_namespace: 926 case tok::kw_typedef: 927 case tok::kw_template: 928 case tok::kw_static_assert: 929 case tok::kw__Static_assert: 930 // A function definition cannot start with any of these keywords. 931 { 932 SourceLocation DeclEnd; 933 return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs); 934 } 935 936 case tok::kw_static: 937 // Parse (then ignore) 'static' prior to a template instantiation. This is 938 // a GCC extension that we intentionally do not support. 939 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) { 940 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 941 << 0; 942 SourceLocation DeclEnd; 943 return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs); 944 } 945 goto dont_know; 946 947 case tok::kw_inline: 948 if (getLangOpts().CPlusPlus) { 949 tok::TokenKind NextKind = NextToken().getKind(); 950 951 // Inline namespaces. Allowed as an extension even in C++03. 952 if (NextKind == tok::kw_namespace) { 953 SourceLocation DeclEnd; 954 return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs); 955 } 956 957 // Parse (then ignore) 'inline' prior to a template instantiation. This is 958 // a GCC extension that we intentionally do not support. 959 if (NextKind == tok::kw_template) { 960 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 961 << 1; 962 SourceLocation DeclEnd; 963 return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs); 964 } 965 } 966 goto dont_know; 967 968 case tok::kw_extern: 969 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) { 970 // Extern templates 971 SourceLocation ExternLoc = ConsumeToken(); 972 SourceLocation TemplateLoc = ConsumeToken(); 973 Diag(ExternLoc, getLangOpts().CPlusPlus11 ? 974 diag::warn_cxx98_compat_extern_template : 975 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc); 976 SourceLocation DeclEnd; 977 return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation( 978 DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, attrs)); 979 } 980 goto dont_know; 981 982 case tok::kw___if_exists: 983 case tok::kw___if_not_exists: 984 ParseMicrosoftIfExistsExternalDeclaration(); 985 return nullptr; 986 987 case tok::kw_module: 988 Diag(Tok, diag::err_unexpected_module_decl); 989 SkipUntil(tok::semi); 990 return nullptr; 991 992 default: 993 dont_know: 994 if (Tok.isEditorPlaceholder()) { 995 ConsumeToken(); 996 return nullptr; 997 } 998 // We can't tell whether this is a function-definition or declaration yet. 999 return ParseDeclarationOrFunctionDefinition(attrs, DS); 1000 } 1001 1002 // This routine returns a DeclGroup, if the thing we parsed only contains a 1003 // single decl, convert it now. 1004 return Actions.ConvertDeclToDeclGroup(SingleDecl); 1005 } 1006 1007 /// Determine whether the current token, if it occurs after a 1008 /// declarator, continues a declaration or declaration list. 1009 bool Parser::isDeclarationAfterDeclarator() { 1010 // Check for '= delete' or '= default' 1011 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) { 1012 const Token &KW = NextToken(); 1013 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete)) 1014 return false; 1015 } 1016 1017 return Tok.is(tok::equal) || // int X()= -> not a function def 1018 Tok.is(tok::comma) || // int X(), -> not a function def 1019 Tok.is(tok::semi) || // int X(); -> not a function def 1020 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def 1021 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def 1022 (getLangOpts().CPlusPlus && 1023 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++] 1024 } 1025 1026 /// Determine whether the current token, if it occurs after a 1027 /// declarator, indicates the start of a function definition. 1028 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) { 1029 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator"); 1030 if (Tok.is(tok::l_brace)) // int X() {} 1031 return true; 1032 1033 // Handle K&R C argument lists: int X(f) int f; {} 1034 if (!getLangOpts().CPlusPlus && 1035 Declarator.getFunctionTypeInfo().isKNRPrototype()) 1036 return isDeclarationSpecifier(); 1037 1038 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) { 1039 const Token &KW = NextToken(); 1040 return KW.is(tok::kw_default) || KW.is(tok::kw_delete); 1041 } 1042 1043 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors) 1044 Tok.is(tok::kw_try); // X() try { ... } 1045 } 1046 1047 /// Parse either a function-definition or a declaration. We can't tell which 1048 /// we have until we read up to the compound-statement in function-definition. 1049 /// TemplateParams, if non-NULL, provides the template parameters when we're 1050 /// parsing a C++ template-declaration. 1051 /// 1052 /// function-definition: [C99 6.9.1] 1053 /// decl-specs declarator declaration-list[opt] compound-statement 1054 /// [C90] function-definition: [C99 6.7.1] - implicit int result 1055 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 1056 /// 1057 /// declaration: [C99 6.7] 1058 /// declaration-specifiers init-declarator-list[opt] ';' 1059 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode] 1060 /// [OMP] threadprivate-directive 1061 /// [OMP] allocate-directive [TODO] 1062 /// 1063 Parser::DeclGroupPtrTy 1064 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, 1065 ParsingDeclSpec &DS, 1066 AccessSpecifier AS) { 1067 MaybeParseMicrosoftAttributes(DS.getAttributes()); 1068 // Parse the common declaration-specifiers piece. 1069 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, 1070 DeclSpecContext::DSC_top_level); 1071 1072 // If we had a free-standing type definition with a missing semicolon, we 1073 // may get this far before the problem becomes obvious. 1074 if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition( 1075 DS, AS, DeclSpecContext::DSC_top_level)) 1076 return nullptr; 1077 1078 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 1079 // declaration-specifiers init-declarator-list[opt] ';' 1080 if (Tok.is(tok::semi)) { 1081 auto LengthOfTSTToken = [](DeclSpec::TST TKind) { 1082 assert(DeclSpec::isDeclRep(TKind)); 1083 switch(TKind) { 1084 case DeclSpec::TST_class: 1085 return 5; 1086 case DeclSpec::TST_struct: 1087 return 6; 1088 case DeclSpec::TST_union: 1089 return 5; 1090 case DeclSpec::TST_enum: 1091 return 4; 1092 case DeclSpec::TST_interface: 1093 return 9; 1094 default: 1095 llvm_unreachable("we only expect to get the length of the class/struct/union/enum"); 1096 } 1097 1098 }; 1099 // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]' 1100 SourceLocation CorrectLocationForAttributes = 1101 DeclSpec::isDeclRep(DS.getTypeSpecType()) 1102 ? DS.getTypeSpecTypeLoc().getLocWithOffset( 1103 LengthOfTSTToken(DS.getTypeSpecType())) 1104 : SourceLocation(); 1105 ProhibitAttributes(attrs, CorrectLocationForAttributes); 1106 ConsumeToken(); 1107 RecordDecl *AnonRecord = nullptr; 1108 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 1109 DS, AnonRecord); 1110 DS.complete(TheDecl); 1111 if (AnonRecord) { 1112 Decl* decls[] = {AnonRecord, TheDecl}; 1113 return Actions.BuildDeclaratorGroup(decls); 1114 } 1115 return Actions.ConvertDeclToDeclGroup(TheDecl); 1116 } 1117 1118 DS.takeAttributesFrom(attrs); 1119 1120 // ObjC2 allows prefix attributes on class interfaces and protocols. 1121 // FIXME: This still needs better diagnostics. We should only accept 1122 // attributes here, no types, etc. 1123 if (getLangOpts().ObjC && Tok.is(tok::at)) { 1124 SourceLocation AtLoc = ConsumeToken(); // the "@" 1125 if (!Tok.isObjCAtKeyword(tok::objc_interface) && 1126 !Tok.isObjCAtKeyword(tok::objc_protocol) && 1127 !Tok.isObjCAtKeyword(tok::objc_implementation)) { 1128 Diag(Tok, diag::err_objc_unexpected_attr); 1129 SkipUntil(tok::semi); 1130 return nullptr; 1131 } 1132 1133 DS.abort(); 1134 1135 const char *PrevSpec = nullptr; 1136 unsigned DiagID; 1137 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID, 1138 Actions.getASTContext().getPrintingPolicy())) 1139 Diag(AtLoc, DiagID) << PrevSpec; 1140 1141 if (Tok.isObjCAtKeyword(tok::objc_protocol)) 1142 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()); 1143 1144 if (Tok.isObjCAtKeyword(tok::objc_implementation)) 1145 return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes()); 1146 1147 return Actions.ConvertDeclToDeclGroup( 1148 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes())); 1149 } 1150 1151 // If the declspec consisted only of 'extern' and we have a string 1152 // literal following it, this must be a C++ linkage specifier like 1153 // 'extern "C"'. 1154 if (getLangOpts().CPlusPlus && isTokenStringLiteral() && 1155 DS.getStorageClassSpec() == DeclSpec::SCS_extern && 1156 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) { 1157 Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File); 1158 return Actions.ConvertDeclToDeclGroup(TheDecl); 1159 } 1160 1161 return ParseDeclGroup(DS, DeclaratorContext::File); 1162 } 1163 1164 Parser::DeclGroupPtrTy 1165 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs, 1166 ParsingDeclSpec *DS, 1167 AccessSpecifier AS) { 1168 if (DS) { 1169 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS); 1170 } else { 1171 ParsingDeclSpec PDS(*this); 1172 // Must temporarily exit the objective-c container scope for 1173 // parsing c constructs and re-enter objc container scope 1174 // afterwards. 1175 ObjCDeclContextSwitch ObjCDC(*this); 1176 1177 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS); 1178 } 1179 } 1180 1181 /// ParseFunctionDefinition - We parsed and verified that the specified 1182 /// Declarator is well formed. If this is a K&R-style function, read the 1183 /// parameters declaration-list, then start the compound-statement. 1184 /// 1185 /// function-definition: [C99 6.9.1] 1186 /// decl-specs declarator declaration-list[opt] compound-statement 1187 /// [C90] function-definition: [C99 6.7.1] - implicit int result 1188 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 1189 /// [C++] function-definition: [C++ 8.4] 1190 /// decl-specifier-seq[opt] declarator ctor-initializer[opt] 1191 /// function-body 1192 /// [C++] function-definition: [C++ 8.4] 1193 /// decl-specifier-seq[opt] declarator function-try-block 1194 /// 1195 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, 1196 const ParsedTemplateInfo &TemplateInfo, 1197 LateParsedAttrList *LateParsedAttrs) { 1198 // Poison SEH identifiers so they are flagged as illegal in function bodies. 1199 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 1200 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 1201 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 1202 1203 // If this is C90 and the declspecs were completely missing, fudge in an 1204 // implicit int. We do this here because this is the only place where 1205 // declaration-specifiers are completely optional in the grammar. 1206 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) { 1207 const char *PrevSpec; 1208 unsigned DiagID; 1209 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 1210 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int, 1211 D.getIdentifierLoc(), 1212 PrevSpec, DiagID, 1213 Policy); 1214 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin()); 1215 } 1216 1217 // If this declaration was formed with a K&R-style identifier list for the 1218 // arguments, parse declarations for all of the args next. 1219 // int foo(a,b) int a; float b; {} 1220 if (FTI.isKNRPrototype()) 1221 ParseKNRParamDeclarations(D); 1222 1223 // We should have either an opening brace or, in a C++ constructor, 1224 // we may have a colon. 1225 if (Tok.isNot(tok::l_brace) && 1226 (!getLangOpts().CPlusPlus || 1227 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && 1228 Tok.isNot(tok::equal)))) { 1229 Diag(Tok, diag::err_expected_fn_body); 1230 1231 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1232 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 1233 1234 // If we didn't find the '{', bail out. 1235 if (Tok.isNot(tok::l_brace)) 1236 return nullptr; 1237 } 1238 1239 // Check to make sure that any normal attributes are allowed to be on 1240 // a definition. Late parsed attributes are checked at the end. 1241 if (Tok.isNot(tok::equal)) { 1242 for (const ParsedAttr &AL : D.getAttributes()) 1243 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax()) 1244 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL; 1245 } 1246 1247 // In delayed template parsing mode, for function template we consume the 1248 // tokens and store them for late parsing at the end of the translation unit. 1249 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) && 1250 TemplateInfo.Kind == ParsedTemplateInfo::Template && 1251 Actions.canDelayFunctionBody(D)) { 1252 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams); 1253 1254 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1255 Scope::CompoundStmtScope); 1256 Scope *ParentScope = getCurScope()->getParent(); 1257 1258 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 1259 Decl *DP = Actions.HandleDeclarator(ParentScope, D, 1260 TemplateParameterLists); 1261 D.complete(DP); 1262 D.getMutableDeclSpec().abort(); 1263 1264 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) && 1265 trySkippingFunctionBody()) { 1266 BodyScope.Exit(); 1267 return Actions.ActOnSkippedFunctionBody(DP); 1268 } 1269 1270 CachedTokens Toks; 1271 LexTemplateFunctionForLateParsing(Toks); 1272 1273 if (DP) { 1274 FunctionDecl *FnD = DP->getAsFunction(); 1275 Actions.CheckForFunctionRedefinition(FnD); 1276 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks); 1277 } 1278 return DP; 1279 } 1280 else if (CurParsedObjCImpl && 1281 !TemplateInfo.TemplateParams && 1282 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || 1283 Tok.is(tok::colon)) && 1284 Actions.CurContext->isTranslationUnit()) { 1285 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1286 Scope::CompoundStmtScope); 1287 Scope *ParentScope = getCurScope()->getParent(); 1288 1289 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 1290 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D, 1291 MultiTemplateParamsArg()); 1292 D.complete(FuncDecl); 1293 D.getMutableDeclSpec().abort(); 1294 if (FuncDecl) { 1295 // Consume the tokens and store them for later parsing. 1296 StashAwayMethodOrFunctionBodyTokens(FuncDecl); 1297 CurParsedObjCImpl->HasCFunction = true; 1298 return FuncDecl; 1299 } 1300 // FIXME: Should we really fall through here? 1301 } 1302 1303 // Enter a scope for the function body. 1304 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1305 Scope::CompoundStmtScope); 1306 1307 // Tell the actions module that we have entered a function definition with the 1308 // specified Declarator for the function. 1309 Sema::SkipBodyInfo SkipBody; 1310 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D, 1311 TemplateInfo.TemplateParams 1312 ? *TemplateInfo.TemplateParams 1313 : MultiTemplateParamsArg(), 1314 &SkipBody); 1315 1316 if (SkipBody.ShouldSkip) { 1317 SkipFunctionBody(); 1318 return Res; 1319 } 1320 1321 // Break out of the ParsingDeclarator context before we parse the body. 1322 D.complete(Res); 1323 1324 // Break out of the ParsingDeclSpec context, too. This const_cast is 1325 // safe because we're always the sole owner. 1326 D.getMutableDeclSpec().abort(); 1327 1328 // With abbreviated function templates - we need to explicitly add depth to 1329 // account for the implicit template parameter list induced by the template. 1330 if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res)) 1331 if (Template->isAbbreviated() && 1332 Template->getTemplateParameters()->getParam(0)->isImplicit()) 1333 // First template parameter is implicit - meaning no explicit template 1334 // parameter list was specified. 1335 CurTemplateDepthTracker.addDepth(1); 1336 1337 if (TryConsumeToken(tok::equal)) { 1338 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='"); 1339 1340 bool Delete = false; 1341 SourceLocation KWLoc; 1342 if (TryConsumeToken(tok::kw_delete, KWLoc)) { 1343 Diag(KWLoc, getLangOpts().CPlusPlus11 1344 ? diag::warn_cxx98_compat_defaulted_deleted_function 1345 : diag::ext_defaulted_deleted_function) 1346 << 1 /* deleted */; 1347 Actions.SetDeclDeleted(Res, KWLoc); 1348 Delete = true; 1349 } else if (TryConsumeToken(tok::kw_default, KWLoc)) { 1350 Diag(KWLoc, getLangOpts().CPlusPlus11 1351 ? diag::warn_cxx98_compat_defaulted_deleted_function 1352 : diag::ext_defaulted_deleted_function) 1353 << 0 /* defaulted */; 1354 Actions.SetDeclDefaulted(Res, KWLoc); 1355 } else { 1356 llvm_unreachable("function definition after = not 'delete' or 'default'"); 1357 } 1358 1359 if (Tok.is(tok::comma)) { 1360 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) 1361 << Delete; 1362 SkipUntil(tok::semi); 1363 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after, 1364 Delete ? "delete" : "default")) { 1365 SkipUntil(tok::semi); 1366 } 1367 1368 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr; 1369 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false); 1370 return Res; 1371 } 1372 1373 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) && 1374 trySkippingFunctionBody()) { 1375 BodyScope.Exit(); 1376 Actions.ActOnSkippedFunctionBody(Res); 1377 return Actions.ActOnFinishFunctionBody(Res, nullptr, false); 1378 } 1379 1380 if (Tok.is(tok::kw_try)) 1381 return ParseFunctionTryBlock(Res, BodyScope); 1382 1383 // If we have a colon, then we're probably parsing a C++ 1384 // ctor-initializer. 1385 if (Tok.is(tok::colon)) { 1386 ParseConstructorInitializer(Res); 1387 1388 // Recover from error. 1389 if (!Tok.is(tok::l_brace)) { 1390 BodyScope.Exit(); 1391 Actions.ActOnFinishFunctionBody(Res, nullptr); 1392 return Res; 1393 } 1394 } else 1395 Actions.ActOnDefaultCtorInitializers(Res); 1396 1397 // Late attributes are parsed in the same scope as the function body. 1398 if (LateParsedAttrs) 1399 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true); 1400 1401 return ParseFunctionStatementBody(Res, BodyScope); 1402 } 1403 1404 void Parser::SkipFunctionBody() { 1405 if (Tok.is(tok::equal)) { 1406 SkipUntil(tok::semi); 1407 return; 1408 } 1409 1410 bool IsFunctionTryBlock = Tok.is(tok::kw_try); 1411 if (IsFunctionTryBlock) 1412 ConsumeToken(); 1413 1414 CachedTokens Skipped; 1415 if (ConsumeAndStoreFunctionPrologue(Skipped)) 1416 SkipMalformedDecl(); 1417 else { 1418 SkipUntil(tok::r_brace); 1419 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) { 1420 SkipUntil(tok::l_brace); 1421 SkipUntil(tok::r_brace); 1422 } 1423 } 1424 } 1425 1426 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides 1427 /// types for a function with a K&R-style identifier list for arguments. 1428 void Parser::ParseKNRParamDeclarations(Declarator &D) { 1429 // We know that the top-level of this declarator is a function. 1430 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 1431 1432 // Enter function-declaration scope, limiting any declarators to the 1433 // function prototype scope, including parameter declarators. 1434 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | 1435 Scope::FunctionDeclarationScope | Scope::DeclScope); 1436 1437 // Read all the argument declarations. 1438 while (isDeclarationSpecifier()) { 1439 SourceLocation DSStart = Tok.getLocation(); 1440 1441 // Parse the common declaration-specifiers piece. 1442 DeclSpec DS(AttrFactory); 1443 ParseDeclarationSpecifiers(DS); 1444 1445 // C99 6.9.1p6: 'each declaration in the declaration list shall have at 1446 // least one declarator'. 1447 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with 1448 // the declarations though. It's trivial to ignore them, really hard to do 1449 // anything else with them. 1450 if (TryConsumeToken(tok::semi)) { 1451 Diag(DSStart, diag::err_declaration_does_not_declare_param); 1452 continue; 1453 } 1454 1455 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other 1456 // than register. 1457 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1458 DS.getStorageClassSpec() != DeclSpec::SCS_register) { 1459 Diag(DS.getStorageClassSpecLoc(), 1460 diag::err_invalid_storage_class_in_func_decl); 1461 DS.ClearStorageClassSpecs(); 1462 } 1463 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) { 1464 Diag(DS.getThreadStorageClassSpecLoc(), 1465 diag::err_invalid_storage_class_in_func_decl); 1466 DS.ClearStorageClassSpecs(); 1467 } 1468 1469 // Parse the first declarator attached to this declspec. 1470 Declarator ParmDeclarator(DS, DeclaratorContext::KNRTypeList); 1471 ParseDeclarator(ParmDeclarator); 1472 1473 // Handle the full declarator list. 1474 while (true) { 1475 // If attributes are present, parse them. 1476 MaybeParseGNUAttributes(ParmDeclarator); 1477 1478 // Ask the actions module to compute the type for this declarator. 1479 Decl *Param = 1480 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 1481 1482 if (Param && 1483 // A missing identifier has already been diagnosed. 1484 ParmDeclarator.getIdentifier()) { 1485 1486 // Scan the argument list looking for the correct param to apply this 1487 // type. 1488 for (unsigned i = 0; ; ++i) { 1489 // C99 6.9.1p6: those declarators shall declare only identifiers from 1490 // the identifier list. 1491 if (i == FTI.NumParams) { 1492 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param) 1493 << ParmDeclarator.getIdentifier(); 1494 break; 1495 } 1496 1497 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) { 1498 // Reject redefinitions of parameters. 1499 if (FTI.Params[i].Param) { 1500 Diag(ParmDeclarator.getIdentifierLoc(), 1501 diag::err_param_redefinition) 1502 << ParmDeclarator.getIdentifier(); 1503 } else { 1504 FTI.Params[i].Param = Param; 1505 } 1506 break; 1507 } 1508 } 1509 } 1510 1511 // If we don't have a comma, it is either the end of the list (a ';') or 1512 // an error, bail out. 1513 if (Tok.isNot(tok::comma)) 1514 break; 1515 1516 ParmDeclarator.clear(); 1517 1518 // Consume the comma. 1519 ParmDeclarator.setCommaLoc(ConsumeToken()); 1520 1521 // Parse the next declarator. 1522 ParseDeclarator(ParmDeclarator); 1523 } 1524 1525 // Consume ';' and continue parsing. 1526 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) 1527 continue; 1528 1529 // Otherwise recover by skipping to next semi or mandatory function body. 1530 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch)) 1531 break; 1532 TryConsumeToken(tok::semi); 1533 } 1534 1535 // The actions module must verify that all arguments were declared. 1536 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation()); 1537 } 1538 1539 1540 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not 1541 /// allowed to be a wide string, and is not subject to character translation. 1542 /// Unlike GCC, we also diagnose an empty string literal when parsing for an 1543 /// asm label as opposed to an asm statement, because such a construct does not 1544 /// behave well. 1545 /// 1546 /// [GNU] asm-string-literal: 1547 /// string-literal 1548 /// 1549 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) { 1550 if (!isTokenStringLiteral()) { 1551 Diag(Tok, diag::err_expected_string_literal) 1552 << /*Source='in...'*/0 << "'asm'"; 1553 return ExprError(); 1554 } 1555 1556 ExprResult AsmString(ParseStringLiteralExpression()); 1557 if (!AsmString.isInvalid()) { 1558 const auto *SL = cast<StringLiteral>(AsmString.get()); 1559 if (!SL->isAscii()) { 1560 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1561 << SL->isWide() 1562 << SL->getSourceRange(); 1563 return ExprError(); 1564 } 1565 if (ForAsmLabel && SL->getString().empty()) { 1566 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1567 << 2 /* an empty */ << SL->getSourceRange(); 1568 return ExprError(); 1569 } 1570 } 1571 return AsmString; 1572 } 1573 1574 /// ParseSimpleAsm 1575 /// 1576 /// [GNU] simple-asm-expr: 1577 /// 'asm' '(' asm-string-literal ')' 1578 /// 1579 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) { 1580 assert(Tok.is(tok::kw_asm) && "Not an asm!"); 1581 SourceLocation Loc = ConsumeToken(); 1582 1583 if (isGNUAsmQualifier(Tok)) { 1584 // Remove from the end of 'asm' to the end of the asm qualifier. 1585 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc), 1586 PP.getLocForEndOfToken(Tok.getLocation())); 1587 Diag(Tok, diag::err_global_asm_qualifier_ignored) 1588 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok)) 1589 << FixItHint::CreateRemoval(RemovalRange); 1590 ConsumeToken(); 1591 } 1592 1593 BalancedDelimiterTracker T(*this, tok::l_paren); 1594 if (T.consumeOpen()) { 1595 Diag(Tok, diag::err_expected_lparen_after) << "asm"; 1596 return ExprError(); 1597 } 1598 1599 ExprResult Result(ParseAsmStringLiteral(ForAsmLabel)); 1600 1601 if (!Result.isInvalid()) { 1602 // Close the paren and get the location of the end bracket 1603 T.consumeClose(); 1604 if (EndLoc) 1605 *EndLoc = T.getCloseLocation(); 1606 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) { 1607 if (EndLoc) 1608 *EndLoc = Tok.getLocation(); 1609 ConsumeParen(); 1610 } 1611 1612 return Result; 1613 } 1614 1615 /// Get the TemplateIdAnnotation from the token and put it in the 1616 /// cleanup pool so that it gets destroyed when parsing the current top level 1617 /// declaration is finished. 1618 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) { 1619 assert(tok.is(tok::annot_template_id) && "Expected template-id token"); 1620 TemplateIdAnnotation * 1621 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue()); 1622 return Id; 1623 } 1624 1625 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) { 1626 // Push the current token back into the token stream (or revert it if it is 1627 // cached) and use an annotation scope token for current token. 1628 if (PP.isBacktrackEnabled()) 1629 PP.RevertCachedTokens(1); 1630 else 1631 PP.EnterToken(Tok, /*IsReinject=*/true); 1632 Tok.setKind(tok::annot_cxxscope); 1633 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1634 Tok.setAnnotationRange(SS.getRange()); 1635 1636 // In case the tokens were cached, have Preprocessor replace them 1637 // with the annotation token. We don't need to do this if we've 1638 // just reverted back to a prior state. 1639 if (IsNewAnnotation) 1640 PP.AnnotateCachedTokens(Tok); 1641 } 1642 1643 /// Attempt to classify the name at the current token position. This may 1644 /// form a type, scope or primary expression annotation, or replace the token 1645 /// with a typo-corrected keyword. This is only appropriate when the current 1646 /// name must refer to an entity which has already been declared. 1647 /// 1648 /// \param CCC Indicates how to perform typo-correction for this name. If NULL, 1649 /// no typo correction will be performed. 1650 Parser::AnnotatedNameKind 1651 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC) { 1652 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope)); 1653 1654 const bool EnteringContext = false; 1655 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1656 1657 CXXScopeSpec SS; 1658 if (getLangOpts().CPlusPlus && 1659 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1660 /*ObjectHasErrors=*/false, 1661 EnteringContext)) 1662 return ANK_Error; 1663 1664 if (Tok.isNot(tok::identifier) || SS.isInvalid()) { 1665 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation)) 1666 return ANK_Error; 1667 return ANK_Unresolved; 1668 } 1669 1670 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1671 SourceLocation NameLoc = Tok.getLocation(); 1672 1673 // FIXME: Move the tentative declaration logic into ClassifyName so we can 1674 // typo-correct to tentatively-declared identifiers. 1675 if (isTentativelyDeclared(Name)) { 1676 // Identifier has been tentatively declared, and thus cannot be resolved as 1677 // an expression. Fall back to annotating it as a type. 1678 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation)) 1679 return ANK_Error; 1680 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl; 1681 } 1682 1683 Token Next = NextToken(); 1684 1685 // Look up and classify the identifier. We don't perform any typo-correction 1686 // after a scope specifier, because in general we can't recover from typos 1687 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to 1688 // jump back into scope specifier parsing). 1689 Sema::NameClassification Classification = Actions.ClassifyName( 1690 getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr); 1691 1692 // If name lookup found nothing and we guessed that this was a template name, 1693 // double-check before committing to that interpretation. C++20 requires that 1694 // we interpret this as a template-id if it can be, but if it can't be, then 1695 // this is an error recovery case. 1696 if (Classification.getKind() == Sema::NC_UndeclaredTemplate && 1697 isTemplateArgumentList(1) == TPResult::False) { 1698 // It's not a template-id; re-classify without the '<' as a hint. 1699 Token FakeNext = Next; 1700 FakeNext.setKind(tok::unknown); 1701 Classification = 1702 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext, 1703 SS.isEmpty() ? CCC : nullptr); 1704 } 1705 1706 switch (Classification.getKind()) { 1707 case Sema::NC_Error: 1708 return ANK_Error; 1709 1710 case Sema::NC_Keyword: 1711 // The identifier was typo-corrected to a keyword. 1712 Tok.setIdentifierInfo(Name); 1713 Tok.setKind(Name->getTokenID()); 1714 PP.TypoCorrectToken(Tok); 1715 if (SS.isNotEmpty()) 1716 AnnotateScopeToken(SS, !WasScopeAnnotation); 1717 // We've "annotated" this as a keyword. 1718 return ANK_Success; 1719 1720 case Sema::NC_Unknown: 1721 // It's not something we know about. Leave it unannotated. 1722 break; 1723 1724 case Sema::NC_Type: { 1725 if (TryAltiVecVectorToken()) 1726 // vector has been found as a type id when altivec is enabled but 1727 // this is followed by a declaration specifier so this is really the 1728 // altivec vector token. Leave it unannotated. 1729 break; 1730 SourceLocation BeginLoc = NameLoc; 1731 if (SS.isNotEmpty()) 1732 BeginLoc = SS.getBeginLoc(); 1733 1734 /// An Objective-C object type followed by '<' is a specialization of 1735 /// a parameterized class type or a protocol-qualified type. 1736 ParsedType Ty = Classification.getType(); 1737 if (getLangOpts().ObjC && NextToken().is(tok::less) && 1738 (Ty.get()->isObjCObjectType() || 1739 Ty.get()->isObjCObjectPointerType())) { 1740 // Consume the name. 1741 SourceLocation IdentifierLoc = ConsumeToken(); 1742 SourceLocation NewEndLoc; 1743 TypeResult NewType 1744 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, 1745 /*consumeLastToken=*/false, 1746 NewEndLoc); 1747 if (NewType.isUsable()) 1748 Ty = NewType.get(); 1749 else if (Tok.is(tok::eof)) // Nothing to do here, bail out... 1750 return ANK_Error; 1751 } 1752 1753 Tok.setKind(tok::annot_typename); 1754 setTypeAnnotation(Tok, Ty); 1755 Tok.setAnnotationEndLoc(Tok.getLocation()); 1756 Tok.setLocation(BeginLoc); 1757 PP.AnnotateCachedTokens(Tok); 1758 return ANK_Success; 1759 } 1760 1761 case Sema::NC_OverloadSet: 1762 Tok.setKind(tok::annot_overload_set); 1763 setExprAnnotation(Tok, Classification.getExpression()); 1764 Tok.setAnnotationEndLoc(NameLoc); 1765 if (SS.isNotEmpty()) 1766 Tok.setLocation(SS.getBeginLoc()); 1767 PP.AnnotateCachedTokens(Tok); 1768 return ANK_Success; 1769 1770 case Sema::NC_NonType: 1771 if (TryAltiVecVectorToken()) 1772 // vector has been found as a non-type id when altivec is enabled but 1773 // this is followed by a declaration specifier so this is really the 1774 // altivec vector token. Leave it unannotated. 1775 break; 1776 Tok.setKind(tok::annot_non_type); 1777 setNonTypeAnnotation(Tok, Classification.getNonTypeDecl()); 1778 Tok.setLocation(NameLoc); 1779 Tok.setAnnotationEndLoc(NameLoc); 1780 PP.AnnotateCachedTokens(Tok); 1781 if (SS.isNotEmpty()) 1782 AnnotateScopeToken(SS, !WasScopeAnnotation); 1783 return ANK_Success; 1784 1785 case Sema::NC_UndeclaredNonType: 1786 case Sema::NC_DependentNonType: 1787 Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType 1788 ? tok::annot_non_type_undeclared 1789 : tok::annot_non_type_dependent); 1790 setIdentifierAnnotation(Tok, Name); 1791 Tok.setLocation(NameLoc); 1792 Tok.setAnnotationEndLoc(NameLoc); 1793 PP.AnnotateCachedTokens(Tok); 1794 if (SS.isNotEmpty()) 1795 AnnotateScopeToken(SS, !WasScopeAnnotation); 1796 return ANK_Success; 1797 1798 case Sema::NC_TypeTemplate: 1799 if (Next.isNot(tok::less)) { 1800 // This may be a type template being used as a template template argument. 1801 if (SS.isNotEmpty()) 1802 AnnotateScopeToken(SS, !WasScopeAnnotation); 1803 return ANK_TemplateName; 1804 } 1805 LLVM_FALLTHROUGH; 1806 case Sema::NC_VarTemplate: 1807 case Sema::NC_FunctionTemplate: 1808 case Sema::NC_UndeclaredTemplate: { 1809 // We have a type, variable or function template followed by '<'. 1810 ConsumeToken(); 1811 UnqualifiedId Id; 1812 Id.setIdentifier(Name, NameLoc); 1813 if (AnnotateTemplateIdToken( 1814 TemplateTy::make(Classification.getTemplateName()), 1815 Classification.getTemplateNameKind(), SS, SourceLocation(), Id)) 1816 return ANK_Error; 1817 return ANK_Success; 1818 } 1819 case Sema::NC_Concept: { 1820 UnqualifiedId Id; 1821 Id.setIdentifier(Name, NameLoc); 1822 if (Next.is(tok::less)) 1823 // We have a concept name followed by '<'. Consume the identifier token so 1824 // we reach the '<' and annotate it. 1825 ConsumeToken(); 1826 if (AnnotateTemplateIdToken( 1827 TemplateTy::make(Classification.getTemplateName()), 1828 Classification.getTemplateNameKind(), SS, SourceLocation(), Id, 1829 /*AllowTypeAnnotation=*/false, /*TypeConstraint=*/true)) 1830 return ANK_Error; 1831 return ANK_Success; 1832 } 1833 } 1834 1835 // Unable to classify the name, but maybe we can annotate a scope specifier. 1836 if (SS.isNotEmpty()) 1837 AnnotateScopeToken(SS, !WasScopeAnnotation); 1838 return ANK_Unresolved; 1839 } 1840 1841 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) { 1842 assert(Tok.isNot(tok::identifier)); 1843 Diag(Tok, diag::ext_keyword_as_ident) 1844 << PP.getSpelling(Tok) 1845 << DisableKeyword; 1846 if (DisableKeyword) 1847 Tok.getIdentifierInfo()->revertTokenIDToIdentifier(); 1848 Tok.setKind(tok::identifier); 1849 return true; 1850 } 1851 1852 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 1853 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 1854 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 1855 /// with a single annotation token representing the typename or C++ scope 1856 /// respectively. 1857 /// This simplifies handling of C++ scope specifiers and allows efficient 1858 /// backtracking without the need to re-parse and resolve nested-names and 1859 /// typenames. 1860 /// It will mainly be called when we expect to treat identifiers as typenames 1861 /// (if they are typenames). For example, in C we do not expect identifiers 1862 /// inside expressions to be treated as typenames so it will not be called 1863 /// for expressions in C. 1864 /// The benefit for C/ObjC is that a typename will be annotated and 1865 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName 1866 /// will not be called twice, once to check whether we have a declaration 1867 /// specifier, and another one to get the actual type inside 1868 /// ParseDeclarationSpecifiers). 1869 /// 1870 /// This returns true if an error occurred. 1871 /// 1872 /// Note that this routine emits an error if you call it with ::new or ::delete 1873 /// as the current tokens, so only call it in contexts where these are invalid. 1874 bool Parser::TryAnnotateTypeOrScopeToken() { 1875 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 1876 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) || 1877 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) || 1878 Tok.is(tok::kw___super)) && 1879 "Cannot be a type or scope token!"); 1880 1881 if (Tok.is(tok::kw_typename)) { 1882 // MSVC lets you do stuff like: 1883 // typename typedef T_::D D; 1884 // 1885 // We will consume the typedef token here and put it back after we have 1886 // parsed the first identifier, transforming it into something more like: 1887 // typename T_::D typedef D; 1888 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) { 1889 Token TypedefToken; 1890 PP.Lex(TypedefToken); 1891 bool Result = TryAnnotateTypeOrScopeToken(); 1892 PP.EnterToken(Tok, /*IsReinject=*/true); 1893 Tok = TypedefToken; 1894 if (!Result) 1895 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename); 1896 return Result; 1897 } 1898 1899 // Parse a C++ typename-specifier, e.g., "typename T::type". 1900 // 1901 // typename-specifier: 1902 // 'typename' '::' [opt] nested-name-specifier identifier 1903 // 'typename' '::' [opt] nested-name-specifier template [opt] 1904 // simple-template-id 1905 SourceLocation TypenameLoc = ConsumeToken(); 1906 CXXScopeSpec SS; 1907 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1908 /*ObjectHasErrors=*/false, 1909 /*EnteringContext=*/false, nullptr, 1910 /*IsTypename*/ true)) 1911 return true; 1912 if (SS.isEmpty()) { 1913 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) || 1914 Tok.is(tok::annot_decltype)) { 1915 // Attempt to recover by skipping the invalid 'typename' 1916 if (Tok.is(tok::annot_decltype) || 1917 (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) { 1918 unsigned DiagID = diag::err_expected_qualified_after_typename; 1919 // MS compatibility: MSVC permits using known types with typename. 1920 // e.g. "typedef typename T* pointer_type" 1921 if (getLangOpts().MicrosoftExt) 1922 DiagID = diag::warn_expected_qualified_after_typename; 1923 Diag(Tok.getLocation(), DiagID); 1924 return false; 1925 } 1926 } 1927 if (Tok.isEditorPlaceholder()) 1928 return true; 1929 1930 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); 1931 return true; 1932 } 1933 1934 TypeResult Ty; 1935 if (Tok.is(tok::identifier)) { 1936 // FIXME: check whether the next token is '<', first! 1937 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1938 *Tok.getIdentifierInfo(), 1939 Tok.getLocation()); 1940 } else if (Tok.is(tok::annot_template_id)) { 1941 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1942 if (!TemplateId->mightBeType()) { 1943 Diag(Tok, diag::err_typename_refers_to_non_type_template) 1944 << Tok.getAnnotationRange(); 1945 return true; 1946 } 1947 1948 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1949 TemplateId->NumArgs); 1950 1951 Ty = TemplateId->isInvalid() 1952 ? TypeError() 1953 : Actions.ActOnTypenameType( 1954 getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc, 1955 TemplateId->Template, TemplateId->Name, 1956 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, 1957 TemplateArgsPtr, TemplateId->RAngleLoc); 1958 } else { 1959 Diag(Tok, diag::err_expected_type_name_after_typename) 1960 << SS.getRange(); 1961 return true; 1962 } 1963 1964 SourceLocation EndLoc = Tok.getLastLoc(); 1965 Tok.setKind(tok::annot_typename); 1966 setTypeAnnotation(Tok, Ty); 1967 Tok.setAnnotationEndLoc(EndLoc); 1968 Tok.setLocation(TypenameLoc); 1969 PP.AnnotateCachedTokens(Tok); 1970 return false; 1971 } 1972 1973 // Remembers whether the token was originally a scope annotation. 1974 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1975 1976 CXXScopeSpec SS; 1977 if (getLangOpts().CPlusPlus) 1978 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1979 /*ObjectHasErrors=*/false, 1980 /*EnteringContext*/ false)) 1981 return true; 1982 1983 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation); 1984 } 1985 1986 /// Try to annotate a type or scope token, having already parsed an 1987 /// optional scope specifier. \p IsNewScope should be \c true unless the scope 1988 /// specifier was extracted from an existing tok::annot_cxxscope annotation. 1989 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, 1990 bool IsNewScope) { 1991 if (Tok.is(tok::identifier)) { 1992 // Determine whether the identifier is a type name. 1993 if (ParsedType Ty = Actions.getTypeName( 1994 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS, 1995 false, NextToken().is(tok::period), nullptr, 1996 /*IsCtorOrDtorName=*/false, 1997 /*NonTrivialTypeSourceInfo*/true, 1998 /*IsClassTemplateDeductionContext*/true)) { 1999 SourceLocation BeginLoc = Tok.getLocation(); 2000 if (SS.isNotEmpty()) // it was a C++ qualified type name. 2001 BeginLoc = SS.getBeginLoc(); 2002 2003 /// An Objective-C object type followed by '<' is a specialization of 2004 /// a parameterized class type or a protocol-qualified type. 2005 if (getLangOpts().ObjC && NextToken().is(tok::less) && 2006 (Ty.get()->isObjCObjectType() || 2007 Ty.get()->isObjCObjectPointerType())) { 2008 // Consume the name. 2009 SourceLocation IdentifierLoc = ConsumeToken(); 2010 SourceLocation NewEndLoc; 2011 TypeResult NewType 2012 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, 2013 /*consumeLastToken=*/false, 2014 NewEndLoc); 2015 if (NewType.isUsable()) 2016 Ty = NewType.get(); 2017 else if (Tok.is(tok::eof)) // Nothing to do here, bail out... 2018 return false; 2019 } 2020 2021 // This is a typename. Replace the current token in-place with an 2022 // annotation type token. 2023 Tok.setKind(tok::annot_typename); 2024 setTypeAnnotation(Tok, Ty); 2025 Tok.setAnnotationEndLoc(Tok.getLocation()); 2026 Tok.setLocation(BeginLoc); 2027 2028 // In case the tokens were cached, have Preprocessor replace 2029 // them with the annotation token. 2030 PP.AnnotateCachedTokens(Tok); 2031 return false; 2032 } 2033 2034 if (!getLangOpts().CPlusPlus) { 2035 // If we're in C, we can't have :: tokens at all (the lexer won't return 2036 // them). If the identifier is not a type, then it can't be scope either, 2037 // just early exit. 2038 return false; 2039 } 2040 2041 // If this is a template-id, annotate with a template-id or type token. 2042 // FIXME: This appears to be dead code. We already have formed template-id 2043 // tokens when parsing the scope specifier; this can never form a new one. 2044 if (NextToken().is(tok::less)) { 2045 TemplateTy Template; 2046 UnqualifiedId TemplateName; 2047 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 2048 bool MemberOfUnknownSpecialization; 2049 if (TemplateNameKind TNK = Actions.isTemplateName( 2050 getCurScope(), SS, 2051 /*hasTemplateKeyword=*/false, TemplateName, 2052 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template, 2053 MemberOfUnknownSpecialization)) { 2054 // Only annotate an undeclared template name as a template-id if the 2055 // following tokens have the form of a template argument list. 2056 if (TNK != TNK_Undeclared_template || 2057 isTemplateArgumentList(1) != TPResult::False) { 2058 // Consume the identifier. 2059 ConsumeToken(); 2060 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 2061 TemplateName)) { 2062 // If an unrecoverable error occurred, we need to return true here, 2063 // because the token stream is in a damaged state. We may not 2064 // return a valid identifier. 2065 return true; 2066 } 2067 } 2068 } 2069 } 2070 2071 // The current token, which is either an identifier or a 2072 // template-id, is not part of the annotation. Fall through to 2073 // push that token back into the stream and complete the C++ scope 2074 // specifier annotation. 2075 } 2076 2077 if (Tok.is(tok::annot_template_id)) { 2078 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2079 if (TemplateId->Kind == TNK_Type_template) { 2080 // A template-id that refers to a type was parsed into a 2081 // template-id annotation in a context where we weren't allowed 2082 // to produce a type annotation token. Update the template-id 2083 // annotation token to a type annotation token now. 2084 AnnotateTemplateIdTokenAsType(SS); 2085 return false; 2086 } 2087 } 2088 2089 if (SS.isEmpty()) 2090 return false; 2091 2092 // A C++ scope specifier that isn't followed by a typename. 2093 AnnotateScopeToken(SS, IsNewScope); 2094 return false; 2095 } 2096 2097 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only 2098 /// annotates C++ scope specifiers and template-ids. This returns 2099 /// true if there was an error that could not be recovered from. 2100 /// 2101 /// Note that this routine emits an error if you call it with ::new or ::delete 2102 /// as the current tokens, so only call it in contexts where these are invalid. 2103 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { 2104 assert(getLangOpts().CPlusPlus && 2105 "Call sites of this function should be guarded by checking for C++"); 2106 assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!"); 2107 2108 CXXScopeSpec SS; 2109 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 2110 /*ObjectHasErrors=*/false, 2111 EnteringContext)) 2112 return true; 2113 if (SS.isEmpty()) 2114 return false; 2115 2116 AnnotateScopeToken(SS, true); 2117 return false; 2118 } 2119 2120 bool Parser::isTokenEqualOrEqualTypo() { 2121 tok::TokenKind Kind = Tok.getKind(); 2122 switch (Kind) { 2123 default: 2124 return false; 2125 case tok::ampequal: // &= 2126 case tok::starequal: // *= 2127 case tok::plusequal: // += 2128 case tok::minusequal: // -= 2129 case tok::exclaimequal: // != 2130 case tok::slashequal: // /= 2131 case tok::percentequal: // %= 2132 case tok::lessequal: // <= 2133 case tok::lesslessequal: // <<= 2134 case tok::greaterequal: // >= 2135 case tok::greatergreaterequal: // >>= 2136 case tok::caretequal: // ^= 2137 case tok::pipeequal: // |= 2138 case tok::equalequal: // == 2139 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal) 2140 << Kind 2141 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "="); 2142 LLVM_FALLTHROUGH; 2143 case tok::equal: 2144 return true; 2145 } 2146 } 2147 2148 SourceLocation Parser::handleUnexpectedCodeCompletionToken() { 2149 assert(Tok.is(tok::code_completion)); 2150 PrevTokLocation = Tok.getLocation(); 2151 2152 for (Scope *S = getCurScope(); S; S = S->getParent()) { 2153 if (S->getFlags() & Scope::FnScope) { 2154 cutOffParsing(); 2155 Actions.CodeCompleteOrdinaryName(getCurScope(), 2156 Sema::PCC_RecoveryInFunction); 2157 return PrevTokLocation; 2158 } 2159 2160 if (S->getFlags() & Scope::ClassScope) { 2161 cutOffParsing(); 2162 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); 2163 return PrevTokLocation; 2164 } 2165 } 2166 2167 cutOffParsing(); 2168 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); 2169 return PrevTokLocation; 2170 } 2171 2172 // Code-completion pass-through functions 2173 2174 void Parser::CodeCompleteDirective(bool InConditional) { 2175 Actions.CodeCompletePreprocessorDirective(InConditional); 2176 } 2177 2178 void Parser::CodeCompleteInConditionalExclusion() { 2179 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope()); 2180 } 2181 2182 void Parser::CodeCompleteMacroName(bool IsDefinition) { 2183 Actions.CodeCompletePreprocessorMacroName(IsDefinition); 2184 } 2185 2186 void Parser::CodeCompletePreprocessorExpression() { 2187 Actions.CodeCompletePreprocessorExpression(); 2188 } 2189 2190 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro, 2191 MacroInfo *MacroInfo, 2192 unsigned ArgumentIndex) { 2193 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 2194 ArgumentIndex); 2195 } 2196 2197 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) { 2198 Actions.CodeCompleteIncludedFile(Dir, IsAngled); 2199 } 2200 2201 void Parser::CodeCompleteNaturalLanguage() { 2202 Actions.CodeCompleteNaturalLanguage(); 2203 } 2204 2205 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { 2206 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) && 2207 "Expected '__if_exists' or '__if_not_exists'"); 2208 Result.IsIfExists = Tok.is(tok::kw___if_exists); 2209 Result.KeywordLoc = ConsumeToken(); 2210 2211 BalancedDelimiterTracker T(*this, tok::l_paren); 2212 if (T.consumeOpen()) { 2213 Diag(Tok, diag::err_expected_lparen_after) 2214 << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); 2215 return true; 2216 } 2217 2218 // Parse nested-name-specifier. 2219 if (getLangOpts().CPlusPlus) 2220 ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr, 2221 /*ObjectHasErrors=*/false, 2222 /*EnteringContext=*/false); 2223 2224 // Check nested-name specifier. 2225 if (Result.SS.isInvalid()) { 2226 T.skipToEnd(); 2227 return true; 2228 } 2229 2230 // Parse the unqualified-id. 2231 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused. 2232 if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr, 2233 /*ObjectHadErrors=*/false, /*EnteringContext*/ false, 2234 /*AllowDestructorName*/ true, 2235 /*AllowConstructorName*/ true, 2236 /*AllowDeductionGuide*/ false, &TemplateKWLoc, 2237 Result.Name)) { 2238 T.skipToEnd(); 2239 return true; 2240 } 2241 2242 if (T.consumeClose()) 2243 return true; 2244 2245 // Check if the symbol exists. 2246 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, 2247 Result.IsIfExists, Result.SS, 2248 Result.Name)) { 2249 case Sema::IER_Exists: 2250 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip; 2251 break; 2252 2253 case Sema::IER_DoesNotExist: 2254 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip; 2255 break; 2256 2257 case Sema::IER_Dependent: 2258 Result.Behavior = IEB_Dependent; 2259 break; 2260 2261 case Sema::IER_Error: 2262 return true; 2263 } 2264 2265 return false; 2266 } 2267 2268 void Parser::ParseMicrosoftIfExistsExternalDeclaration() { 2269 IfExistsCondition Result; 2270 if (ParseMicrosoftIfExistsCondition(Result)) 2271 return; 2272 2273 BalancedDelimiterTracker Braces(*this, tok::l_brace); 2274 if (Braces.consumeOpen()) { 2275 Diag(Tok, diag::err_expected) << tok::l_brace; 2276 return; 2277 } 2278 2279 switch (Result.Behavior) { 2280 case IEB_Parse: 2281 // Parse declarations below. 2282 break; 2283 2284 case IEB_Dependent: 2285 llvm_unreachable("Cannot have a dependent external declaration"); 2286 2287 case IEB_Skip: 2288 Braces.skipToEnd(); 2289 return; 2290 } 2291 2292 // Parse the declarations. 2293 // FIXME: Support module import within __if_exists? 2294 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 2295 ParsedAttributesWithRange attrs(AttrFactory); 2296 MaybeParseCXX11Attributes(attrs); 2297 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs); 2298 if (Result && !getCurScope()->getParent()) 2299 Actions.getASTConsumer().HandleTopLevelDecl(Result.get()); 2300 } 2301 Braces.consumeClose(); 2302 } 2303 2304 /// Parse a declaration beginning with the 'module' keyword or C++20 2305 /// context-sensitive keyword (optionally preceded by 'export'). 2306 /// 2307 /// module-declaration: [Modules TS + P0629R0] 2308 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';' 2309 /// 2310 /// global-module-fragment: [C++2a] 2311 /// 'module' ';' top-level-declaration-seq[opt] 2312 /// module-declaration: [C++2a] 2313 /// 'export'[opt] 'module' module-name module-partition[opt] 2314 /// attribute-specifier-seq[opt] ';' 2315 /// private-module-fragment: [C++2a] 2316 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt] 2317 Parser::DeclGroupPtrTy 2318 Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) { 2319 SourceLocation StartLoc = Tok.getLocation(); 2320 2321 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export) 2322 ? Sema::ModuleDeclKind::Interface 2323 : Sema::ModuleDeclKind::Implementation; 2324 2325 assert( 2326 (Tok.is(tok::kw_module) || 2327 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) && 2328 "not a module declaration"); 2329 SourceLocation ModuleLoc = ConsumeToken(); 2330 2331 // Attributes appear after the module name, not before. 2332 // FIXME: Suggest moving the attributes later with a fixit. 2333 DiagnoseAndSkipCXX11Attributes(); 2334 2335 // Parse a global-module-fragment, if present. 2336 if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) { 2337 SourceLocation SemiLoc = ConsumeToken(); 2338 if (ImportState != Sema::ModuleImportState::FirstDecl) { 2339 Diag(StartLoc, diag::err_global_module_introducer_not_at_start) 2340 << SourceRange(StartLoc, SemiLoc); 2341 return nullptr; 2342 } 2343 if (MDK == Sema::ModuleDeclKind::Interface) { 2344 Diag(StartLoc, diag::err_module_fragment_exported) 2345 << /*global*/0 << FixItHint::CreateRemoval(StartLoc); 2346 } 2347 ImportState = Sema::ModuleImportState::GlobalFragment; 2348 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc); 2349 } 2350 2351 // Parse a private-module-fragment, if present. 2352 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) && 2353 NextToken().is(tok::kw_private)) { 2354 if (MDK == Sema::ModuleDeclKind::Interface) { 2355 Diag(StartLoc, diag::err_module_fragment_exported) 2356 << /*private*/1 << FixItHint::CreateRemoval(StartLoc); 2357 } 2358 ConsumeToken(); 2359 SourceLocation PrivateLoc = ConsumeToken(); 2360 DiagnoseAndSkipCXX11Attributes(); 2361 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi); 2362 ImportState = Sema::ModuleImportState::PrivateFragment; 2363 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc); 2364 } 2365 2366 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2367 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false)) 2368 return nullptr; 2369 2370 // Parse the optional module-partition. 2371 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition; 2372 if (Tok.is(tok::colon)) { 2373 SourceLocation ColonLoc = ConsumeToken(); 2374 if (!getLangOpts().CPlusPlusModules) 2375 Diag(ColonLoc, diag::err_unsupported_module_partition) 2376 << SourceRange(ColonLoc, Partition.back().second); 2377 // Recover by ignoring the partition name. 2378 else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false)) 2379 return nullptr; 2380 } 2381 2382 // We don't support any module attributes yet; just parse them and diagnose. 2383 ParsedAttributesWithRange Attrs(AttrFactory); 2384 MaybeParseCXX11Attributes(Attrs); 2385 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr); 2386 2387 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2388 2389 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition, 2390 ImportState); 2391 } 2392 2393 /// Parse a module import declaration. This is essentially the same for 2394 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the 2395 /// trailing optional attributes (in C++). 2396 /// 2397 /// [ObjC] @import declaration: 2398 /// '@' 'import' module-name ';' 2399 /// [ModTS] module-import-declaration: 2400 /// 'import' module-name attribute-specifier-seq[opt] ';' 2401 /// [C++20] module-import-declaration: 2402 /// 'export'[opt] 'import' module-name 2403 /// attribute-specifier-seq[opt] ';' 2404 /// 'export'[opt] 'import' module-partition 2405 /// attribute-specifier-seq[opt] ';' 2406 /// 'export'[opt] 'import' header-name 2407 /// attribute-specifier-seq[opt] ';' 2408 Decl *Parser::ParseModuleImport(SourceLocation AtLoc, 2409 Sema::ModuleImportState &ImportState) { 2410 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc; 2411 2412 SourceLocation ExportLoc; 2413 TryConsumeToken(tok::kw_export, ExportLoc); 2414 2415 assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier) 2416 : Tok.isObjCAtKeyword(tok::objc_import)) && 2417 "Improper start to module import"); 2418 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import); 2419 SourceLocation ImportLoc = ConsumeToken(); 2420 2421 // For C++20 modules, we can have "name" or ":Partition name" as valid input. 2422 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2423 bool IsPartition = false; 2424 Module *HeaderUnit = nullptr; 2425 if (Tok.is(tok::header_name)) { 2426 // This is a header import that the preprocessor decided we should skip 2427 // because it was malformed in some way. Parse and ignore it; it's already 2428 // been diagnosed. 2429 ConsumeToken(); 2430 } else if (Tok.is(tok::annot_header_unit)) { 2431 // This is a header import that the preprocessor mapped to a module import. 2432 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue()); 2433 ConsumeAnnotationToken(); 2434 } else if (Tok.is(tok::colon)) { 2435 SourceLocation ColonLoc = ConsumeToken(); 2436 if (!getLangOpts().CPlusPlusModules) 2437 Diag(ColonLoc, diag::err_unsupported_module_partition) 2438 << SourceRange(ColonLoc, Path.back().second); 2439 // Recover by leaving partition empty. 2440 else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true)) 2441 return nullptr; 2442 else 2443 IsPartition = true; 2444 } else { 2445 if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true)) 2446 return nullptr; 2447 } 2448 2449 ParsedAttributesWithRange Attrs(AttrFactory); 2450 MaybeParseCXX11Attributes(Attrs); 2451 // We don't support any module import attributes yet. 2452 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr); 2453 2454 if (PP.hadModuleLoaderFatalFailure()) { 2455 // With a fatal failure in the module loader, we abort parsing. 2456 cutOffParsing(); 2457 return nullptr; 2458 } 2459 2460 // Diagnose mis-imports. 2461 bool SeenError = true; 2462 switch (ImportState) { 2463 case Sema::ModuleImportState::ImportAllowed: 2464 SeenError = false; 2465 break; 2466 case Sema::ModuleImportState::FirstDecl: 2467 case Sema::ModuleImportState::NotACXX20Module: 2468 // We can only import a partition within a module purview. 2469 if (IsPartition) 2470 Diag(ImportLoc, diag::err_partition_import_outside_module); 2471 else 2472 SeenError = false; 2473 break; 2474 case Sema::ModuleImportState::GlobalFragment: 2475 // We can only have pre-processor directives in the global module 2476 // fragment. We can, however have a header unit import here. 2477 if (!HeaderUnit) 2478 Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 0; 2479 else 2480 SeenError = false; 2481 break; 2482 case Sema::ModuleImportState::ImportFinished: 2483 if (getLangOpts().CPlusPlusModules) 2484 Diag(ImportLoc, diag::err_import_not_allowed_here); 2485 else 2486 SeenError = false; 2487 break; 2488 case Sema::ModuleImportState::PrivateFragment: 2489 Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 1; 2490 break; 2491 } 2492 if (SeenError) { 2493 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2494 return nullptr; 2495 } 2496 2497 DeclResult Import; 2498 if (HeaderUnit) 2499 Import = 2500 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit); 2501 else if (!Path.empty()) 2502 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path, 2503 IsPartition); 2504 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2505 if (Import.isInvalid()) 2506 return nullptr; 2507 2508 // Using '@import' in framework headers requires modules to be enabled so that 2509 // the header is parseable. Emit a warning to make the user aware. 2510 if (IsObjCAtImport && AtLoc.isValid()) { 2511 auto &SrcMgr = PP.getSourceManager(); 2512 auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc)); 2513 if (FE && llvm::sys::path::parent_path(FE->getDir()->getName()) 2514 .endswith(".framework")) 2515 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header); 2516 } 2517 2518 return Import.get(); 2519 } 2520 2521 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same 2522 /// grammar). 2523 /// 2524 /// module-name: 2525 /// module-name-qualifier[opt] identifier 2526 /// module-name-qualifier: 2527 /// module-name-qualifier[opt] identifier '.' 2528 bool Parser::ParseModuleName( 2529 SourceLocation UseLoc, 2530 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, 2531 bool IsImport) { 2532 // Parse the module path. 2533 while (true) { 2534 if (!Tok.is(tok::identifier)) { 2535 if (Tok.is(tok::code_completion)) { 2536 cutOffParsing(); 2537 Actions.CodeCompleteModuleImport(UseLoc, Path); 2538 return true; 2539 } 2540 2541 Diag(Tok, diag::err_module_expected_ident) << IsImport; 2542 SkipUntil(tok::semi); 2543 return true; 2544 } 2545 2546 // Record this part of the module path. 2547 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); 2548 ConsumeToken(); 2549 2550 if (Tok.isNot(tok::period)) 2551 return false; 2552 2553 ConsumeToken(); 2554 } 2555 } 2556 2557 /// Try recover parser when module annotation appears where it must not 2558 /// be found. 2559 /// \returns false if the recover was successful and parsing may be continued, or 2560 /// true if parser must bail out to top level and handle the token there. 2561 bool Parser::parseMisplacedModuleImport() { 2562 while (true) { 2563 switch (Tok.getKind()) { 2564 case tok::annot_module_end: 2565 // If we recovered from a misplaced module begin, we expect to hit a 2566 // misplaced module end too. Stay in the current context when this 2567 // happens. 2568 if (MisplacedModuleBeginCount) { 2569 --MisplacedModuleBeginCount; 2570 Actions.ActOnModuleEnd(Tok.getLocation(), 2571 reinterpret_cast<Module *>( 2572 Tok.getAnnotationValue())); 2573 ConsumeAnnotationToken(); 2574 continue; 2575 } 2576 // Inform caller that recovery failed, the error must be handled at upper 2577 // level. This will generate the desired "missing '}' at end of module" 2578 // diagnostics on the way out. 2579 return true; 2580 case tok::annot_module_begin: 2581 // Recover by entering the module (Sema will diagnose). 2582 Actions.ActOnModuleBegin(Tok.getLocation(), 2583 reinterpret_cast<Module *>( 2584 Tok.getAnnotationValue())); 2585 ConsumeAnnotationToken(); 2586 ++MisplacedModuleBeginCount; 2587 continue; 2588 case tok::annot_module_include: 2589 // Module import found where it should not be, for instance, inside a 2590 // namespace. Recover by importing the module. 2591 Actions.ActOnModuleInclude(Tok.getLocation(), 2592 reinterpret_cast<Module *>( 2593 Tok.getAnnotationValue())); 2594 ConsumeAnnotationToken(); 2595 // If there is another module import, process it. 2596 continue; 2597 default: 2598 return false; 2599 } 2600 } 2601 return false; 2602 } 2603 2604 bool BalancedDelimiterTracker::diagnoseOverflow() { 2605 P.Diag(P.Tok, diag::err_bracket_depth_exceeded) 2606 << P.getLangOpts().BracketDepth; 2607 P.Diag(P.Tok, diag::note_bracket_depth); 2608 P.cutOffParsing(); 2609 return true; 2610 } 2611 2612 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, 2613 const char *Msg, 2614 tok::TokenKind SkipToTok) { 2615 LOpen = P.Tok.getLocation(); 2616 if (P.ExpectAndConsume(Kind, DiagID, Msg)) { 2617 if (SkipToTok != tok::unknown) 2618 P.SkipUntil(SkipToTok, Parser::StopAtSemi); 2619 return true; 2620 } 2621 2622 if (getDepth() < P.getLangOpts().BracketDepth) 2623 return false; 2624 2625 return diagnoseOverflow(); 2626 } 2627 2628 bool BalancedDelimiterTracker::diagnoseMissingClose() { 2629 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter"); 2630 2631 if (P.Tok.is(tok::annot_module_end)) 2632 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close; 2633 else 2634 P.Diag(P.Tok, diag::err_expected) << Close; 2635 P.Diag(LOpen, diag::note_matching) << Kind; 2636 2637 // If we're not already at some kind of closing bracket, skip to our closing 2638 // token. 2639 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) && 2640 P.Tok.isNot(tok::r_square) && 2641 P.SkipUntil(Close, FinalToken, 2642 Parser::StopAtSemi | Parser::StopBeforeMatch) && 2643 P.Tok.is(Close)) 2644 LClose = P.ConsumeAnyToken(); 2645 return true; 2646 } 2647 2648 void BalancedDelimiterTracker::skipToEnd() { 2649 P.SkipUntil(Close, Parser::StopBeforeMatch); 2650 consumeClose(); 2651 } 2652