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