1 //===--- Parser.cpp - C Language Family Parser ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Parser interfaces. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Parse/Parser.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/DeclTemplate.h" 17 #include "clang/Basic/FileManager.h" 18 #include "clang/Parse/ParseDiagnostic.h" 19 #include "clang/Parse/RAIIObjectsForParser.h" 20 #include "clang/Sema/DeclSpec.h" 21 #include "clang/Sema/ParsedTemplate.h" 22 #include "clang/Sema/Scope.h" 23 #include "llvm/Support/Path.h" 24 using namespace clang; 25 26 27 namespace { 28 /// A comment handler that passes comments found by the preprocessor 29 /// to the parser action. 30 class ActionCommentHandler : public CommentHandler { 31 Sema &S; 32 33 public: 34 explicit ActionCommentHandler(Sema &S) : S(S) { } 35 36 bool HandleComment(Preprocessor &PP, SourceRange Comment) override { 37 S.ActOnComment(Comment); 38 return false; 39 } 40 }; 41 } // end anonymous namespace 42 43 IdentifierInfo *Parser::getSEHExceptKeyword() { 44 // __except is accepted as a (contextual) keyword 45 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland)) 46 Ident__except = PP.getIdentifierInfo("__except"); 47 48 return Ident__except; 49 } 50 51 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies) 52 : PP(pp), 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 73 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) { 74 return Diags.Report(Loc, DiagID); 75 } 76 77 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) { 78 return Diag(Tok.getLocation(), DiagID); 79 } 80 81 /// Emits a diagnostic suggesting parentheses surrounding a 82 /// given range. 83 /// 84 /// \param Loc The location where we'll emit the diagnostic. 85 /// \param DK The kind of diagnostic to emit. 86 /// \param ParenRange Source range enclosing code that should be parenthesized. 87 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK, 88 SourceRange ParenRange) { 89 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd()); 90 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 91 // We can't display the parentheses, so just dig the 92 // warning/error and return. 93 Diag(Loc, DK); 94 return; 95 } 96 97 Diag(Loc, DK) 98 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 99 << FixItHint::CreateInsertion(EndLoc, ")"); 100 } 101 102 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) { 103 switch (ExpectedTok) { 104 case tok::semi: 105 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ; 106 default: return false; 107 } 108 } 109 110 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID, 111 StringRef Msg) { 112 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) { 113 ConsumeAnyToken(); 114 return false; 115 } 116 117 // Detect common single-character typos and resume. 118 if (IsCommonTypo(ExpectedTok, Tok)) { 119 SourceLocation Loc = Tok.getLocation(); 120 { 121 DiagnosticBuilder DB = Diag(Loc, DiagID); 122 DB << FixItHint::CreateReplacement( 123 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok)); 124 if (DiagID == diag::err_expected) 125 DB << ExpectedTok; 126 else if (DiagID == diag::err_expected_after) 127 DB << Msg << ExpectedTok; 128 else 129 DB << Msg; 130 } 131 132 // Pretend there wasn't a problem. 133 ConsumeAnyToken(); 134 return false; 135 } 136 137 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); 138 const char *Spelling = nullptr; 139 if (EndLoc.isValid()) 140 Spelling = tok::getPunctuatorSpelling(ExpectedTok); 141 142 DiagnosticBuilder DB = 143 Spelling 144 ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling) 145 : Diag(Tok, DiagID); 146 if (DiagID == diag::err_expected) 147 DB << ExpectedTok; 148 else if (DiagID == diag::err_expected_after) 149 DB << Msg << ExpectedTok; 150 else 151 DB << Msg; 152 153 return true; 154 } 155 156 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { 157 if (TryConsumeToken(tok::semi)) 158 return false; 159 160 if (Tok.is(tok::code_completion)) { 161 handleUnexpectedCodeCompletionToken(); 162 return false; 163 } 164 165 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && 166 NextToken().is(tok::semi)) { 167 Diag(Tok, diag::err_extraneous_token_before_semi) 168 << PP.getSpelling(Tok) 169 << FixItHint::CreateRemoval(Tok.getLocation()); 170 ConsumeAnyToken(); // The ')' or ']'. 171 ConsumeToken(); // The ';'. 172 return false; 173 } 174 175 return ExpectAndConsume(tok::semi, DiagID); 176 } 177 178 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) { 179 if (!Tok.is(tok::semi)) return; 180 181 bool HadMultipleSemis = false; 182 SourceLocation StartLoc = Tok.getLocation(); 183 SourceLocation EndLoc = Tok.getLocation(); 184 ConsumeToken(); 185 186 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) { 187 HadMultipleSemis = true; 188 EndLoc = Tok.getLocation(); 189 ConsumeToken(); 190 } 191 192 // C++11 allows extra semicolons at namespace scope, but not in any of the 193 // other contexts. 194 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) { 195 if (getLangOpts().CPlusPlus11) 196 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi) 197 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 198 else 199 Diag(StartLoc, diag::ext_extra_semi_cxx11) 200 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 201 return; 202 } 203 204 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis) 205 Diag(StartLoc, diag::ext_extra_semi) 206 << Kind << DeclSpec::getSpecifierName(TST, 207 Actions.getASTContext().getPrintingPolicy()) 208 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 209 else 210 // A single semicolon is valid after a member function definition. 211 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def) 212 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); 213 } 214 215 bool Parser::expectIdentifier() { 216 if (Tok.is(tok::identifier)) 217 return false; 218 if (const auto *II = Tok.getIdentifierInfo()) { 219 if (II->isCPlusPlusKeyword(getLangOpts())) { 220 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword) 221 << tok::identifier << Tok.getIdentifierInfo(); 222 // Objective-C++: Recover by treating this keyword as a valid identifier. 223 return false; 224 } 225 } 226 Diag(Tok, diag::err_expected) << tok::identifier; 227 return true; 228 } 229 230 void 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 266 static 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. 278 bool 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. 403 void 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. 414 void 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. 432 Parser::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. 443 Parser::ParseScopeFlags::~ParseScopeFlags() { 444 if (CurScope) 445 CurScope->setFlags(OldFlags); 446 } 447 448 449 //===----------------------------------------------------------------------===// 450 // C99 6.9: External Definitions. 451 //===----------------------------------------------------------------------===// 452 453 Parser::~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 /// 473 void 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 566 void 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. 582 bool 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 604 bool 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 /// 748 Parser::DeclGroupPtrTy 749 Parser::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. 982 bool 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. 1001 bool 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 /// 1036 Parser::DeclGroupPtrTy 1037 Parser::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 (getLangOpts().OpenCL) 1085 Actions.setCurrentOpenCLExtensionForDecl(TheDecl); 1086 if (AnonRecord) { 1087 Decl* decls[] = {AnonRecord, TheDecl}; 1088 return Actions.BuildDeclaratorGroup(decls); 1089 } 1090 return Actions.ConvertDeclToDeclGroup(TheDecl); 1091 } 1092 1093 DS.takeAttributesFrom(attrs); 1094 1095 // ObjC2 allows prefix attributes on class interfaces and protocols. 1096 // FIXME: This still needs better diagnostics. We should only accept 1097 // attributes here, no types, etc. 1098 if (getLangOpts().ObjC && Tok.is(tok::at)) { 1099 SourceLocation AtLoc = ConsumeToken(); // the "@" 1100 if (!Tok.isObjCAtKeyword(tok::objc_interface) && 1101 !Tok.isObjCAtKeyword(tok::objc_protocol) && 1102 !Tok.isObjCAtKeyword(tok::objc_implementation)) { 1103 Diag(Tok, diag::err_objc_unexpected_attr); 1104 SkipUntil(tok::semi); 1105 return nullptr; 1106 } 1107 1108 DS.abort(); 1109 1110 const char *PrevSpec = nullptr; 1111 unsigned DiagID; 1112 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID, 1113 Actions.getASTContext().getPrintingPolicy())) 1114 Diag(AtLoc, DiagID) << PrevSpec; 1115 1116 if (Tok.isObjCAtKeyword(tok::objc_protocol)) 1117 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()); 1118 1119 if (Tok.isObjCAtKeyword(tok::objc_implementation)) 1120 return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes()); 1121 1122 return Actions.ConvertDeclToDeclGroup( 1123 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes())); 1124 } 1125 1126 // If the declspec consisted only of 'extern' and we have a string 1127 // literal following it, this must be a C++ linkage specifier like 1128 // 'extern "C"'. 1129 if (getLangOpts().CPlusPlus && isTokenStringLiteral() && 1130 DS.getStorageClassSpec() == DeclSpec::SCS_extern && 1131 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) { 1132 Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File); 1133 return Actions.ConvertDeclToDeclGroup(TheDecl); 1134 } 1135 1136 return ParseDeclGroup(DS, DeclaratorContext::File); 1137 } 1138 1139 Parser::DeclGroupPtrTy 1140 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs, 1141 ParsingDeclSpec *DS, 1142 AccessSpecifier AS) { 1143 if (DS) { 1144 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS); 1145 } else { 1146 ParsingDeclSpec PDS(*this); 1147 // Must temporarily exit the objective-c container scope for 1148 // parsing c constructs and re-enter objc container scope 1149 // afterwards. 1150 ObjCDeclContextSwitch ObjCDC(*this); 1151 1152 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS); 1153 } 1154 } 1155 1156 /// ParseFunctionDefinition - We parsed and verified that the specified 1157 /// Declarator is well formed. If this is a K&R-style function, read the 1158 /// parameters declaration-list, then start the compound-statement. 1159 /// 1160 /// function-definition: [C99 6.9.1] 1161 /// decl-specs declarator declaration-list[opt] compound-statement 1162 /// [C90] function-definition: [C99 6.7.1] - implicit int result 1163 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 1164 /// [C++] function-definition: [C++ 8.4] 1165 /// decl-specifier-seq[opt] declarator ctor-initializer[opt] 1166 /// function-body 1167 /// [C++] function-definition: [C++ 8.4] 1168 /// decl-specifier-seq[opt] declarator function-try-block 1169 /// 1170 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, 1171 const ParsedTemplateInfo &TemplateInfo, 1172 LateParsedAttrList *LateParsedAttrs) { 1173 // Poison SEH identifiers so they are flagged as illegal in function bodies. 1174 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 1175 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 1176 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); 1177 1178 // If this is C90 and the declspecs were completely missing, fudge in an 1179 // implicit int. We do this here because this is the only place where 1180 // declaration-specifiers are completely optional in the grammar. 1181 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) { 1182 const char *PrevSpec; 1183 unsigned DiagID; 1184 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); 1185 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int, 1186 D.getIdentifierLoc(), 1187 PrevSpec, DiagID, 1188 Policy); 1189 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin()); 1190 } 1191 1192 // If this declaration was formed with a K&R-style identifier list for the 1193 // arguments, parse declarations for all of the args next. 1194 // int foo(a,b) int a; float b; {} 1195 if (FTI.isKNRPrototype()) 1196 ParseKNRParamDeclarations(D); 1197 1198 // We should have either an opening brace or, in a C++ constructor, 1199 // we may have a colon. 1200 if (Tok.isNot(tok::l_brace) && 1201 (!getLangOpts().CPlusPlus || 1202 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && 1203 Tok.isNot(tok::equal)))) { 1204 Diag(Tok, diag::err_expected_fn_body); 1205 1206 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1207 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 1208 1209 // If we didn't find the '{', bail out. 1210 if (Tok.isNot(tok::l_brace)) 1211 return nullptr; 1212 } 1213 1214 // Check to make sure that any normal attributes are allowed to be on 1215 // a definition. Late parsed attributes are checked at the end. 1216 if (Tok.isNot(tok::equal)) { 1217 for (const ParsedAttr &AL : D.getAttributes()) 1218 if (AL.isKnownToGCC() && !AL.isCXX11Attribute()) 1219 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL; 1220 } 1221 1222 // In delayed template parsing mode, for function template we consume the 1223 // tokens and store them for late parsing at the end of the translation unit. 1224 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) && 1225 TemplateInfo.Kind == ParsedTemplateInfo::Template && 1226 Actions.canDelayFunctionBody(D)) { 1227 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams); 1228 1229 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1230 Scope::CompoundStmtScope); 1231 Scope *ParentScope = getCurScope()->getParent(); 1232 1233 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 1234 Decl *DP = Actions.HandleDeclarator(ParentScope, D, 1235 TemplateParameterLists); 1236 D.complete(DP); 1237 D.getMutableDeclSpec().abort(); 1238 1239 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) && 1240 trySkippingFunctionBody()) { 1241 BodyScope.Exit(); 1242 return Actions.ActOnSkippedFunctionBody(DP); 1243 } 1244 1245 CachedTokens Toks; 1246 LexTemplateFunctionForLateParsing(Toks); 1247 1248 if (DP) { 1249 FunctionDecl *FnD = DP->getAsFunction(); 1250 Actions.CheckForFunctionRedefinition(FnD); 1251 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks); 1252 } 1253 return DP; 1254 } 1255 else if (CurParsedObjCImpl && 1256 !TemplateInfo.TemplateParams && 1257 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || 1258 Tok.is(tok::colon)) && 1259 Actions.CurContext->isTranslationUnit()) { 1260 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1261 Scope::CompoundStmtScope); 1262 Scope *ParentScope = getCurScope()->getParent(); 1263 1264 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 1265 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D, 1266 MultiTemplateParamsArg()); 1267 D.complete(FuncDecl); 1268 D.getMutableDeclSpec().abort(); 1269 if (FuncDecl) { 1270 // Consume the tokens and store them for later parsing. 1271 StashAwayMethodOrFunctionBodyTokens(FuncDecl); 1272 CurParsedObjCImpl->HasCFunction = true; 1273 return FuncDecl; 1274 } 1275 // FIXME: Should we really fall through here? 1276 } 1277 1278 // Enter a scope for the function body. 1279 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | 1280 Scope::CompoundStmtScope); 1281 1282 // Tell the actions module that we have entered a function definition with the 1283 // specified Declarator for the function. 1284 Sema::SkipBodyInfo SkipBody; 1285 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D, 1286 TemplateInfo.TemplateParams 1287 ? *TemplateInfo.TemplateParams 1288 : MultiTemplateParamsArg(), 1289 &SkipBody); 1290 1291 if (SkipBody.ShouldSkip) { 1292 SkipFunctionBody(); 1293 return Res; 1294 } 1295 1296 // Break out of the ParsingDeclarator context before we parse the body. 1297 D.complete(Res); 1298 1299 // Break out of the ParsingDeclSpec context, too. This const_cast is 1300 // safe because we're always the sole owner. 1301 D.getMutableDeclSpec().abort(); 1302 1303 // With abbreviated function templates - we need to explicitly add depth to 1304 // account for the implicit template parameter list induced by the template. 1305 if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res)) 1306 if (Template->isAbbreviated() && 1307 Template->getTemplateParameters()->getParam(0)->isImplicit()) 1308 // First template parameter is implicit - meaning no explicit template 1309 // parameter list was specified. 1310 CurTemplateDepthTracker.addDepth(1); 1311 1312 if (TryConsumeToken(tok::equal)) { 1313 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='"); 1314 1315 bool Delete = false; 1316 SourceLocation KWLoc; 1317 if (TryConsumeToken(tok::kw_delete, KWLoc)) { 1318 Diag(KWLoc, getLangOpts().CPlusPlus11 1319 ? diag::warn_cxx98_compat_defaulted_deleted_function 1320 : diag::ext_defaulted_deleted_function) 1321 << 1 /* deleted */; 1322 Actions.SetDeclDeleted(Res, KWLoc); 1323 Delete = true; 1324 } else if (TryConsumeToken(tok::kw_default, KWLoc)) { 1325 Diag(KWLoc, getLangOpts().CPlusPlus11 1326 ? diag::warn_cxx98_compat_defaulted_deleted_function 1327 : diag::ext_defaulted_deleted_function) 1328 << 0 /* defaulted */; 1329 Actions.SetDeclDefaulted(Res, KWLoc); 1330 } else { 1331 llvm_unreachable("function definition after = not 'delete' or 'default'"); 1332 } 1333 1334 if (Tok.is(tok::comma)) { 1335 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) 1336 << Delete; 1337 SkipUntil(tok::semi); 1338 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after, 1339 Delete ? "delete" : "default")) { 1340 SkipUntil(tok::semi); 1341 } 1342 1343 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr; 1344 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false); 1345 return Res; 1346 } 1347 1348 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) && 1349 trySkippingFunctionBody()) { 1350 BodyScope.Exit(); 1351 Actions.ActOnSkippedFunctionBody(Res); 1352 return Actions.ActOnFinishFunctionBody(Res, nullptr, false); 1353 } 1354 1355 if (Tok.is(tok::kw_try)) 1356 return ParseFunctionTryBlock(Res, BodyScope); 1357 1358 // If we have a colon, then we're probably parsing a C++ 1359 // ctor-initializer. 1360 if (Tok.is(tok::colon)) { 1361 ParseConstructorInitializer(Res); 1362 1363 // Recover from error. 1364 if (!Tok.is(tok::l_brace)) { 1365 BodyScope.Exit(); 1366 Actions.ActOnFinishFunctionBody(Res, nullptr); 1367 return Res; 1368 } 1369 } else 1370 Actions.ActOnDefaultCtorInitializers(Res); 1371 1372 // Late attributes are parsed in the same scope as the function body. 1373 if (LateParsedAttrs) 1374 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true); 1375 1376 return ParseFunctionStatementBody(Res, BodyScope); 1377 } 1378 1379 void Parser::SkipFunctionBody() { 1380 if (Tok.is(tok::equal)) { 1381 SkipUntil(tok::semi); 1382 return; 1383 } 1384 1385 bool IsFunctionTryBlock = Tok.is(tok::kw_try); 1386 if (IsFunctionTryBlock) 1387 ConsumeToken(); 1388 1389 CachedTokens Skipped; 1390 if (ConsumeAndStoreFunctionPrologue(Skipped)) 1391 SkipMalformedDecl(); 1392 else { 1393 SkipUntil(tok::r_brace); 1394 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) { 1395 SkipUntil(tok::l_brace); 1396 SkipUntil(tok::r_brace); 1397 } 1398 } 1399 } 1400 1401 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides 1402 /// types for a function with a K&R-style identifier list for arguments. 1403 void Parser::ParseKNRParamDeclarations(Declarator &D) { 1404 // We know that the top-level of this declarator is a function. 1405 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 1406 1407 // Enter function-declaration scope, limiting any declarators to the 1408 // function prototype scope, including parameter declarators. 1409 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | 1410 Scope::FunctionDeclarationScope | Scope::DeclScope); 1411 1412 // Read all the argument declarations. 1413 while (isDeclarationSpecifier()) { 1414 SourceLocation DSStart = Tok.getLocation(); 1415 1416 // Parse the common declaration-specifiers piece. 1417 DeclSpec DS(AttrFactory); 1418 ParseDeclarationSpecifiers(DS); 1419 1420 // C99 6.9.1p6: 'each declaration in the declaration list shall have at 1421 // least one declarator'. 1422 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with 1423 // the declarations though. It's trivial to ignore them, really hard to do 1424 // anything else with them. 1425 if (TryConsumeToken(tok::semi)) { 1426 Diag(DSStart, diag::err_declaration_does_not_declare_param); 1427 continue; 1428 } 1429 1430 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other 1431 // than register. 1432 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1433 DS.getStorageClassSpec() != DeclSpec::SCS_register) { 1434 Diag(DS.getStorageClassSpecLoc(), 1435 diag::err_invalid_storage_class_in_func_decl); 1436 DS.ClearStorageClassSpecs(); 1437 } 1438 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) { 1439 Diag(DS.getThreadStorageClassSpecLoc(), 1440 diag::err_invalid_storage_class_in_func_decl); 1441 DS.ClearStorageClassSpecs(); 1442 } 1443 1444 // Parse the first declarator attached to this declspec. 1445 Declarator ParmDeclarator(DS, DeclaratorContext::KNRTypeList); 1446 ParseDeclarator(ParmDeclarator); 1447 1448 // Handle the full declarator list. 1449 while (1) { 1450 // If attributes are present, parse them. 1451 MaybeParseGNUAttributes(ParmDeclarator); 1452 1453 // Ask the actions module to compute the type for this declarator. 1454 Decl *Param = 1455 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 1456 1457 if (Param && 1458 // A missing identifier has already been diagnosed. 1459 ParmDeclarator.getIdentifier()) { 1460 1461 // Scan the argument list looking for the correct param to apply this 1462 // type. 1463 for (unsigned i = 0; ; ++i) { 1464 // C99 6.9.1p6: those declarators shall declare only identifiers from 1465 // the identifier list. 1466 if (i == FTI.NumParams) { 1467 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param) 1468 << ParmDeclarator.getIdentifier(); 1469 break; 1470 } 1471 1472 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) { 1473 // Reject redefinitions of parameters. 1474 if (FTI.Params[i].Param) { 1475 Diag(ParmDeclarator.getIdentifierLoc(), 1476 diag::err_param_redefinition) 1477 << ParmDeclarator.getIdentifier(); 1478 } else { 1479 FTI.Params[i].Param = Param; 1480 } 1481 break; 1482 } 1483 } 1484 } 1485 1486 // If we don't have a comma, it is either the end of the list (a ';') or 1487 // an error, bail out. 1488 if (Tok.isNot(tok::comma)) 1489 break; 1490 1491 ParmDeclarator.clear(); 1492 1493 // Consume the comma. 1494 ParmDeclarator.setCommaLoc(ConsumeToken()); 1495 1496 // Parse the next declarator. 1497 ParseDeclarator(ParmDeclarator); 1498 } 1499 1500 // Consume ';' and continue parsing. 1501 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) 1502 continue; 1503 1504 // Otherwise recover by skipping to next semi or mandatory function body. 1505 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch)) 1506 break; 1507 TryConsumeToken(tok::semi); 1508 } 1509 1510 // The actions module must verify that all arguments were declared. 1511 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation()); 1512 } 1513 1514 1515 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not 1516 /// allowed to be a wide string, and is not subject to character translation. 1517 /// Unlike GCC, we also diagnose an empty string literal when parsing for an 1518 /// asm label as opposed to an asm statement, because such a construct does not 1519 /// behave well. 1520 /// 1521 /// [GNU] asm-string-literal: 1522 /// string-literal 1523 /// 1524 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) { 1525 if (!isTokenStringLiteral()) { 1526 Diag(Tok, diag::err_expected_string_literal) 1527 << /*Source='in...'*/0 << "'asm'"; 1528 return ExprError(); 1529 } 1530 1531 ExprResult AsmString(ParseStringLiteralExpression()); 1532 if (!AsmString.isInvalid()) { 1533 const auto *SL = cast<StringLiteral>(AsmString.get()); 1534 if (!SL->isAscii()) { 1535 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1536 << SL->isWide() 1537 << SL->getSourceRange(); 1538 return ExprError(); 1539 } 1540 if (ForAsmLabel && SL->getString().empty()) { 1541 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1542 << 2 /* an empty */ << SL->getSourceRange(); 1543 return ExprError(); 1544 } 1545 } 1546 return AsmString; 1547 } 1548 1549 /// ParseSimpleAsm 1550 /// 1551 /// [GNU] simple-asm-expr: 1552 /// 'asm' '(' asm-string-literal ')' 1553 /// 1554 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) { 1555 assert(Tok.is(tok::kw_asm) && "Not an asm!"); 1556 SourceLocation Loc = ConsumeToken(); 1557 1558 if (isGNUAsmQualifier(Tok)) { 1559 // Remove from the end of 'asm' to the end of the asm qualifier. 1560 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc), 1561 PP.getLocForEndOfToken(Tok.getLocation())); 1562 Diag(Tok, diag::err_global_asm_qualifier_ignored) 1563 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok)) 1564 << FixItHint::CreateRemoval(RemovalRange); 1565 ConsumeToken(); 1566 } 1567 1568 BalancedDelimiterTracker T(*this, tok::l_paren); 1569 if (T.consumeOpen()) { 1570 Diag(Tok, diag::err_expected_lparen_after) << "asm"; 1571 return ExprError(); 1572 } 1573 1574 ExprResult Result(ParseAsmStringLiteral(ForAsmLabel)); 1575 1576 if (!Result.isInvalid()) { 1577 // Close the paren and get the location of the end bracket 1578 T.consumeClose(); 1579 if (EndLoc) 1580 *EndLoc = T.getCloseLocation(); 1581 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) { 1582 if (EndLoc) 1583 *EndLoc = Tok.getLocation(); 1584 ConsumeParen(); 1585 } 1586 1587 return Result; 1588 } 1589 1590 /// Get the TemplateIdAnnotation from the token and put it in the 1591 /// cleanup pool so that it gets destroyed when parsing the current top level 1592 /// declaration is finished. 1593 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) { 1594 assert(tok.is(tok::annot_template_id) && "Expected template-id token"); 1595 TemplateIdAnnotation * 1596 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue()); 1597 return Id; 1598 } 1599 1600 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) { 1601 // Push the current token back into the token stream (or revert it if it is 1602 // cached) and use an annotation scope token for current token. 1603 if (PP.isBacktrackEnabled()) 1604 PP.RevertCachedTokens(1); 1605 else 1606 PP.EnterToken(Tok, /*IsReinject=*/true); 1607 Tok.setKind(tok::annot_cxxscope); 1608 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1609 Tok.setAnnotationRange(SS.getRange()); 1610 1611 // In case the tokens were cached, have Preprocessor replace them 1612 // with the annotation token. We don't need to do this if we've 1613 // just reverted back to a prior state. 1614 if (IsNewAnnotation) 1615 PP.AnnotateCachedTokens(Tok); 1616 } 1617 1618 /// Attempt to classify the name at the current token position. This may 1619 /// form a type, scope or primary expression annotation, or replace the token 1620 /// with a typo-corrected keyword. This is only appropriate when the current 1621 /// name must refer to an entity which has already been declared. 1622 /// 1623 /// \param CCC Indicates how to perform typo-correction for this name. If NULL, 1624 /// no typo correction will be performed. 1625 Parser::AnnotatedNameKind 1626 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC) { 1627 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope)); 1628 1629 const bool EnteringContext = false; 1630 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1631 1632 CXXScopeSpec SS; 1633 if (getLangOpts().CPlusPlus && 1634 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1635 /*ObjectHadErrors=*/false, 1636 EnteringContext)) 1637 return ANK_Error; 1638 1639 if (Tok.isNot(tok::identifier) || SS.isInvalid()) { 1640 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation)) 1641 return ANK_Error; 1642 return ANK_Unresolved; 1643 } 1644 1645 IdentifierInfo *Name = Tok.getIdentifierInfo(); 1646 SourceLocation NameLoc = Tok.getLocation(); 1647 1648 // FIXME: Move the tentative declaration logic into ClassifyName so we can 1649 // typo-correct to tentatively-declared identifiers. 1650 if (isTentativelyDeclared(Name)) { 1651 // Identifier has been tentatively declared, and thus cannot be resolved as 1652 // an expression. Fall back to annotating it as a type. 1653 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation)) 1654 return ANK_Error; 1655 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl; 1656 } 1657 1658 Token Next = NextToken(); 1659 1660 // Look up and classify the identifier. We don't perform any typo-correction 1661 // after a scope specifier, because in general we can't recover from typos 1662 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to 1663 // jump back into scope specifier parsing). 1664 Sema::NameClassification Classification = Actions.ClassifyName( 1665 getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr); 1666 1667 // If name lookup found nothing and we guessed that this was a template name, 1668 // double-check before committing to that interpretation. C++20 requires that 1669 // we interpret this as a template-id if it can be, but if it can't be, then 1670 // this is an error recovery case. 1671 if (Classification.getKind() == Sema::NC_UndeclaredTemplate && 1672 isTemplateArgumentList(1) == TPResult::False) { 1673 // It's not a template-id; re-classify without the '<' as a hint. 1674 Token FakeNext = Next; 1675 FakeNext.setKind(tok::unknown); 1676 Classification = 1677 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext, 1678 SS.isEmpty() ? CCC : nullptr); 1679 } 1680 1681 switch (Classification.getKind()) { 1682 case Sema::NC_Error: 1683 return ANK_Error; 1684 1685 case Sema::NC_Keyword: 1686 // The identifier was typo-corrected to a keyword. 1687 Tok.setIdentifierInfo(Name); 1688 Tok.setKind(Name->getTokenID()); 1689 PP.TypoCorrectToken(Tok); 1690 if (SS.isNotEmpty()) 1691 AnnotateScopeToken(SS, !WasScopeAnnotation); 1692 // We've "annotated" this as a keyword. 1693 return ANK_Success; 1694 1695 case Sema::NC_Unknown: 1696 // It's not something we know about. Leave it unannotated. 1697 break; 1698 1699 case Sema::NC_Type: { 1700 SourceLocation BeginLoc = NameLoc; 1701 if (SS.isNotEmpty()) 1702 BeginLoc = SS.getBeginLoc(); 1703 1704 /// An Objective-C object type followed by '<' is a specialization of 1705 /// a parameterized class type or a protocol-qualified type. 1706 ParsedType Ty = Classification.getType(); 1707 if (getLangOpts().ObjC && NextToken().is(tok::less) && 1708 (Ty.get()->isObjCObjectType() || 1709 Ty.get()->isObjCObjectPointerType())) { 1710 // Consume the name. 1711 SourceLocation IdentifierLoc = ConsumeToken(); 1712 SourceLocation NewEndLoc; 1713 TypeResult NewType 1714 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, 1715 /*consumeLastToken=*/false, 1716 NewEndLoc); 1717 if (NewType.isUsable()) 1718 Ty = NewType.get(); 1719 else if (Tok.is(tok::eof)) // Nothing to do here, bail out... 1720 return ANK_Error; 1721 } 1722 1723 Tok.setKind(tok::annot_typename); 1724 setTypeAnnotation(Tok, Ty); 1725 Tok.setAnnotationEndLoc(Tok.getLocation()); 1726 Tok.setLocation(BeginLoc); 1727 PP.AnnotateCachedTokens(Tok); 1728 return ANK_Success; 1729 } 1730 1731 case Sema::NC_OverloadSet: 1732 Tok.setKind(tok::annot_overload_set); 1733 setExprAnnotation(Tok, Classification.getExpression()); 1734 Tok.setAnnotationEndLoc(NameLoc); 1735 if (SS.isNotEmpty()) 1736 Tok.setLocation(SS.getBeginLoc()); 1737 PP.AnnotateCachedTokens(Tok); 1738 return ANK_Success; 1739 1740 case Sema::NC_NonType: 1741 Tok.setKind(tok::annot_non_type); 1742 setNonTypeAnnotation(Tok, Classification.getNonTypeDecl()); 1743 Tok.setLocation(NameLoc); 1744 Tok.setAnnotationEndLoc(NameLoc); 1745 PP.AnnotateCachedTokens(Tok); 1746 if (SS.isNotEmpty()) 1747 AnnotateScopeToken(SS, !WasScopeAnnotation); 1748 return ANK_Success; 1749 1750 case Sema::NC_UndeclaredNonType: 1751 case Sema::NC_DependentNonType: 1752 Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType 1753 ? tok::annot_non_type_undeclared 1754 : tok::annot_non_type_dependent); 1755 setIdentifierAnnotation(Tok, Name); 1756 Tok.setLocation(NameLoc); 1757 Tok.setAnnotationEndLoc(NameLoc); 1758 PP.AnnotateCachedTokens(Tok); 1759 if (SS.isNotEmpty()) 1760 AnnotateScopeToken(SS, !WasScopeAnnotation); 1761 return ANK_Success; 1762 1763 case Sema::NC_TypeTemplate: 1764 if (Next.isNot(tok::less)) { 1765 // This may be a type template being used as a template template argument. 1766 if (SS.isNotEmpty()) 1767 AnnotateScopeToken(SS, !WasScopeAnnotation); 1768 return ANK_TemplateName; 1769 } 1770 LLVM_FALLTHROUGH; 1771 case Sema::NC_VarTemplate: 1772 case Sema::NC_FunctionTemplate: 1773 case Sema::NC_UndeclaredTemplate: { 1774 // We have a type, variable or function template followed by '<'. 1775 ConsumeToken(); 1776 UnqualifiedId Id; 1777 Id.setIdentifier(Name, NameLoc); 1778 if (AnnotateTemplateIdToken( 1779 TemplateTy::make(Classification.getTemplateName()), 1780 Classification.getTemplateNameKind(), SS, SourceLocation(), Id)) 1781 return ANK_Error; 1782 return ANK_Success; 1783 } 1784 case Sema::NC_Concept: { 1785 UnqualifiedId Id; 1786 Id.setIdentifier(Name, NameLoc); 1787 if (Next.is(tok::less)) 1788 // We have a concept name followed by '<'. Consume the identifier token so 1789 // we reach the '<' and annotate it. 1790 ConsumeToken(); 1791 if (AnnotateTemplateIdToken( 1792 TemplateTy::make(Classification.getTemplateName()), 1793 Classification.getTemplateNameKind(), SS, SourceLocation(), Id, 1794 /*AllowTypeAnnotation=*/false, /*TypeConstraint=*/true)) 1795 return ANK_Error; 1796 return ANK_Success; 1797 } 1798 } 1799 1800 // Unable to classify the name, but maybe we can annotate a scope specifier. 1801 if (SS.isNotEmpty()) 1802 AnnotateScopeToken(SS, !WasScopeAnnotation); 1803 return ANK_Unresolved; 1804 } 1805 1806 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) { 1807 assert(Tok.isNot(tok::identifier)); 1808 Diag(Tok, diag::ext_keyword_as_ident) 1809 << PP.getSpelling(Tok) 1810 << DisableKeyword; 1811 if (DisableKeyword) 1812 Tok.getIdentifierInfo()->revertTokenIDToIdentifier(); 1813 Tok.setKind(tok::identifier); 1814 return true; 1815 } 1816 1817 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 1818 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 1819 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 1820 /// with a single annotation token representing the typename or C++ scope 1821 /// respectively. 1822 /// This simplifies handling of C++ scope specifiers and allows efficient 1823 /// backtracking without the need to re-parse and resolve nested-names and 1824 /// typenames. 1825 /// It will mainly be called when we expect to treat identifiers as typenames 1826 /// (if they are typenames). For example, in C we do not expect identifiers 1827 /// inside expressions to be treated as typenames so it will not be called 1828 /// for expressions in C. 1829 /// The benefit for C/ObjC is that a typename will be annotated and 1830 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName 1831 /// will not be called twice, once to check whether we have a declaration 1832 /// specifier, and another one to get the actual type inside 1833 /// ParseDeclarationSpecifiers). 1834 /// 1835 /// This returns true if an error occurred. 1836 /// 1837 /// Note that this routine emits an error if you call it with ::new or ::delete 1838 /// as the current tokens, so only call it in contexts where these are invalid. 1839 bool Parser::TryAnnotateTypeOrScopeToken() { 1840 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 1841 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) || 1842 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) || 1843 Tok.is(tok::kw___super)) && 1844 "Cannot be a type or scope token!"); 1845 1846 if (Tok.is(tok::kw_typename)) { 1847 // MSVC lets you do stuff like: 1848 // typename typedef T_::D D; 1849 // 1850 // We will consume the typedef token here and put it back after we have 1851 // parsed the first identifier, transforming it into something more like: 1852 // typename T_::D typedef D; 1853 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) { 1854 Token TypedefToken; 1855 PP.Lex(TypedefToken); 1856 bool Result = TryAnnotateTypeOrScopeToken(); 1857 PP.EnterToken(Tok, /*IsReinject=*/true); 1858 Tok = TypedefToken; 1859 if (!Result) 1860 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename); 1861 return Result; 1862 } 1863 1864 // Parse a C++ typename-specifier, e.g., "typename T::type". 1865 // 1866 // typename-specifier: 1867 // 'typename' '::' [opt] nested-name-specifier identifier 1868 // 'typename' '::' [opt] nested-name-specifier template [opt] 1869 // simple-template-id 1870 SourceLocation TypenameLoc = ConsumeToken(); 1871 CXXScopeSpec SS; 1872 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1873 /*ObjectHadErrors=*/false, 1874 /*EnteringContext=*/false, nullptr, 1875 /*IsTypename*/ true)) 1876 return true; 1877 if (SS.isEmpty()) { 1878 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) || 1879 Tok.is(tok::annot_decltype)) { 1880 // Attempt to recover by skipping the invalid 'typename' 1881 if (Tok.is(tok::annot_decltype) || 1882 (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) { 1883 unsigned DiagID = diag::err_expected_qualified_after_typename; 1884 // MS compatibility: MSVC permits using known types with typename. 1885 // e.g. "typedef typename T* pointer_type" 1886 if (getLangOpts().MicrosoftExt) 1887 DiagID = diag::warn_expected_qualified_after_typename; 1888 Diag(Tok.getLocation(), DiagID); 1889 return false; 1890 } 1891 } 1892 if (Tok.isEditorPlaceholder()) 1893 return true; 1894 1895 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); 1896 return true; 1897 } 1898 1899 TypeResult Ty; 1900 if (Tok.is(tok::identifier)) { 1901 // FIXME: check whether the next token is '<', first! 1902 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1903 *Tok.getIdentifierInfo(), 1904 Tok.getLocation()); 1905 } else if (Tok.is(tok::annot_template_id)) { 1906 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1907 if (!TemplateId->mightBeType()) { 1908 Diag(Tok, diag::err_typename_refers_to_non_type_template) 1909 << Tok.getAnnotationRange(); 1910 return true; 1911 } 1912 1913 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1914 TemplateId->NumArgs); 1915 1916 Ty = TemplateId->isInvalid() 1917 ? TypeError() 1918 : Actions.ActOnTypenameType( 1919 getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc, 1920 TemplateId->Template, TemplateId->Name, 1921 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, 1922 TemplateArgsPtr, TemplateId->RAngleLoc); 1923 } else { 1924 Diag(Tok, diag::err_expected_type_name_after_typename) 1925 << SS.getRange(); 1926 return true; 1927 } 1928 1929 SourceLocation EndLoc = Tok.getLastLoc(); 1930 Tok.setKind(tok::annot_typename); 1931 setTypeAnnotation(Tok, Ty); 1932 Tok.setAnnotationEndLoc(EndLoc); 1933 Tok.setLocation(TypenameLoc); 1934 PP.AnnotateCachedTokens(Tok); 1935 return false; 1936 } 1937 1938 // Remembers whether the token was originally a scope annotation. 1939 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1940 1941 CXXScopeSpec SS; 1942 if (getLangOpts().CPlusPlus) 1943 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 1944 /*ObjectHadErrors=*/false, 1945 /*EnteringContext*/ false)) 1946 return true; 1947 1948 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation); 1949 } 1950 1951 /// Try to annotate a type or scope token, having already parsed an 1952 /// optional scope specifier. \p IsNewScope should be \c true unless the scope 1953 /// specifier was extracted from an existing tok::annot_cxxscope annotation. 1954 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, 1955 bool IsNewScope) { 1956 if (Tok.is(tok::identifier)) { 1957 // Determine whether the identifier is a type name. 1958 if (ParsedType Ty = Actions.getTypeName( 1959 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS, 1960 false, NextToken().is(tok::period), nullptr, 1961 /*IsCtorOrDtorName=*/false, 1962 /*NonTrivialTypeSourceInfo*/true, 1963 /*IsClassTemplateDeductionContext*/true)) { 1964 SourceLocation BeginLoc = Tok.getLocation(); 1965 if (SS.isNotEmpty()) // it was a C++ qualified type name. 1966 BeginLoc = SS.getBeginLoc(); 1967 1968 /// An Objective-C object type followed by '<' is a specialization of 1969 /// a parameterized class type or a protocol-qualified type. 1970 if (getLangOpts().ObjC && NextToken().is(tok::less) && 1971 (Ty.get()->isObjCObjectType() || 1972 Ty.get()->isObjCObjectPointerType())) { 1973 // Consume the name. 1974 SourceLocation IdentifierLoc = ConsumeToken(); 1975 SourceLocation NewEndLoc; 1976 TypeResult NewType 1977 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, 1978 /*consumeLastToken=*/false, 1979 NewEndLoc); 1980 if (NewType.isUsable()) 1981 Ty = NewType.get(); 1982 else if (Tok.is(tok::eof)) // Nothing to do here, bail out... 1983 return false; 1984 } 1985 1986 // This is a typename. Replace the current token in-place with an 1987 // annotation type token. 1988 Tok.setKind(tok::annot_typename); 1989 setTypeAnnotation(Tok, Ty); 1990 Tok.setAnnotationEndLoc(Tok.getLocation()); 1991 Tok.setLocation(BeginLoc); 1992 1993 // In case the tokens were cached, have Preprocessor replace 1994 // them with the annotation token. 1995 PP.AnnotateCachedTokens(Tok); 1996 return false; 1997 } 1998 1999 if (!getLangOpts().CPlusPlus) { 2000 // If we're in C, we can't have :: tokens at all (the lexer won't return 2001 // them). If the identifier is not a type, then it can't be scope either, 2002 // just early exit. 2003 return false; 2004 } 2005 2006 // If this is a template-id, annotate with a template-id or type token. 2007 // FIXME: This appears to be dead code. We already have formed template-id 2008 // tokens when parsing the scope specifier; this can never form a new one. 2009 if (NextToken().is(tok::less)) { 2010 TemplateTy Template; 2011 UnqualifiedId TemplateName; 2012 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 2013 bool MemberOfUnknownSpecialization; 2014 if (TemplateNameKind TNK = Actions.isTemplateName( 2015 getCurScope(), SS, 2016 /*hasTemplateKeyword=*/false, TemplateName, 2017 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template, 2018 MemberOfUnknownSpecialization)) { 2019 // Only annotate an undeclared template name as a template-id if the 2020 // following tokens have the form of a template argument list. 2021 if (TNK != TNK_Undeclared_template || 2022 isTemplateArgumentList(1) != TPResult::False) { 2023 // Consume the identifier. 2024 ConsumeToken(); 2025 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 2026 TemplateName)) { 2027 // If an unrecoverable error occurred, we need to return true here, 2028 // because the token stream is in a damaged state. We may not 2029 // return a valid identifier. 2030 return true; 2031 } 2032 } 2033 } 2034 } 2035 2036 // The current token, which is either an identifier or a 2037 // template-id, is not part of the annotation. Fall through to 2038 // push that token back into the stream and complete the C++ scope 2039 // specifier annotation. 2040 } 2041 2042 if (Tok.is(tok::annot_template_id)) { 2043 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2044 if (TemplateId->Kind == TNK_Type_template) { 2045 // A template-id that refers to a type was parsed into a 2046 // template-id annotation in a context where we weren't allowed 2047 // to produce a type annotation token. Update the template-id 2048 // annotation token to a type annotation token now. 2049 AnnotateTemplateIdTokenAsType(SS); 2050 return false; 2051 } 2052 } 2053 2054 if (SS.isEmpty()) 2055 return false; 2056 2057 // A C++ scope specifier that isn't followed by a typename. 2058 AnnotateScopeToken(SS, IsNewScope); 2059 return false; 2060 } 2061 2062 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only 2063 /// annotates C++ scope specifiers and template-ids. This returns 2064 /// true if there was an error that could not be recovered from. 2065 /// 2066 /// Note that this routine emits an error if you call it with ::new or ::delete 2067 /// as the current tokens, so only call it in contexts where these are invalid. 2068 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { 2069 assert(getLangOpts().CPlusPlus && 2070 "Call sites of this function should be guarded by checking for C++"); 2071 assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!"); 2072 2073 CXXScopeSpec SS; 2074 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 2075 /*ObjectHadErrors=*/false, 2076 EnteringContext)) 2077 return true; 2078 if (SS.isEmpty()) 2079 return false; 2080 2081 AnnotateScopeToken(SS, true); 2082 return false; 2083 } 2084 2085 bool Parser::isTokenEqualOrEqualTypo() { 2086 tok::TokenKind Kind = Tok.getKind(); 2087 switch (Kind) { 2088 default: 2089 return false; 2090 case tok::ampequal: // &= 2091 case tok::starequal: // *= 2092 case tok::plusequal: // += 2093 case tok::minusequal: // -= 2094 case tok::exclaimequal: // != 2095 case tok::slashequal: // /= 2096 case tok::percentequal: // %= 2097 case tok::lessequal: // <= 2098 case tok::lesslessequal: // <<= 2099 case tok::greaterequal: // >= 2100 case tok::greatergreaterequal: // >>= 2101 case tok::caretequal: // ^= 2102 case tok::pipeequal: // |= 2103 case tok::equalequal: // == 2104 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal) 2105 << Kind 2106 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "="); 2107 LLVM_FALLTHROUGH; 2108 case tok::equal: 2109 return true; 2110 } 2111 } 2112 2113 SourceLocation Parser::handleUnexpectedCodeCompletionToken() { 2114 assert(Tok.is(tok::code_completion)); 2115 PrevTokLocation = Tok.getLocation(); 2116 2117 for (Scope *S = getCurScope(); S; S = S->getParent()) { 2118 if (S->getFlags() & Scope::FnScope) { 2119 cutOffParsing(); 2120 Actions.CodeCompleteOrdinaryName(getCurScope(), 2121 Sema::PCC_RecoveryInFunction); 2122 return PrevTokLocation; 2123 } 2124 2125 if (S->getFlags() & Scope::ClassScope) { 2126 cutOffParsing(); 2127 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); 2128 return PrevTokLocation; 2129 } 2130 } 2131 2132 cutOffParsing(); 2133 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); 2134 return PrevTokLocation; 2135 } 2136 2137 // Code-completion pass-through functions 2138 2139 void Parser::CodeCompleteDirective(bool InConditional) { 2140 Actions.CodeCompletePreprocessorDirective(InConditional); 2141 } 2142 2143 void Parser::CodeCompleteInConditionalExclusion() { 2144 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope()); 2145 } 2146 2147 void Parser::CodeCompleteMacroName(bool IsDefinition) { 2148 Actions.CodeCompletePreprocessorMacroName(IsDefinition); 2149 } 2150 2151 void Parser::CodeCompletePreprocessorExpression() { 2152 Actions.CodeCompletePreprocessorExpression(); 2153 } 2154 2155 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro, 2156 MacroInfo *MacroInfo, 2157 unsigned ArgumentIndex) { 2158 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 2159 ArgumentIndex); 2160 } 2161 2162 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) { 2163 Actions.CodeCompleteIncludedFile(Dir, IsAngled); 2164 } 2165 2166 void Parser::CodeCompleteNaturalLanguage() { 2167 Actions.CodeCompleteNaturalLanguage(); 2168 } 2169 2170 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { 2171 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) && 2172 "Expected '__if_exists' or '__if_not_exists'"); 2173 Result.IsIfExists = Tok.is(tok::kw___if_exists); 2174 Result.KeywordLoc = ConsumeToken(); 2175 2176 BalancedDelimiterTracker T(*this, tok::l_paren); 2177 if (T.consumeOpen()) { 2178 Diag(Tok, diag::err_expected_lparen_after) 2179 << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); 2180 return true; 2181 } 2182 2183 // Parse nested-name-specifier. 2184 if (getLangOpts().CPlusPlus) 2185 ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr, 2186 /*ObjectHadErrors=*/false, 2187 /*EnteringContext=*/false); 2188 2189 // Check nested-name specifier. 2190 if (Result.SS.isInvalid()) { 2191 T.skipToEnd(); 2192 return true; 2193 } 2194 2195 // Parse the unqualified-id. 2196 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused. 2197 if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr, 2198 /*ObjectHadErrors=*/false, /*EnteringContext*/ false, 2199 /*AllowDestructorName*/ true, 2200 /*AllowConstructorName*/ true, 2201 /*AllowDeductionGuide*/ false, &TemplateKWLoc, 2202 Result.Name)) { 2203 T.skipToEnd(); 2204 return true; 2205 } 2206 2207 if (T.consumeClose()) 2208 return true; 2209 2210 // Check if the symbol exists. 2211 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, 2212 Result.IsIfExists, Result.SS, 2213 Result.Name)) { 2214 case Sema::IER_Exists: 2215 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip; 2216 break; 2217 2218 case Sema::IER_DoesNotExist: 2219 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip; 2220 break; 2221 2222 case Sema::IER_Dependent: 2223 Result.Behavior = IEB_Dependent; 2224 break; 2225 2226 case Sema::IER_Error: 2227 return true; 2228 } 2229 2230 return false; 2231 } 2232 2233 void Parser::ParseMicrosoftIfExistsExternalDeclaration() { 2234 IfExistsCondition Result; 2235 if (ParseMicrosoftIfExistsCondition(Result)) 2236 return; 2237 2238 BalancedDelimiterTracker Braces(*this, tok::l_brace); 2239 if (Braces.consumeOpen()) { 2240 Diag(Tok, diag::err_expected) << tok::l_brace; 2241 return; 2242 } 2243 2244 switch (Result.Behavior) { 2245 case IEB_Parse: 2246 // Parse declarations below. 2247 break; 2248 2249 case IEB_Dependent: 2250 llvm_unreachable("Cannot have a dependent external declaration"); 2251 2252 case IEB_Skip: 2253 Braces.skipToEnd(); 2254 return; 2255 } 2256 2257 // Parse the declarations. 2258 // FIXME: Support module import within __if_exists? 2259 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 2260 ParsedAttributesWithRange attrs(AttrFactory); 2261 MaybeParseCXX11Attributes(attrs); 2262 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs); 2263 if (Result && !getCurScope()->getParent()) 2264 Actions.getASTConsumer().HandleTopLevelDecl(Result.get()); 2265 } 2266 Braces.consumeClose(); 2267 } 2268 2269 /// Parse a declaration beginning with the 'module' keyword or C++20 2270 /// context-sensitive keyword (optionally preceded by 'export'). 2271 /// 2272 /// module-declaration: [Modules TS + P0629R0] 2273 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';' 2274 /// 2275 /// global-module-fragment: [C++2a] 2276 /// 'module' ';' top-level-declaration-seq[opt] 2277 /// module-declaration: [C++2a] 2278 /// 'export'[opt] 'module' module-name module-partition[opt] 2279 /// attribute-specifier-seq[opt] ';' 2280 /// private-module-fragment: [C++2a] 2281 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt] 2282 Parser::DeclGroupPtrTy Parser::ParseModuleDecl(bool IsFirstDecl) { 2283 SourceLocation StartLoc = Tok.getLocation(); 2284 2285 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export) 2286 ? Sema::ModuleDeclKind::Interface 2287 : Sema::ModuleDeclKind::Implementation; 2288 2289 assert( 2290 (Tok.is(tok::kw_module) || 2291 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) && 2292 "not a module declaration"); 2293 SourceLocation ModuleLoc = ConsumeToken(); 2294 2295 // Attributes appear after the module name, not before. 2296 // FIXME: Suggest moving the attributes later with a fixit. 2297 DiagnoseAndSkipCXX11Attributes(); 2298 2299 // Parse a global-module-fragment, if present. 2300 if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) { 2301 SourceLocation SemiLoc = ConsumeToken(); 2302 if (!IsFirstDecl) { 2303 Diag(StartLoc, diag::err_global_module_introducer_not_at_start) 2304 << SourceRange(StartLoc, SemiLoc); 2305 return nullptr; 2306 } 2307 if (MDK == Sema::ModuleDeclKind::Interface) { 2308 Diag(StartLoc, diag::err_module_fragment_exported) 2309 << /*global*/0 << FixItHint::CreateRemoval(StartLoc); 2310 } 2311 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc); 2312 } 2313 2314 // Parse a private-module-fragment, if present. 2315 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) && 2316 NextToken().is(tok::kw_private)) { 2317 if (MDK == Sema::ModuleDeclKind::Interface) { 2318 Diag(StartLoc, diag::err_module_fragment_exported) 2319 << /*private*/1 << FixItHint::CreateRemoval(StartLoc); 2320 } 2321 ConsumeToken(); 2322 SourceLocation PrivateLoc = ConsumeToken(); 2323 DiagnoseAndSkipCXX11Attributes(); 2324 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi); 2325 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc); 2326 } 2327 2328 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2329 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false)) 2330 return nullptr; 2331 2332 // Parse the optional module-partition. 2333 if (Tok.is(tok::colon)) { 2334 SourceLocation ColonLoc = ConsumeToken(); 2335 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition; 2336 if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/false)) 2337 return nullptr; 2338 2339 // FIXME: Support module partition declarations. 2340 Diag(ColonLoc, diag::err_unsupported_module_partition) 2341 << SourceRange(ColonLoc, Partition.back().second); 2342 // Recover by parsing as a non-partition. 2343 } 2344 2345 // We don't support any module attributes yet; just parse them and diagnose. 2346 ParsedAttributesWithRange Attrs(AttrFactory); 2347 MaybeParseCXX11Attributes(Attrs); 2348 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr); 2349 2350 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2351 2352 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, IsFirstDecl); 2353 } 2354 2355 /// Parse a module import declaration. This is essentially the same for 2356 /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC) 2357 /// and the trailing optional attributes (in C++). 2358 /// 2359 /// [ObjC] @import declaration: 2360 /// '@' 'import' module-name ';' 2361 /// [ModTS] module-import-declaration: 2362 /// 'import' module-name attribute-specifier-seq[opt] ';' 2363 /// [C++2a] module-import-declaration: 2364 /// 'export'[opt] 'import' module-name 2365 /// attribute-specifier-seq[opt] ';' 2366 /// 'export'[opt] 'import' module-partition 2367 /// attribute-specifier-seq[opt] ';' 2368 /// 'export'[opt] 'import' header-name 2369 /// attribute-specifier-seq[opt] ';' 2370 Decl *Parser::ParseModuleImport(SourceLocation AtLoc) { 2371 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc; 2372 2373 SourceLocation ExportLoc; 2374 TryConsumeToken(tok::kw_export, ExportLoc); 2375 2376 assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier) 2377 : Tok.isObjCAtKeyword(tok::objc_import)) && 2378 "Improper start to module import"); 2379 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import); 2380 SourceLocation ImportLoc = ConsumeToken(); 2381 2382 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2383 Module *HeaderUnit = nullptr; 2384 2385 if (Tok.is(tok::header_name)) { 2386 // This is a header import that the preprocessor decided we should skip 2387 // because it was malformed in some way. Parse and ignore it; it's already 2388 // been diagnosed. 2389 ConsumeToken(); 2390 } else if (Tok.is(tok::annot_header_unit)) { 2391 // This is a header import that the preprocessor mapped to a module import. 2392 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue()); 2393 ConsumeAnnotationToken(); 2394 } else if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon)) { 2395 SourceLocation ColonLoc = ConsumeToken(); 2396 if (ParseModuleName(ImportLoc, Path, /*IsImport*/true)) 2397 return nullptr; 2398 2399 // FIXME: Support module partition import. 2400 Diag(ColonLoc, diag::err_unsupported_module_partition) 2401 << SourceRange(ColonLoc, Path.back().second); 2402 return nullptr; 2403 } else { 2404 if (ParseModuleName(ImportLoc, Path, /*IsImport*/true)) 2405 return nullptr; 2406 } 2407 2408 ParsedAttributesWithRange Attrs(AttrFactory); 2409 MaybeParseCXX11Attributes(Attrs); 2410 // We don't support any module import attributes yet. 2411 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr); 2412 2413 if (PP.hadModuleLoaderFatalFailure()) { 2414 // With a fatal failure in the module loader, we abort parsing. 2415 cutOffParsing(); 2416 return nullptr; 2417 } 2418 2419 DeclResult Import; 2420 if (HeaderUnit) 2421 Import = 2422 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit); 2423 else if (!Path.empty()) 2424 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path); 2425 ExpectAndConsumeSemi(diag::err_module_expected_semi); 2426 if (Import.isInvalid()) 2427 return nullptr; 2428 2429 // Using '@import' in framework headers requires modules to be enabled so that 2430 // the header is parseable. Emit a warning to make the user aware. 2431 if (IsObjCAtImport && AtLoc.isValid()) { 2432 auto &SrcMgr = PP.getSourceManager(); 2433 auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc)); 2434 if (FE && llvm::sys::path::parent_path(FE->getDir()->getName()) 2435 .endswith(".framework")) 2436 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header); 2437 } 2438 2439 return Import.get(); 2440 } 2441 2442 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same 2443 /// grammar). 2444 /// 2445 /// module-name: 2446 /// module-name-qualifier[opt] identifier 2447 /// module-name-qualifier: 2448 /// module-name-qualifier[opt] identifier '.' 2449 bool Parser::ParseModuleName( 2450 SourceLocation UseLoc, 2451 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, 2452 bool IsImport) { 2453 // Parse the module path. 2454 while (true) { 2455 if (!Tok.is(tok::identifier)) { 2456 if (Tok.is(tok::code_completion)) { 2457 cutOffParsing(); 2458 Actions.CodeCompleteModuleImport(UseLoc, Path); 2459 return true; 2460 } 2461 2462 Diag(Tok, diag::err_module_expected_ident) << IsImport; 2463 SkipUntil(tok::semi); 2464 return true; 2465 } 2466 2467 // Record this part of the module path. 2468 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); 2469 ConsumeToken(); 2470 2471 if (Tok.isNot(tok::period)) 2472 return false; 2473 2474 ConsumeToken(); 2475 } 2476 } 2477 2478 /// Try recover parser when module annotation appears where it must not 2479 /// be found. 2480 /// \returns false if the recover was successful and parsing may be continued, or 2481 /// true if parser must bail out to top level and handle the token there. 2482 bool Parser::parseMisplacedModuleImport() { 2483 while (true) { 2484 switch (Tok.getKind()) { 2485 case tok::annot_module_end: 2486 // If we recovered from a misplaced module begin, we expect to hit a 2487 // misplaced module end too. Stay in the current context when this 2488 // happens. 2489 if (MisplacedModuleBeginCount) { 2490 --MisplacedModuleBeginCount; 2491 Actions.ActOnModuleEnd(Tok.getLocation(), 2492 reinterpret_cast<Module *>( 2493 Tok.getAnnotationValue())); 2494 ConsumeAnnotationToken(); 2495 continue; 2496 } 2497 // Inform caller that recovery failed, the error must be handled at upper 2498 // level. This will generate the desired "missing '}' at end of module" 2499 // diagnostics on the way out. 2500 return true; 2501 case tok::annot_module_begin: 2502 // Recover by entering the module (Sema will diagnose). 2503 Actions.ActOnModuleBegin(Tok.getLocation(), 2504 reinterpret_cast<Module *>( 2505 Tok.getAnnotationValue())); 2506 ConsumeAnnotationToken(); 2507 ++MisplacedModuleBeginCount; 2508 continue; 2509 case tok::annot_module_include: 2510 // Module import found where it should not be, for instance, inside a 2511 // namespace. Recover by importing the module. 2512 Actions.ActOnModuleInclude(Tok.getLocation(), 2513 reinterpret_cast<Module *>( 2514 Tok.getAnnotationValue())); 2515 ConsumeAnnotationToken(); 2516 // If there is another module import, process it. 2517 continue; 2518 default: 2519 return false; 2520 } 2521 } 2522 return false; 2523 } 2524 2525 bool BalancedDelimiterTracker::diagnoseOverflow() { 2526 P.Diag(P.Tok, diag::err_bracket_depth_exceeded) 2527 << P.getLangOpts().BracketDepth; 2528 P.Diag(P.Tok, diag::note_bracket_depth); 2529 P.cutOffParsing(); 2530 return true; 2531 } 2532 2533 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, 2534 const char *Msg, 2535 tok::TokenKind SkipToTok) { 2536 LOpen = P.Tok.getLocation(); 2537 if (P.ExpectAndConsume(Kind, DiagID, Msg)) { 2538 if (SkipToTok != tok::unknown) 2539 P.SkipUntil(SkipToTok, Parser::StopAtSemi); 2540 return true; 2541 } 2542 2543 if (getDepth() < P.getLangOpts().BracketDepth) 2544 return false; 2545 2546 return diagnoseOverflow(); 2547 } 2548 2549 bool BalancedDelimiterTracker::diagnoseMissingClose() { 2550 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter"); 2551 2552 if (P.Tok.is(tok::annot_module_end)) 2553 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close; 2554 else 2555 P.Diag(P.Tok, diag::err_expected) << Close; 2556 P.Diag(LOpen, diag::note_matching) << Kind; 2557 2558 // If we're not already at some kind of closing bracket, skip to our closing 2559 // token. 2560 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) && 2561 P.Tok.isNot(tok::r_square) && 2562 P.SkipUntil(Close, FinalToken, 2563 Parser::StopAtSemi | Parser::StopBeforeMatch) && 2564 P.Tok.is(Close)) 2565 LClose = P.ConsumeAnyToken(); 2566 return true; 2567 } 2568 2569 void BalancedDelimiterTracker::skipToEnd() { 2570 P.SkipUntil(Close, Parser::StopBeforeMatch); 2571 consumeClose(); 2572 } 2573