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