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