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