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