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