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(&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 /// 1471 /// [GNU] asm-string-literal: 1472 /// string-literal 1473 /// 1474 ExprResult Parser::ParseAsmStringLiteral() { 1475 if (!isTokenStringLiteral()) { 1476 Diag(Tok, diag::err_expected_string_literal) 1477 << /*Source='in...'*/0 << "'asm'"; 1478 return ExprError(); 1479 } 1480 1481 ExprResult AsmString(ParseStringLiteralExpression()); 1482 if (!AsmString.isInvalid()) { 1483 const auto *SL = cast<StringLiteral>(AsmString.get()); 1484 if (!SL->isAscii()) { 1485 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1486 << SL->isWide() 1487 << SL->getSourceRange(); 1488 return ExprError(); 1489 } 1490 } 1491 return AsmString; 1492 } 1493 1494 /// ParseSimpleAsm 1495 /// 1496 /// [GNU] simple-asm-expr: 1497 /// 'asm' '(' asm-string-literal ')' 1498 /// 1499 ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) { 1500 assert(Tok.is(tok::kw_asm) && "Not an asm!"); 1501 SourceLocation Loc = ConsumeToken(); 1502 1503 if (Tok.is(tok::kw_volatile)) { 1504 // Remove from the end of 'asm' to the end of 'volatile'. 1505 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc), 1506 PP.getLocForEndOfToken(Tok.getLocation())); 1507 1508 Diag(Tok, diag::warn_file_asm_volatile) 1509 << FixItHint::CreateRemoval(RemovalRange); 1510 ConsumeToken(); 1511 } 1512 1513 BalancedDelimiterTracker T(*this, tok::l_paren); 1514 if (T.consumeOpen()) { 1515 Diag(Tok, diag::err_expected_lparen_after) << "asm"; 1516 return ExprError(); 1517 } 1518 1519 ExprResult Result(ParseAsmStringLiteral()); 1520 1521 if (!Result.isInvalid()) { 1522 // Close the paren and get the location of the end bracket 1523 T.consumeClose(); 1524 if (EndLoc) 1525 *EndLoc = T.getCloseLocation(); 1526 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) { 1527 if (EndLoc) 1528 *EndLoc = Tok.getLocation(); 1529 ConsumeParen(); 1530 } 1531 1532 return Result; 1533 } 1534 1535 /// Get the TemplateIdAnnotation from the token and put it in the 1536 /// cleanup pool so that it gets destroyed when parsing the current top level 1537 /// declaration is finished. 1538 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) { 1539 assert(tok.is(tok::annot_template_id) && "Expected template-id token"); 1540 TemplateIdAnnotation * 1541 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue()); 1542 return Id; 1543 } 1544 1545 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) { 1546 // Push the current token back into the token stream (or revert it if it is 1547 // cached) and use an annotation scope token for current token. 1548 if (PP.isBacktrackEnabled()) 1549 PP.RevertCachedTokens(1); 1550 else 1551 PP.EnterToken(Tok, /*IsReinject=*/true); 1552 Tok.setKind(tok::annot_cxxscope); 1553 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1554 Tok.setAnnotationRange(SS.getRange()); 1555 1556 // In case the tokens were cached, have Preprocessor replace them 1557 // with the annotation token. We don't need to do this if we've 1558 // just reverted back to a prior state. 1559 if (IsNewAnnotation) 1560 PP.AnnotateCachedTokens(Tok); 1561 } 1562 1563 /// Attempt to classify the name at the current token position. This may 1564 /// form a type, scope or primary expression annotation, or replace the token 1565 /// with a typo-corrected keyword. This is only appropriate when the current 1566 /// name must refer to an entity which has already been declared. 1567 /// 1568 /// \param CCC Indicates how to perform typo-correction for this name. If NULL, 1569 /// no typo correction will be performed. 1570 Parser::AnnotatedNameKind 1571 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC) { 1572 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope)); 1573 1574 const bool EnteringContext = false; 1575 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1576 1577 CXXScopeSpec SS; 1578 if (getLangOpts().CPlusPlus && 1579 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext)) 1580 return ANK_Error; 1581 1582 if (Tok.isNot(tok::identifier) || SS.isInvalid()) { 1583 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation)) 1584 return ANK_Error; 1585 return ANK_Unresolved; 1586 } 1587 1588 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1589 SourceLocation NameLoc = Tok.getLocation(); 1590 1591 // FIXME: Move the tentative declaration logic into ClassifyName so we can 1592 // typo-correct to tentatively-declared identifiers. 1593 if (isTentativelyDeclared(Name)) { 1594 // Identifier has been tentatively declared, and thus cannot be resolved as 1595 // an expression. Fall back to annotating it as a type. 1596 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation)) 1597 return ANK_Error; 1598 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl; 1599 } 1600 1601 Token Next = NextToken(); 1602 1603 // Look up and classify the identifier. We don't perform any typo-correction 1604 // after a scope specifier, because in general we can't recover from typos 1605 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to 1606 // jump back into scope specifier parsing). 1607 Sema::NameClassification Classification = Actions.ClassifyName( 1608 getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr); 1609 1610 // If name lookup found nothing and we guessed that this was a template name, 1611 // double-check before committing to that interpretation. C++20 requires that 1612 // we interpret this as a template-id if it can be, but if it can't be, then 1613 // this is an error recovery case. 1614 if (Classification.getKind() == Sema::NC_UndeclaredTemplate && 1615 isTemplateArgumentList(1) == TPResult::False) { 1616 // It's not a template-id; re-classify without the '<' as a hint. 1617 Token FakeNext = Next; 1618 FakeNext.setKind(tok::unknown); 1619 Classification = 1620 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext, 1621 SS.isEmpty() ? CCC : nullptr); 1622 } 1623 1624 switch (Classification.getKind()) { 1625 case Sema::NC_Error: 1626 return ANK_Error; 1627 1628 case Sema::NC_Keyword: 1629 // The identifier was typo-corrected to a keyword. 1630 Tok.setIdentifierInfo(Name); 1631 Tok.setKind(Name->getTokenID()); 1632 PP.TypoCorrectToken(Tok); 1633 if (SS.isNotEmpty()) 1634 AnnotateScopeToken(SS, !WasScopeAnnotation); 1635 // We've "annotated" this as a keyword. 1636 return ANK_Success; 1637 1638 case Sema::NC_Unknown: 1639 // It's not something we know about. Leave it unannotated. 1640 break; 1641 1642 case Sema::NC_Type: { 1643 SourceLocation BeginLoc = NameLoc; 1644 if (SS.isNotEmpty()) 1645 BeginLoc = SS.getBeginLoc(); 1646 1647 /// An Objective-C object type followed by '<' is a specialization of 1648 /// a parameterized class type or a protocol-qualified type. 1649 ParsedType Ty = Classification.getType(); 1650 if (getLangOpts().ObjC && NextToken().is(tok::less) && 1651 (Ty.get()->isObjCObjectType() || 1652 Ty.get()->isObjCObjectPointerType())) { 1653 // Consume the name. 1654 SourceLocation IdentifierLoc = ConsumeToken(); 1655 SourceLocation NewEndLoc; 1656 TypeResult NewType 1657 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, 1658 /*consumeLastToken=*/false, 1659 NewEndLoc); 1660 if (NewType.isUsable()) 1661 Ty = NewType.get(); 1662 else if (Tok.is(tok::eof)) // Nothing to do here, bail out... 1663 return ANK_Error; 1664 } 1665 1666 Tok.setKind(tok::annot_typename); 1667 setTypeAnnotation(Tok, Ty); 1668 Tok.setAnnotationEndLoc(Tok.getLocation()); 1669 Tok.setLocation(BeginLoc); 1670 PP.AnnotateCachedTokens(Tok); 1671 return ANK_Success; 1672 } 1673 1674 case Sema::NC_ContextIndependentExpr: 1675 Tok.setKind(tok::annot_primary_expr); 1676 setExprAnnotation(Tok, Classification.getExpression()); 1677 Tok.setAnnotationEndLoc(NameLoc); 1678 if (SS.isNotEmpty()) 1679 Tok.setLocation(SS.getBeginLoc()); 1680 PP.AnnotateCachedTokens(Tok); 1681 return ANK_Success; 1682 1683 case Sema::NC_NonType: 1684 Tok.setKind(tok::annot_non_type); 1685 setNonTypeAnnotation(Tok, Classification.getNonTypeDecl()); 1686 Tok.setLocation(NameLoc); 1687 Tok.setAnnotationEndLoc(NameLoc); 1688 PP.AnnotateCachedTokens(Tok); 1689 if (SS.isNotEmpty()) 1690 AnnotateScopeToken(SS, !WasScopeAnnotation); 1691 return ANK_Success; 1692 1693 case Sema::NC_UndeclaredNonType: 1694 case Sema::NC_DependentNonType: 1695 Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType 1696 ? tok::annot_non_type_undeclared 1697 : tok::annot_non_type_dependent); 1698 setIdentifierAnnotation(Tok, Name); 1699 Tok.setLocation(NameLoc); 1700 Tok.setAnnotationEndLoc(NameLoc); 1701 PP.AnnotateCachedTokens(Tok); 1702 if (SS.isNotEmpty()) 1703 AnnotateScopeToken(SS, !WasScopeAnnotation); 1704 return ANK_Success; 1705 1706 case Sema::NC_TypeTemplate: 1707 if (Next.isNot(tok::less)) { 1708 // This may be a type template being used as a template template argument. 1709 if (SS.isNotEmpty()) 1710 AnnotateScopeToken(SS, !WasScopeAnnotation); 1711 return ANK_TemplateName; 1712 } 1713 LLVM_FALLTHROUGH; 1714 case Sema::NC_VarTemplate: 1715 case Sema::NC_FunctionTemplate: 1716 case Sema::NC_UndeclaredTemplate: { 1717 // We have a type, variable or function template followed by '<'. 1718 ConsumeToken(); 1719 UnqualifiedId Id; 1720 Id.setIdentifier(Name, NameLoc); 1721 if (AnnotateTemplateIdToken( 1722 TemplateTy::make(Classification.getTemplateName()), 1723 Classification.getTemplateNameKind(), SS, SourceLocation(), Id)) 1724 return ANK_Error; 1725 return ANK_Success; 1726 } 1727 } 1728 1729 // Unable to classify the name, but maybe we can annotate a scope specifier. 1730 if (SS.isNotEmpty()) 1731 AnnotateScopeToken(SS, !WasScopeAnnotation); 1732 return ANK_Unresolved; 1733 } 1734 1735 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) { 1736 assert(Tok.isNot(tok::identifier)); 1737 Diag(Tok, diag::ext_keyword_as_ident) 1738 << PP.getSpelling(Tok) 1739 << DisableKeyword; 1740 if (DisableKeyword) 1741 Tok.getIdentifierInfo()->revertTokenIDToIdentifier(); 1742 Tok.setKind(tok::identifier); 1743 return true; 1744 } 1745 1746 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 1747 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 1748 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 1749 /// with a single annotation token representing the typename or C++ scope 1750 /// respectively. 1751 /// This simplifies handling of C++ scope specifiers and allows efficient 1752 /// backtracking without the need to re-parse and resolve nested-names and 1753 /// typenames. 1754 /// It will mainly be called when we expect to treat identifiers as typenames 1755 /// (if they are typenames). For example, in C we do not expect identifiers 1756 /// inside expressions to be treated as typenames so it will not be called 1757 /// for expressions in C. 1758 /// The benefit for C/ObjC is that a typename will be annotated and 1759 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName 1760 /// will not be called twice, once to check whether we have a declaration 1761 /// specifier, and another one to get the actual type inside 1762 /// ParseDeclarationSpecifiers). 1763 /// 1764 /// This returns true if an error occurred. 1765 /// 1766 /// Note that this routine emits an error if you call it with ::new or ::delete 1767 /// as the current tokens, so only call it in contexts where these are invalid. 1768 bool Parser::TryAnnotateTypeOrScopeToken() { 1769 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 1770 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) || 1771 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) || 1772 Tok.is(tok::kw___super)) && 1773 "Cannot be a type or scope token!"); 1774 1775 if (Tok.is(tok::kw_typename)) { 1776 // MSVC lets you do stuff like: 1777 // typename typedef T_::D D; 1778 // 1779 // We will consume the typedef token here and put it back after we have 1780 // parsed the first identifier, transforming it into something more like: 1781 // typename T_::D typedef D; 1782 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) { 1783 Token TypedefToken; 1784 PP.Lex(TypedefToken); 1785 bool Result = TryAnnotateTypeOrScopeToken(); 1786 PP.EnterToken(Tok, /*IsReinject=*/true); 1787 Tok = TypedefToken; 1788 if (!Result) 1789 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename); 1790 return Result; 1791 } 1792 1793 // Parse a C++ typename-specifier, e.g., "typename T::type". 1794 // 1795 // typename-specifier: 1796 // 'typename' '::' [opt] nested-name-specifier identifier 1797 // 'typename' '::' [opt] nested-name-specifier template [opt] 1798 // simple-template-id 1799 SourceLocation TypenameLoc = ConsumeToken(); 1800 CXXScopeSpec SS; 1801 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1802 /*EnteringContext=*/false, nullptr, 1803 /*IsTypename*/ true)) 1804 return true; 1805 if (!SS.isSet()) { 1806 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) || 1807 Tok.is(tok::annot_decltype)) { 1808 // Attempt to recover by skipping the invalid 'typename' 1809 if (Tok.is(tok::annot_decltype) || 1810 (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) { 1811 unsigned DiagID = diag::err_expected_qualified_after_typename; 1812 // MS compatibility: MSVC permits using known types with typename. 1813 // e.g. "typedef typename T* pointer_type" 1814 if (getLangOpts().MicrosoftExt) 1815 DiagID = diag::warn_expected_qualified_after_typename; 1816 Diag(Tok.getLocation(), DiagID); 1817 return false; 1818 } 1819 } 1820 if (Tok.isEditorPlaceholder()) 1821 return true; 1822 1823 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); 1824 return true; 1825 } 1826 1827 TypeResult Ty; 1828 if (Tok.is(tok::identifier)) { 1829 // FIXME: check whether the next token is '<', first! 1830 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1831 *Tok.getIdentifierInfo(), 1832 Tok.getLocation()); 1833 } else if (Tok.is(tok::annot_template_id)) { 1834 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1835 if (TemplateId->Kind != TNK_Type_template && 1836 TemplateId->Kind != TNK_Dependent_template_name && 1837 TemplateId->Kind != TNK_Undeclared_template) { 1838 Diag(Tok, diag::err_typename_refers_to_non_type_template) 1839 << Tok.getAnnotationRange(); 1840 return true; 1841 } 1842 1843 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1844 TemplateId->NumArgs); 1845 1846 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1847 TemplateId->TemplateKWLoc, 1848 TemplateId->Template, 1849 TemplateId->Name, 1850 TemplateId->TemplateNameLoc, 1851 TemplateId->LAngleLoc, 1852 TemplateArgsPtr, 1853 TemplateId->RAngleLoc); 1854 } else { 1855 Diag(Tok, diag::err_expected_type_name_after_typename) 1856 << SS.getRange(); 1857 return true; 1858 } 1859 1860 SourceLocation EndLoc = Tok.getLastLoc(); 1861 Tok.setKind(tok::annot_typename); 1862 setTypeAnnotation(Tok, Ty.isInvalid() ? nullptr : Ty.get()); 1863 Tok.setAnnotationEndLoc(EndLoc); 1864 Tok.setLocation(TypenameLoc); 1865 PP.AnnotateCachedTokens(Tok); 1866 return false; 1867 } 1868 1869 // Remembers whether the token was originally a scope annotation. 1870 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1871 1872 CXXScopeSpec SS; 1873 if (getLangOpts().CPlusPlus) 1874 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext*/false)) 1875 return true; 1876 1877 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation); 1878 } 1879 1880 /// Try to annotate a type or scope token, having already parsed an 1881 /// optional scope specifier. \p IsNewScope should be \c true unless the scope 1882 /// specifier was extracted from an existing tok::annot_cxxscope annotation. 1883 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, 1884 bool IsNewScope) { 1885 if (Tok.is(tok::identifier)) { 1886 // Determine whether the identifier is a type name. 1887 if (ParsedType Ty = Actions.getTypeName( 1888 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS, 1889 false, NextToken().is(tok::period), nullptr, 1890 /*IsCtorOrDtorName=*/false, 1891 /*NonTrivialTypeSourceInfo*/true, 1892 /*IsClassTemplateDeductionContext*/true)) { 1893 SourceLocation BeginLoc = Tok.getLocation(); 1894 if (SS.isNotEmpty()) // it was a C++ qualified type name. 1895 BeginLoc = SS.getBeginLoc(); 1896 1897 /// An Objective-C object type followed by '<' is a specialization of 1898 /// a parameterized class type or a protocol-qualified type. 1899 if (getLangOpts().ObjC && NextToken().is(tok::less) && 1900 (Ty.get()->isObjCObjectType() || 1901 Ty.get()->isObjCObjectPointerType())) { 1902 // Consume the name. 1903 SourceLocation IdentifierLoc = ConsumeToken(); 1904 SourceLocation NewEndLoc; 1905 TypeResult NewType 1906 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, 1907 /*consumeLastToken=*/false, 1908 NewEndLoc); 1909 if (NewType.isUsable()) 1910 Ty = NewType.get(); 1911 else if (Tok.is(tok::eof)) // Nothing to do here, bail out... 1912 return false; 1913 } 1914 1915 // This is a typename. Replace the current token in-place with an 1916 // annotation type token. 1917 Tok.setKind(tok::annot_typename); 1918 setTypeAnnotation(Tok, Ty); 1919 Tok.setAnnotationEndLoc(Tok.getLocation()); 1920 Tok.setLocation(BeginLoc); 1921 1922 // In case the tokens were cached, have Preprocessor replace 1923 // them with the annotation token. 1924 PP.AnnotateCachedTokens(Tok); 1925 return false; 1926 } 1927 1928 if (!getLangOpts().CPlusPlus) { 1929 // If we're in C, we can't have :: tokens at all (the lexer won't return 1930 // them). If the identifier is not a type, then it can't be scope either, 1931 // just early exit. 1932 return false; 1933 } 1934 1935 // If this is a template-id, annotate with a template-id or type token. 1936 // FIXME: This appears to be dead code. We already have formed template-id 1937 // tokens when parsing the scope specifier; this can never form a new one. 1938 if (NextToken().is(tok::less)) { 1939 TemplateTy Template; 1940 UnqualifiedId TemplateName; 1941 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1942 bool MemberOfUnknownSpecialization; 1943 if (TemplateNameKind TNK = Actions.isTemplateName( 1944 getCurScope(), SS, 1945 /*hasTemplateKeyword=*/false, TemplateName, 1946 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template, 1947 MemberOfUnknownSpecialization)) { 1948 // Only annotate an undeclared template name as a template-id if the 1949 // following tokens have the form of a template argument list. 1950 if (TNK != TNK_Undeclared_template || 1951 isTemplateArgumentList(1) != TPResult::False) { 1952 // Consume the identifier. 1953 ConsumeToken(); 1954 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 1955 TemplateName)) { 1956 // If an unrecoverable error occurred, we need to return true here, 1957 // because the token stream is in a damaged state. We may not 1958 // return a valid identifier. 1959 return true; 1960 } 1961 } 1962 } 1963 } 1964 1965 // The current token, which is either an identifier or a 1966 // template-id, is not part of the annotation. Fall through to 1967 // push that token back into the stream and complete the C++ scope 1968 // specifier annotation. 1969 } 1970 1971 if (Tok.is(tok::annot_template_id)) { 1972 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1973 if (TemplateId->Kind == TNK_Type_template) { 1974 // A template-id that refers to a type was parsed into a 1975 // template-id annotation in a context where we weren't allowed 1976 // to produce a type annotation token. Update the template-id 1977 // annotation token to a type annotation token now. 1978 AnnotateTemplateIdTokenAsType(); 1979 return false; 1980 } 1981 } 1982 1983 if (SS.isEmpty()) 1984 return false; 1985 1986 // A C++ scope specifier that isn't followed by a typename. 1987 AnnotateScopeToken(SS, IsNewScope); 1988 return false; 1989 } 1990 1991 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only 1992 /// annotates C++ scope specifiers and template-ids. This returns 1993 /// true if there was an error that could not be recovered from. 1994 /// 1995 /// Note that this routine emits an error if you call it with ::new or ::delete 1996 /// as the current tokens, so only call it in contexts where these are invalid. 1997 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { 1998 assert(getLangOpts().CPlusPlus && 1999 "Call sites of this function should be guarded by checking for C++"); 2000 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 2001 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || 2002 Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) && 2003 "Cannot be a type or scope token!"); 2004 2005 CXXScopeSpec SS; 2006 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext)) 2007 return true; 2008 if (SS.isEmpty()) 2009 return false; 2010 2011 AnnotateScopeToken(SS, true); 2012 return false; 2013 } 2014 2015 bool Parser::isTokenEqualOrEqualTypo() { 2016 tok::TokenKind Kind = Tok.getKind(); 2017 switch (Kind) { 2018 default: 2019 return false; 2020 case tok::ampequal: // &= 2021 case tok::starequal: // *= 2022 case tok::plusequal: // += 2023 case tok::minusequal: // -= 2024 case tok::exclaimequal: // != 2025 case tok::slashequal: // /= 2026 case tok::percentequal: // %= 2027 case tok::lessequal: // <= 2028 case tok::lesslessequal: // <<= 2029 case tok::greaterequal: // >= 2030 case tok::greatergreaterequal: // >>= 2031 case tok::caretequal: // ^= 2032 case tok::pipeequal: // |= 2033 case tok::equalequal: // == 2034 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal) 2035 << Kind 2036 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "="); 2037 LLVM_FALLTHROUGH; 2038 case tok::equal: 2039 return true; 2040 } 2041 } 2042 2043 SourceLocation Parser::handleUnexpectedCodeCompletionToken() { 2044 assert(Tok.is(tok::code_completion)); 2045 PrevTokLocation = Tok.getLocation(); 2046 2047 for (Scope *S = getCurScope(); S; S = S->getParent()) { 2048 if (S->getFlags() & Scope::FnScope) { 2049 Actions.CodeCompleteOrdinaryName(getCurScope(), 2050 Sema::PCC_RecoveryInFunction); 2051 cutOffParsing(); 2052 return PrevTokLocation; 2053 } 2054 2055 if (S->getFlags() & Scope::ClassScope) { 2056 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); 2057 cutOffParsing(); 2058 return PrevTokLocation; 2059 } 2060 } 2061 2062 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); 2063 cutOffParsing(); 2064 return PrevTokLocation; 2065 } 2066 2067 // Code-completion pass-through functions 2068 2069 void Parser::CodeCompleteDirective(bool InConditional) { 2070 Actions.CodeCompletePreprocessorDirective(InConditional); 2071 } 2072 2073 void Parser::CodeCompleteInConditionalExclusion() { 2074 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope()); 2075 } 2076 2077 void Parser::CodeCompleteMacroName(bool IsDefinition) { 2078 Actions.CodeCompletePreprocessorMacroName(IsDefinition); 2079 } 2080 2081 void Parser::CodeCompletePreprocessorExpression() { 2082 Actions.CodeCompletePreprocessorExpression(); 2083 } 2084 2085 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro, 2086 MacroInfo *MacroInfo, 2087 unsigned ArgumentIndex) { 2088 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 2089 ArgumentIndex); 2090 } 2091 2092 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) { 2093 Actions.CodeCompleteIncludedFile(Dir, IsAngled); 2094 } 2095 2096 void Parser::CodeCompleteNaturalLanguage() { 2097 Actions.CodeCompleteNaturalLanguage(); 2098 } 2099 2100 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { 2101 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) && 2102 "Expected '__if_exists' or '__if_not_exists'"); 2103 Result.IsIfExists = Tok.is(tok::kw___if_exists); 2104 Result.KeywordLoc = ConsumeToken(); 2105 2106 BalancedDelimiterTracker T(*this, tok::l_paren); 2107 if (T.consumeOpen()) { 2108 Diag(Tok, diag::err_expected_lparen_after) 2109 << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); 2110 return true; 2111 } 2112 2113 // Parse nested-name-specifier. 2114 if (getLangOpts().CPlusPlus) 2115 ParseOptionalCXXScopeSpecifier(Result.SS, nullptr, 2116 /*EnteringContext=*/false); 2117 2118 // Check nested-name specifier. 2119 if (Result.SS.isInvalid()) { 2120 T.skipToEnd(); 2121 return true; 2122 } 2123 2124 // Parse the unqualified-id. 2125 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused. 2126 if (ParseUnqualifiedId( 2127 Result.SS, /*EnteringContext*/false, /*AllowDestructorName*/true, 2128 /*AllowConstructorName*/true, /*AllowDeductionGuide*/false, nullptr, 2129 &TemplateKWLoc, Result.Name)) { 2130 T.skipToEnd(); 2131 return true; 2132 } 2133 2134 if (T.consumeClose()) 2135 return true; 2136 2137 // Check if the symbol exists. 2138 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, 2139 Result.IsIfExists, Result.SS, 2140 Result.Name)) { 2141 case Sema::IER_Exists: 2142 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip; 2143 break; 2144 2145 case Sema::IER_DoesNotExist: 2146 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip; 2147 break; 2148 2149 case Sema::IER_Dependent: 2150 Result.Behavior = IEB_Dependent; 2151 break; 2152 2153 case Sema::IER_Error: 2154 return true; 2155 } 2156 2157 return false; 2158 } 2159 2160 void Parser::ParseMicrosoftIfExistsExternalDeclaration() { 2161 IfExistsCondition Result; 2162 if (ParseMicrosoftIfExistsCondition(Result)) 2163 return; 2164 2165 BalancedDelimiterTracker Braces(*this, tok::l_brace); 2166 if (Braces.consumeOpen()) { 2167 Diag(Tok, diag::err_expected) << tok::l_brace; 2168 return; 2169 } 2170 2171 switch (Result.Behavior) { 2172 case IEB_Parse: 2173 // Parse declarations below. 2174 break; 2175 2176 case IEB_Dependent: 2177 llvm_unreachable("Cannot have a dependent external declaration"); 2178 2179 case IEB_Skip: 2180 Braces.skipToEnd(); 2181 return; 2182 } 2183 2184 // Parse the declarations. 2185 // FIXME: Support module import within __if_exists? 2186 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 2187 ParsedAttributesWithRange attrs(AttrFactory); 2188 MaybeParseCXX11Attributes(attrs); 2189 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs); 2190 if (Result && !getCurScope()->getParent()) 2191 Actions.getASTConsumer().HandleTopLevelDecl(Result.get()); 2192 } 2193 Braces.consumeClose(); 2194 } 2195 2196 /// Parse a declaration beginning with the 'module' keyword or C++20 2197 /// context-sensitive keyword (optionally preceded by 'export'). 2198 /// 2199 /// module-declaration: [Modules TS + P0629R0] 2200 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';' 2201 /// 2202 /// global-module-fragment: [C++2a] 2203 /// 'module' ';' top-level-declaration-seq[opt] 2204 /// module-declaration: [C++2a] 2205 /// 'export'[opt] 'module' module-name module-partition[opt] 2206 /// attribute-specifier-seq[opt] ';' 2207 /// private-module-fragment: [C++2a] 2208 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt] 2209 Parser::DeclGroupPtrTy Parser::ParseModuleDecl(bool IsFirstDecl) { 2210 SourceLocation StartLoc = Tok.getLocation(); 2211 2212 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export) 2213 ? Sema::ModuleDeclKind::Interface 2214 : Sema::ModuleDeclKind::Implementation; 2215 2216 assert( 2217 (Tok.is(tok::kw_module) || 2218 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) && 2219 "not a module declaration"); 2220 SourceLocation ModuleLoc = ConsumeToken(); 2221 2222 // Attributes appear after the module name, not before. 2223 // FIXME: Suggest moving the attributes later with a fixit. 2224 DiagnoseAndSkipCXX11Attributes(); 2225 2226 // Parse a global-module-fragment, if present. 2227 if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) { 2228 SourceLocation SemiLoc = ConsumeToken(); 2229 if (!IsFirstDecl) { 2230 Diag(StartLoc, diag::err_global_module_introducer_not_at_start) 2231 << SourceRange(StartLoc, SemiLoc); 2232 return nullptr; 2233 } 2234 if (MDK == Sema::ModuleDeclKind::Interface) { 2235 Diag(StartLoc, diag::err_module_fragment_exported) 2236 << /*global*/0 << FixItHint::CreateRemoval(StartLoc); 2237 } 2238 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc); 2239 } 2240 2241 // Parse a private-module-fragment, if present. 2242 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) && 2243 NextToken().is(tok::kw_private)) { 2244 if (MDK == Sema::ModuleDeclKind::Interface) { 2245 Diag(StartLoc, diag::err_module_fragment_exported) 2246 << /*private*/1 << FixItHint::CreateRemoval(StartLoc); 2247 } 2248 ConsumeToken(); 2249 SourceLocation PrivateLoc = ConsumeToken(); 2250 DiagnoseAndSkipCXX11Attributes(); 2251 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi); 2252 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc); 2253 } 2254 2255 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2256 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false)) 2257 return nullptr; 2258 2259 // Parse the optional module-partition. 2260 if (Tok.is(tok::colon)) { 2261 SourceLocation ColonLoc = ConsumeToken(); 2262 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition; 2263 if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/false)) 2264 return nullptr; 2265 2266 // FIXME: Support module partition declarations. 2267 Diag(ColonLoc, diag::err_unsupported_module_partition) 2268 << SourceRange(ColonLoc, Partition.back().second); 2269 // Recover by parsing as a non-partition. 2270 } 2271 2272 // We don't support any module attributes yet; just parse them and diagnose. 2273 ParsedAttributesWithRange Attrs(AttrFactory); 2274 MaybeParseCXX11Attributes(Attrs); 2275 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr); 2276 2277 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2278 2279 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, IsFirstDecl); 2280 } 2281 2282 /// Parse a module import declaration. This is essentially the same for 2283 /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC) 2284 /// and the trailing optional attributes (in C++). 2285 /// 2286 /// [ObjC] @import declaration: 2287 /// '@' 'import' module-name ';' 2288 /// [ModTS] module-import-declaration: 2289 /// 'import' module-name attribute-specifier-seq[opt] ';' 2290 /// [C++2a] module-import-declaration: 2291 /// 'export'[opt] 'import' module-name 2292 /// attribute-specifier-seq[opt] ';' 2293 /// 'export'[opt] 'import' module-partition 2294 /// attribute-specifier-seq[opt] ';' 2295 /// 'export'[opt] 'import' header-name 2296 /// attribute-specifier-seq[opt] ';' 2297 Decl *Parser::ParseModuleImport(SourceLocation AtLoc) { 2298 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc; 2299 2300 SourceLocation ExportLoc; 2301 TryConsumeToken(tok::kw_export, ExportLoc); 2302 2303 assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier) 2304 : Tok.isObjCAtKeyword(tok::objc_import)) && 2305 "Improper start to module import"); 2306 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import); 2307 SourceLocation ImportLoc = ConsumeToken(); 2308 2309 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2310 Module *HeaderUnit = nullptr; 2311 2312 if (Tok.is(tok::header_name)) { 2313 // This is a header import that the preprocessor decided we should skip 2314 // because it was malformed in some way. Parse and ignore it; it's already 2315 // been diagnosed. 2316 ConsumeToken(); 2317 } else if (Tok.is(tok::annot_header_unit)) { 2318 // This is a header import that the preprocessor mapped to a module import. 2319 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue()); 2320 ConsumeAnnotationToken(); 2321 } else if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon)) { 2322 SourceLocation ColonLoc = ConsumeToken(); 2323 if (ParseModuleName(ImportLoc, Path, /*IsImport*/true)) 2324 return nullptr; 2325 2326 // FIXME: Support module partition import. 2327 Diag(ColonLoc, diag::err_unsupported_module_partition) 2328 << SourceRange(ColonLoc, Path.back().second); 2329 return nullptr; 2330 } else { 2331 if (ParseModuleName(ImportLoc, Path, /*IsImport*/true)) 2332 return nullptr; 2333 } 2334 2335 ParsedAttributesWithRange Attrs(AttrFactory); 2336 MaybeParseCXX11Attributes(Attrs); 2337 // We don't support any module import attributes yet. 2338 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr); 2339 2340 if (PP.hadModuleLoaderFatalFailure()) { 2341 // With a fatal failure in the module loader, we abort parsing. 2342 cutOffParsing(); 2343 return nullptr; 2344 } 2345 2346 DeclResult Import; 2347 if (HeaderUnit) 2348 Import = 2349 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit); 2350 else if (!Path.empty()) 2351 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path); 2352 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2353 if (Import.isInvalid()) 2354 return nullptr; 2355 2356 // Using '@import' in framework headers requires modules to be enabled so that 2357 // the header is parseable. Emit a warning to make the user aware. 2358 if (IsObjCAtImport && AtLoc.isValid()) { 2359 auto &SrcMgr = PP.getSourceManager(); 2360 auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc)); 2361 if (FE && llvm::sys::path::parent_path(FE->getDir()->getName()) 2362 .endswith(".framework")) 2363 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header); 2364 } 2365 2366 return Import.get(); 2367 } 2368 2369 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same 2370 /// grammar). 2371 /// 2372 /// module-name: 2373 /// module-name-qualifier[opt] identifier 2374 /// module-name-qualifier: 2375 /// module-name-qualifier[opt] identifier '.' 2376 bool Parser::ParseModuleName( 2377 SourceLocation UseLoc, 2378 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, 2379 bool IsImport) { 2380 // Parse the module path. 2381 while (true) { 2382 if (!Tok.is(tok::identifier)) { 2383 if (Tok.is(tok::code_completion)) { 2384 Actions.CodeCompleteModuleImport(UseLoc, Path); 2385 cutOffParsing(); 2386 return true; 2387 } 2388 2389 Diag(Tok, diag::err_module_expected_ident) << IsImport; 2390 SkipUntil(tok::semi); 2391 return true; 2392 } 2393 2394 // Record this part of the module path. 2395 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); 2396 ConsumeToken(); 2397 2398 if (Tok.isNot(tok::period)) 2399 return false; 2400 2401 ConsumeToken(); 2402 } 2403 } 2404 2405 /// Try recover parser when module annotation appears where it must not 2406 /// be found. 2407 /// \returns false if the recover was successful and parsing may be continued, or 2408 /// true if parser must bail out to top level and handle the token there. 2409 bool Parser::parseMisplacedModuleImport() { 2410 while (true) { 2411 switch (Tok.getKind()) { 2412 case tok::annot_module_end: 2413 // If we recovered from a misplaced module begin, we expect to hit a 2414 // misplaced module end too. Stay in the current context when this 2415 // happens. 2416 if (MisplacedModuleBeginCount) { 2417 --MisplacedModuleBeginCount; 2418 Actions.ActOnModuleEnd(Tok.getLocation(), 2419 reinterpret_cast<Module *>( 2420 Tok.getAnnotationValue())); 2421 ConsumeAnnotationToken(); 2422 continue; 2423 } 2424 // Inform caller that recovery failed, the error must be handled at upper 2425 // level. This will generate the desired "missing '}' at end of module" 2426 // diagnostics on the way out. 2427 return true; 2428 case tok::annot_module_begin: 2429 // Recover by entering the module (Sema will diagnose). 2430 Actions.ActOnModuleBegin(Tok.getLocation(), 2431 reinterpret_cast<Module *>( 2432 Tok.getAnnotationValue())); 2433 ConsumeAnnotationToken(); 2434 ++MisplacedModuleBeginCount; 2435 continue; 2436 case tok::annot_module_include: 2437 // Module import found where it should not be, for instance, inside a 2438 // namespace. Recover by importing the module. 2439 Actions.ActOnModuleInclude(Tok.getLocation(), 2440 reinterpret_cast<Module *>( 2441 Tok.getAnnotationValue())); 2442 ConsumeAnnotationToken(); 2443 // If there is another module import, process it. 2444 continue; 2445 default: 2446 return false; 2447 } 2448 } 2449 return false; 2450 } 2451 2452 bool BalancedDelimiterTracker::diagnoseOverflow() { 2453 P.Diag(P.Tok, diag::err_bracket_depth_exceeded) 2454 << P.getLangOpts().BracketDepth; 2455 P.Diag(P.Tok, diag::note_bracket_depth); 2456 P.cutOffParsing(); 2457 return true; 2458 } 2459 2460 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, 2461 const char *Msg, 2462 tok::TokenKind SkipToTok) { 2463 LOpen = P.Tok.getLocation(); 2464 if (P.ExpectAndConsume(Kind, DiagID, Msg)) { 2465 if (SkipToTok != tok::unknown) 2466 P.SkipUntil(SkipToTok, Parser::StopAtSemi); 2467 return true; 2468 } 2469 2470 if (getDepth() < P.getLangOpts().BracketDepth) 2471 return false; 2472 2473 return diagnoseOverflow(); 2474 } 2475 2476 bool BalancedDelimiterTracker::diagnoseMissingClose() { 2477 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter"); 2478 2479 if (P.Tok.is(tok::annot_module_end)) 2480 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close; 2481 else 2482 P.Diag(P.Tok, diag::err_expected) << Close; 2483 P.Diag(LOpen, diag::note_matching) << Kind; 2484 2485 // If we're not already at some kind of closing bracket, skip to our closing 2486 // token. 2487 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) && 2488 P.Tok.isNot(tok::r_square) && 2489 P.SkipUntil(Close, FinalToken, 2490 Parser::StopAtSemi | Parser::StopBeforeMatch) && 2491 P.Tok.is(Close)) 2492 LClose = P.ConsumeAnyToken(); 2493 return true; 2494 } 2495 2496 void BalancedDelimiterTracker::skipToEnd() { 2497 P.SkipUntil(Close, Parser::StopBeforeMatch); 2498 consumeClose(); 2499 } 2500