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