1 //===--- Parser.cpp - C Language Family Parser ----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Parser interfaces. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Parse/Parser.h" 15 #include "clang/Parse/ParseDiagnostic.h" 16 #include "clang/Sema/DeclSpec.h" 17 #include "clang/Sema/Scope.h" 18 #include "clang/Sema/ParsedTemplate.h" 19 #include "llvm/Support/raw_ostream.h" 20 #include "RAIIObjectsForParser.h" 21 #include "ParsePragma.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/ASTConsumer.h" 24 using namespace clang; 25 26 IdentifierInfo *Parser::getSEHExceptKeyword() { 27 // __except is accepted as a (contextual) keyword 28 if (!Ident__except && (getLang().MicrosoftExt || getLang().Borland)) 29 Ident__except = PP.getIdentifierInfo("__except"); 30 31 return Ident__except; 32 } 33 34 Parser::Parser(Preprocessor &pp, Sema &actions) 35 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()), 36 GreaterThanIsOperator(true), ColonIsSacred(false), 37 InMessageExpression(false), TemplateParameterDepth(0) { 38 Tok.setKind(tok::eof); 39 Actions.CurScope = 0; 40 NumCachedScopes = 0; 41 ParenCount = BracketCount = BraceCount = 0; 42 ObjCImpDecl = 0; 43 44 // Add #pragma handlers. These are removed and destroyed in the 45 // destructor. 46 AlignHandler.reset(new PragmaAlignHandler(actions)); 47 PP.AddPragmaHandler(AlignHandler.get()); 48 49 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler(actions)); 50 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get()); 51 52 OptionsHandler.reset(new PragmaOptionsHandler(actions)); 53 PP.AddPragmaHandler(OptionsHandler.get()); 54 55 PackHandler.reset(new PragmaPackHandler(actions)); 56 PP.AddPragmaHandler(PackHandler.get()); 57 58 MSStructHandler.reset(new PragmaMSStructHandler(actions)); 59 PP.AddPragmaHandler(MSStructHandler.get()); 60 61 UnusedHandler.reset(new PragmaUnusedHandler(actions, *this)); 62 PP.AddPragmaHandler(UnusedHandler.get()); 63 64 WeakHandler.reset(new PragmaWeakHandler(actions)); 65 PP.AddPragmaHandler(WeakHandler.get()); 66 67 FPContractHandler.reset(new PragmaFPContractHandler(actions, *this)); 68 PP.AddPragmaHandler("STDC", FPContractHandler.get()); 69 70 if (getLang().OpenCL) { 71 OpenCLExtensionHandler.reset( 72 new PragmaOpenCLExtensionHandler(actions, *this)); 73 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get()); 74 75 PP.AddPragmaHandler("OPENCL", FPContractHandler.get()); 76 } 77 78 PP.setCodeCompletionHandler(*this); 79 } 80 81 /// If a crash happens while the parser is active, print out a line indicating 82 /// what the current token is. 83 void PrettyStackTraceParserEntry::print(raw_ostream &OS) const { 84 const Token &Tok = P.getCurToken(); 85 if (Tok.is(tok::eof)) { 86 OS << "<eof> parser at end of file\n"; 87 return; 88 } 89 90 if (Tok.getLocation().isInvalid()) { 91 OS << "<unknown> parser at unknown location\n"; 92 return; 93 } 94 95 const Preprocessor &PP = P.getPreprocessor(); 96 Tok.getLocation().print(OS, PP.getSourceManager()); 97 if (Tok.isAnnotation()) 98 OS << ": at annotation token \n"; 99 else 100 OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n"; 101 } 102 103 104 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) { 105 return Diags.Report(Loc, DiagID); 106 } 107 108 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) { 109 return Diag(Tok.getLocation(), DiagID); 110 } 111 112 /// \brief Emits a diagnostic suggesting parentheses surrounding a 113 /// given range. 114 /// 115 /// \param Loc The location where we'll emit the diagnostic. 116 /// \param Loc The kind of diagnostic to emit. 117 /// \param ParenRange Source range enclosing code that should be parenthesized. 118 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK, 119 SourceRange ParenRange) { 120 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd()); 121 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 122 // We can't display the parentheses, so just dig the 123 // warning/error and return. 124 Diag(Loc, DK); 125 return; 126 } 127 128 Diag(Loc, DK) 129 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 130 << FixItHint::CreateInsertion(EndLoc, ")"); 131 } 132 133 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) { 134 switch (ExpectedTok) { 135 case tok::semi: return Tok.is(tok::colon); // : for ; 136 default: return false; 137 } 138 } 139 140 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the 141 /// input. If so, it is consumed and false is returned. 142 /// 143 /// If the input is malformed, this emits the specified diagnostic. Next, if 144 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is 145 /// returned. 146 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID, 147 const char *Msg, tok::TokenKind SkipToTok) { 148 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) { 149 ConsumeAnyToken(); 150 return false; 151 } 152 153 // Detect common single-character typos and resume. 154 if (IsCommonTypo(ExpectedTok, Tok)) { 155 SourceLocation Loc = Tok.getLocation(); 156 Diag(Loc, DiagID) 157 << Msg 158 << FixItHint::CreateReplacement(SourceRange(Loc), 159 getTokenSimpleSpelling(ExpectedTok)); 160 ConsumeAnyToken(); 161 162 // Pretend there wasn't a problem. 163 return false; 164 } 165 166 const char *Spelling = 0; 167 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); 168 if (EndLoc.isValid() && 169 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) { 170 // Show what code to insert to fix this problem. 171 Diag(EndLoc, DiagID) 172 << Msg 173 << FixItHint::CreateInsertion(EndLoc, Spelling); 174 } else 175 Diag(Tok, DiagID) << Msg; 176 177 if (SkipToTok != tok::unknown) 178 SkipUntil(SkipToTok); 179 return true; 180 } 181 182 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { 183 if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) { 184 ConsumeAnyToken(); 185 return false; 186 } 187 188 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && 189 NextToken().is(tok::semi)) { 190 Diag(Tok, diag::err_extraneous_token_before_semi) 191 << PP.getSpelling(Tok) 192 << FixItHint::CreateRemoval(Tok.getLocation()); 193 ConsumeAnyToken(); // The ')' or ']'. 194 ConsumeToken(); // The ';'. 195 return false; 196 } 197 198 return ExpectAndConsume(tok::semi, DiagID); 199 } 200 201 //===----------------------------------------------------------------------===// 202 // Error recovery. 203 //===----------------------------------------------------------------------===// 204 205 /// SkipUntil - Read tokens until we get to the specified token, then consume 206 /// it (unless DontConsume is true). Because we cannot guarantee that the 207 /// token will ever occur, this skips to the next token, or to some likely 208 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';' 209 /// character. 210 /// 211 /// If SkipUntil finds the specified token, it returns true, otherwise it 212 /// returns false. 213 bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks, 214 bool StopAtSemi, bool DontConsume, 215 bool StopAtCodeCompletion) { 216 // We always want this function to skip at least one token if the first token 217 // isn't T and if not at EOF. 218 bool isFirstTokenSkipped = true; 219 while (1) { 220 // If we found one of the tokens, stop and return true. 221 for (unsigned i = 0; i != NumToks; ++i) { 222 if (Tok.is(Toks[i])) { 223 if (DontConsume) { 224 // Noop, don't consume the token. 225 } else { 226 ConsumeAnyToken(); 227 } 228 return true; 229 } 230 } 231 232 switch (Tok.getKind()) { 233 case tok::eof: 234 // Ran out of tokens. 235 return false; 236 237 case tok::code_completion: 238 if (!StopAtCodeCompletion) 239 ConsumeToken(); 240 return false; 241 242 case tok::l_paren: 243 // Recursively skip properly-nested parens. 244 ConsumeParen(); 245 SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion); 246 break; 247 case tok::l_square: 248 // Recursively skip properly-nested square brackets. 249 ConsumeBracket(); 250 SkipUntil(tok::r_square, false, false, StopAtCodeCompletion); 251 break; 252 case tok::l_brace: 253 // Recursively skip properly-nested braces. 254 ConsumeBrace(); 255 SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion); 256 break; 257 258 // Okay, we found a ']' or '}' or ')', which we think should be balanced. 259 // Since the user wasn't looking for this token (if they were, it would 260 // already be handled), this isn't balanced. If there is a LHS token at a 261 // higher level, we will assume that this matches the unbalanced token 262 // and return it. Otherwise, this is a spurious RHS token, which we skip. 263 case tok::r_paren: 264 if (ParenCount && !isFirstTokenSkipped) 265 return false; // Matches something. 266 ConsumeParen(); 267 break; 268 case tok::r_square: 269 if (BracketCount && !isFirstTokenSkipped) 270 return false; // Matches something. 271 ConsumeBracket(); 272 break; 273 case tok::r_brace: 274 if (BraceCount && !isFirstTokenSkipped) 275 return false; // Matches something. 276 ConsumeBrace(); 277 break; 278 279 case tok::string_literal: 280 case tok::wide_string_literal: 281 case tok::utf8_string_literal: 282 case tok::utf16_string_literal: 283 case tok::utf32_string_literal: 284 ConsumeStringToken(); 285 break; 286 287 case tok::semi: 288 if (StopAtSemi) 289 return false; 290 // FALL THROUGH. 291 default: 292 // Skip this token. 293 ConsumeToken(); 294 break; 295 } 296 isFirstTokenSkipped = false; 297 } 298 } 299 300 //===----------------------------------------------------------------------===// 301 // Scope manipulation 302 //===----------------------------------------------------------------------===// 303 304 /// EnterScope - Start a new scope. 305 void Parser::EnterScope(unsigned ScopeFlags) { 306 if (NumCachedScopes) { 307 Scope *N = ScopeCache[--NumCachedScopes]; 308 N->Init(getCurScope(), ScopeFlags); 309 Actions.CurScope = N; 310 } else { 311 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags); 312 } 313 } 314 315 /// ExitScope - Pop a scope off the scope stack. 316 void Parser::ExitScope() { 317 assert(getCurScope() && "Scope imbalance!"); 318 319 // Inform the actions module that this scope is going away if there are any 320 // decls in it. 321 if (!getCurScope()->decl_empty()) 322 Actions.ActOnPopScope(Tok.getLocation(), getCurScope()); 323 324 Scope *OldScope = getCurScope(); 325 Actions.CurScope = OldScope->getParent(); 326 327 if (NumCachedScopes == ScopeCacheSize) 328 delete OldScope; 329 else 330 ScopeCache[NumCachedScopes++] = OldScope; 331 } 332 333 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false, 334 /// this object does nothing. 335 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags, 336 bool ManageFlags) 337 : CurScope(ManageFlags ? Self->getCurScope() : 0) { 338 if (CurScope) { 339 OldFlags = CurScope->getFlags(); 340 CurScope->setFlags(ScopeFlags); 341 } 342 } 343 344 /// Restore the flags for the current scope to what they were before this 345 /// object overrode them. 346 Parser::ParseScopeFlags::~ParseScopeFlags() { 347 if (CurScope) 348 CurScope->setFlags(OldFlags); 349 } 350 351 352 //===----------------------------------------------------------------------===// 353 // C99 6.9: External Definitions. 354 //===----------------------------------------------------------------------===// 355 356 Parser::~Parser() { 357 // If we still have scopes active, delete the scope tree. 358 delete getCurScope(); 359 Actions.CurScope = 0; 360 361 // Free the scope cache. 362 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i) 363 delete ScopeCache[i]; 364 365 // Free LateParsedTemplatedFunction nodes. 366 for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin(); 367 it != LateParsedTemplateMap.end(); ++it) 368 delete it->second; 369 370 clearLateParsedObjCMethods(); 371 372 // Remove the pragma handlers we installed. 373 PP.RemovePragmaHandler(AlignHandler.get()); 374 AlignHandler.reset(); 375 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get()); 376 GCCVisibilityHandler.reset(); 377 PP.RemovePragmaHandler(OptionsHandler.get()); 378 OptionsHandler.reset(); 379 PP.RemovePragmaHandler(PackHandler.get()); 380 PackHandler.reset(); 381 PP.RemovePragmaHandler(MSStructHandler.get()); 382 MSStructHandler.reset(); 383 PP.RemovePragmaHandler(UnusedHandler.get()); 384 UnusedHandler.reset(); 385 PP.RemovePragmaHandler(WeakHandler.get()); 386 WeakHandler.reset(); 387 388 if (getLang().OpenCL) { 389 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get()); 390 OpenCLExtensionHandler.reset(); 391 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get()); 392 } 393 394 PP.RemovePragmaHandler("STDC", FPContractHandler.get()); 395 FPContractHandler.reset(); 396 PP.clearCodeCompletionHandler(); 397 } 398 399 /// Initialize - Warm up the parser. 400 /// 401 void Parser::Initialize() { 402 // Create the translation unit scope. Install it as the current scope. 403 assert(getCurScope() == 0 && "A scope is already active?"); 404 EnterScope(Scope::DeclScope); 405 Actions.ActOnTranslationUnitScope(getCurScope()); 406 407 // Prime the lexer look-ahead. 408 ConsumeToken(); 409 410 if (Tok.is(tok::eof) && 411 !getLang().CPlusPlus) // Empty source file is an extension in C 412 Diag(Tok, diag::ext_empty_source_file); 413 414 // Initialization for Objective-C context sensitive keywords recognition. 415 // Referenced in Parser::ParseObjCTypeQualifierList. 416 if (getLang().ObjC1) { 417 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in"); 418 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out"); 419 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout"); 420 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway"); 421 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy"); 422 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref"); 423 } 424 425 Ident_instancetype = 0; 426 Ident_final = 0; 427 Ident_override = 0; 428 429 Ident_super = &PP.getIdentifierTable().get("super"); 430 431 if (getLang().AltiVec) { 432 Ident_vector = &PP.getIdentifierTable().get("vector"); 433 Ident_pixel = &PP.getIdentifierTable().get("pixel"); 434 } 435 436 Ident_introduced = 0; 437 Ident_deprecated = 0; 438 Ident_obsoleted = 0; 439 Ident_unavailable = 0; 440 441 Ident__except = 0; 442 443 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0; 444 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0; 445 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0; 446 447 if(getLang().Borland) { 448 Ident__exception_info = PP.getIdentifierInfo("_exception_info"); 449 Ident___exception_info = PP.getIdentifierInfo("__exception_info"); 450 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation"); 451 Ident__exception_code = PP.getIdentifierInfo("_exception_code"); 452 Ident___exception_code = PP.getIdentifierInfo("__exception_code"); 453 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode"); 454 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination"); 455 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination"); 456 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination"); 457 458 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block); 459 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block); 460 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block); 461 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter); 462 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter); 463 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter); 464 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block); 465 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block); 466 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block); 467 } 468 } 469 470 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the 471 /// action tells us to. This returns true if the EOF was encountered. 472 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) { 473 DelayedCleanupPoint CleanupRAII(TopLevelDeclCleanupPool); 474 475 while (Tok.is(tok::annot_pragma_unused)) 476 HandlePragmaUnused(); 477 478 Result = DeclGroupPtrTy(); 479 if (Tok.is(tok::eof)) { 480 // Late template parsing can begin. 481 if (getLang().DelayedTemplateParsing) 482 Actions.SetLateTemplateParser(LateTemplateParserCallback, this); 483 484 Actions.ActOnEndOfTranslationUnit(); 485 return true; 486 } 487 488 ParsedAttributesWithRange attrs(AttrFactory); 489 MaybeParseCXX0XAttributes(attrs); 490 MaybeParseMicrosoftAttributes(attrs); 491 492 Result = ParseExternalDeclaration(attrs); 493 return false; 494 } 495 496 /// ParseTranslationUnit: 497 /// translation-unit: [C99 6.9] 498 /// external-declaration 499 /// translation-unit external-declaration 500 void Parser::ParseTranslationUnit() { 501 Initialize(); 502 503 DeclGroupPtrTy Res; 504 while (!ParseTopLevelDecl(Res)) 505 /*parse them all*/; 506 507 ExitScope(); 508 assert(getCurScope() == 0 && "Scope imbalance!"); 509 } 510 511 /// ParseExternalDeclaration: 512 /// 513 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl] 514 /// function-definition 515 /// declaration 516 /// [C++0x] empty-declaration 517 /// [GNU] asm-definition 518 /// [GNU] __extension__ external-declaration 519 /// [OBJC] objc-class-definition 520 /// [OBJC] objc-class-declaration 521 /// [OBJC] objc-alias-declaration 522 /// [OBJC] objc-protocol-definition 523 /// [OBJC] objc-method-definition 524 /// [OBJC] @end 525 /// [C++] linkage-specification 526 /// [GNU] asm-definition: 527 /// simple-asm-expr ';' 528 /// 529 /// [C++0x] empty-declaration: 530 /// ';' 531 /// 532 /// [C++0x/GNU] 'extern' 'template' declaration 533 Parser::DeclGroupPtrTy 534 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs, 535 ParsingDeclSpec *DS) { 536 DelayedCleanupPoint CleanupRAII(TopLevelDeclCleanupPool); 537 ParenBraceBracketBalancer BalancerRAIIObj(*this); 538 539 if (PP.isCodeCompletionReached()) { 540 cutOffParsing(); 541 return DeclGroupPtrTy(); 542 } 543 544 Decl *SingleDecl = 0; 545 switch (Tok.getKind()) { 546 case tok::semi: 547 Diag(Tok, getLang().CPlusPlus0x ? 548 diag::warn_cxx98_compat_top_level_semi : diag::ext_top_level_semi) 549 << FixItHint::CreateRemoval(Tok.getLocation()); 550 551 ConsumeToken(); 552 // TODO: Invoke action for top-level semicolon. 553 return DeclGroupPtrTy(); 554 case tok::r_brace: 555 Diag(Tok, diag::err_extraneous_closing_brace); 556 ConsumeBrace(); 557 return DeclGroupPtrTy(); 558 case tok::eof: 559 Diag(Tok, diag::err_expected_external_declaration); 560 return DeclGroupPtrTy(); 561 case tok::kw___extension__: { 562 // __extension__ silences extension warnings in the subexpression. 563 ExtensionRAIIObject O(Diags); // Use RAII to do this. 564 ConsumeToken(); 565 return ParseExternalDeclaration(attrs); 566 } 567 case tok::kw_asm: { 568 ProhibitAttributes(attrs); 569 570 SourceLocation StartLoc = Tok.getLocation(); 571 SourceLocation EndLoc; 572 ExprResult Result(ParseSimpleAsm(&EndLoc)); 573 574 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 575 "top-level asm block"); 576 577 if (Result.isInvalid()) 578 return DeclGroupPtrTy(); 579 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc); 580 break; 581 } 582 case tok::at: 583 return ParseObjCAtDirectives(); 584 case tok::minus: 585 case tok::plus: 586 if (!getLang().ObjC1) { 587 Diag(Tok, diag::err_expected_external_declaration); 588 ConsumeToken(); 589 return DeclGroupPtrTy(); 590 } 591 SingleDecl = ParseObjCMethodDefinition(); 592 break; 593 case tok::code_completion: 594 Actions.CodeCompleteOrdinaryName(getCurScope(), 595 ObjCImpDecl? Sema::PCC_ObjCImplementation 596 : Sema::PCC_Namespace); 597 cutOffParsing(); 598 return DeclGroupPtrTy(); 599 case tok::kw_using: 600 case tok::kw_namespace: 601 case tok::kw_typedef: 602 case tok::kw_template: 603 case tok::kw_export: // As in 'export template' 604 case tok::kw_static_assert: 605 case tok::kw__Static_assert: 606 // A function definition cannot start with a these keywords. 607 { 608 SourceLocation DeclEnd; 609 StmtVector Stmts(Actions); 610 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 611 } 612 613 case tok::kw_static: 614 // Parse (then ignore) 'static' prior to a template instantiation. This is 615 // a GCC extension that we intentionally do not support. 616 if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) { 617 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 618 << 0; 619 SourceLocation DeclEnd; 620 StmtVector Stmts(Actions); 621 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 622 } 623 goto dont_know; 624 625 case tok::kw_inline: 626 if (getLang().CPlusPlus) { 627 tok::TokenKind NextKind = NextToken().getKind(); 628 629 // Inline namespaces. Allowed as an extension even in C++03. 630 if (NextKind == tok::kw_namespace) { 631 SourceLocation DeclEnd; 632 StmtVector Stmts(Actions); 633 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 634 } 635 636 // Parse (then ignore) 'inline' prior to a template instantiation. This is 637 // a GCC extension that we intentionally do not support. 638 if (NextKind == tok::kw_template) { 639 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 640 << 1; 641 SourceLocation DeclEnd; 642 StmtVector Stmts(Actions); 643 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 644 } 645 } 646 goto dont_know; 647 648 case tok::kw_extern: 649 if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) { 650 // Extern templates 651 SourceLocation ExternLoc = ConsumeToken(); 652 SourceLocation TemplateLoc = ConsumeToken(); 653 Diag(ExternLoc, getLang().CPlusPlus0x ? 654 diag::warn_cxx98_compat_extern_template : 655 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc); 656 SourceLocation DeclEnd; 657 return Actions.ConvertDeclToDeclGroup( 658 ParseExplicitInstantiation(Declarator::FileContext, 659 ExternLoc, TemplateLoc, DeclEnd)); 660 } 661 // FIXME: Detect C++ linkage specifications here? 662 goto dont_know; 663 664 case tok::kw___if_exists: 665 case tok::kw___if_not_exists: 666 ParseMicrosoftIfExistsExternalDeclaration(); 667 return DeclGroupPtrTy(); 668 669 default: 670 dont_know: 671 // We can't tell whether this is a function-definition or declaration yet. 672 if (DS) { 673 DS->takeAttributesFrom(attrs); 674 return ParseDeclarationOrFunctionDefinition(*DS); 675 } else { 676 return ParseDeclarationOrFunctionDefinition(attrs); 677 } 678 } 679 680 // This routine returns a DeclGroup, if the thing we parsed only contains a 681 // single decl, convert it now. 682 return Actions.ConvertDeclToDeclGroup(SingleDecl); 683 } 684 685 /// \brief Determine whether the current token, if it occurs after a 686 /// declarator, continues a declaration or declaration list. 687 bool Parser::isDeclarationAfterDeclarator() { 688 // Check for '= delete' or '= default' 689 if (getLang().CPlusPlus && Tok.is(tok::equal)) { 690 const Token &KW = NextToken(); 691 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete)) 692 return false; 693 } 694 695 return Tok.is(tok::equal) || // int X()= -> not a function def 696 Tok.is(tok::comma) || // int X(), -> not a function def 697 Tok.is(tok::semi) || // int X(); -> not a function def 698 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def 699 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def 700 (getLang().CPlusPlus && 701 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++] 702 } 703 704 /// \brief Determine whether the current token, if it occurs after a 705 /// declarator, indicates the start of a function definition. 706 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) { 707 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator"); 708 if (Tok.is(tok::l_brace)) // int X() {} 709 return true; 710 711 // Handle K&R C argument lists: int X(f) int f; {} 712 if (!getLang().CPlusPlus && 713 Declarator.getFunctionTypeInfo().isKNRPrototype()) 714 return isDeclarationSpecifier(); 715 716 if (getLang().CPlusPlus && Tok.is(tok::equal)) { 717 const Token &KW = NextToken(); 718 return KW.is(tok::kw_default) || KW.is(tok::kw_delete); 719 } 720 721 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors) 722 Tok.is(tok::kw_try); // X() try { ... } 723 } 724 725 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or 726 /// a declaration. We can't tell which we have until we read up to the 727 /// compound-statement in function-definition. TemplateParams, if 728 /// non-NULL, provides the template parameters when we're parsing a 729 /// C++ template-declaration. 730 /// 731 /// function-definition: [C99 6.9.1] 732 /// decl-specs declarator declaration-list[opt] compound-statement 733 /// [C90] function-definition: [C99 6.7.1] - implicit int result 734 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 735 /// 736 /// declaration: [C99 6.7] 737 /// declaration-specifiers init-declarator-list[opt] ';' 738 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode] 739 /// [OMP] threadprivate-directive [TODO] 740 /// 741 Parser::DeclGroupPtrTy 742 Parser::ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS, 743 AccessSpecifier AS) { 744 // Parse the common declaration-specifiers piece. 745 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level); 746 747 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 748 // declaration-specifiers init-declarator-list[opt] ';' 749 if (Tok.is(tok::semi)) { 750 ConsumeToken(); 751 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS); 752 DS.complete(TheDecl); 753 return Actions.ConvertDeclToDeclGroup(TheDecl); 754 } 755 756 // ObjC2 allows prefix attributes on class interfaces and protocols. 757 // FIXME: This still needs better diagnostics. We should only accept 758 // attributes here, no types, etc. 759 if (getLang().ObjC2 && Tok.is(tok::at)) { 760 SourceLocation AtLoc = ConsumeToken(); // the "@" 761 if (!Tok.isObjCAtKeyword(tok::objc_interface) && 762 !Tok.isObjCAtKeyword(tok::objc_protocol)) { 763 Diag(Tok, diag::err_objc_unexpected_attr); 764 SkipUntil(tok::semi); // FIXME: better skip? 765 return DeclGroupPtrTy(); 766 } 767 768 DS.abort(); 769 770 const char *PrevSpec = 0; 771 unsigned DiagID; 772 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID)) 773 Diag(AtLoc, DiagID) << PrevSpec; 774 775 if (Tok.isObjCAtKeyword(tok::objc_protocol)) 776 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()); 777 778 return Actions.ConvertDeclToDeclGroup( 779 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes())); 780 } 781 782 // If the declspec consisted only of 'extern' and we have a string 783 // literal following it, this must be a C++ linkage specifier like 784 // 'extern "C"'. 785 if (Tok.is(tok::string_literal) && getLang().CPlusPlus && 786 DS.getStorageClassSpec() == DeclSpec::SCS_extern && 787 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) { 788 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext); 789 return Actions.ConvertDeclToDeclGroup(TheDecl); 790 } 791 792 return ParseDeclGroup(DS, Declarator::FileContext, true); 793 } 794 795 Parser::DeclGroupPtrTy 796 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributes &attrs, 797 AccessSpecifier AS) { 798 ParsingDeclSpec DS(*this); 799 DS.takeAttributesFrom(attrs); 800 // Must temporarily exit the objective-c container scope for 801 // parsing c constructs and re-enter objc container scope 802 // afterwards. 803 ObjCDeclContextSwitch ObjCDC(*this); 804 805 return ParseDeclarationOrFunctionDefinition(DS, AS); 806 } 807 808 /// ParseFunctionDefinition - We parsed and verified that the specified 809 /// Declarator is well formed. If this is a K&R-style function, read the 810 /// parameters declaration-list, then start the compound-statement. 811 /// 812 /// function-definition: [C99 6.9.1] 813 /// decl-specs declarator declaration-list[opt] compound-statement 814 /// [C90] function-definition: [C99 6.7.1] - implicit int result 815 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 816 /// [C++] function-definition: [C++ 8.4] 817 /// decl-specifier-seq[opt] declarator ctor-initializer[opt] 818 /// function-body 819 /// [C++] function-definition: [C++ 8.4] 820 /// decl-specifier-seq[opt] declarator function-try-block 821 /// 822 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, 823 const ParsedTemplateInfo &TemplateInfo) { 824 // Poison the SEH identifiers so they are flagged as illegal in function bodies 825 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 826 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 827 828 // If this is C90 and the declspecs were completely missing, fudge in an 829 // implicit int. We do this here because this is the only place where 830 // declaration-specifiers are completely optional in the grammar. 831 if (getLang().ImplicitInt && D.getDeclSpec().isEmpty()) { 832 const char *PrevSpec; 833 unsigned DiagID; 834 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int, 835 D.getIdentifierLoc(), 836 PrevSpec, DiagID); 837 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin()); 838 } 839 840 // If this declaration was formed with a K&R-style identifier list for the 841 // arguments, parse declarations for all of the args next. 842 // int foo(a,b) int a; float b; {} 843 if (FTI.isKNRPrototype()) 844 ParseKNRParamDeclarations(D); 845 846 847 // We should have either an opening brace or, in a C++ constructor, 848 // we may have a colon. 849 if (Tok.isNot(tok::l_brace) && 850 (!getLang().CPlusPlus || 851 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && 852 Tok.isNot(tok::equal)))) { 853 Diag(Tok, diag::err_expected_fn_body); 854 855 // Skip over garbage, until we get to '{'. Don't eat the '{'. 856 SkipUntil(tok::l_brace, true, true); 857 858 // If we didn't find the '{', bail out. 859 if (Tok.isNot(tok::l_brace)) 860 return 0; 861 } 862 863 // In delayed template parsing mode, for function template we consume the 864 // tokens and store them for late parsing at the end of the translation unit. 865 if (getLang().DelayedTemplateParsing && 866 TemplateInfo.Kind == ParsedTemplateInfo::Template) { 867 MultiTemplateParamsArg TemplateParameterLists(Actions, 868 TemplateInfo.TemplateParams->data(), 869 TemplateInfo.TemplateParams->size()); 870 871 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); 872 Scope *ParentScope = getCurScope()->getParent(); 873 874 D.setFunctionDefinitionKind(FDK_Definition); 875 Decl *DP = Actions.HandleDeclarator(ParentScope, D, 876 move(TemplateParameterLists)); 877 D.complete(DP); 878 D.getMutableDeclSpec().abort(); 879 880 if (DP) { 881 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP); 882 883 FunctionDecl *FnD = 0; 884 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP)) 885 FnD = FunTmpl->getTemplatedDecl(); 886 else 887 FnD = cast<FunctionDecl>(DP); 888 Actions.CheckForFunctionRedefinition(FnD); 889 890 LateParsedTemplateMap[FnD] = LPT; 891 Actions.MarkAsLateParsedTemplate(FnD); 892 LexTemplateFunctionForLateParsing(LPT->Toks); 893 } else { 894 CachedTokens Toks; 895 LexTemplateFunctionForLateParsing(Toks); 896 } 897 return DP; 898 } 899 900 // Enter a scope for the function body. 901 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); 902 903 // Tell the actions module that we have entered a function definition with the 904 // specified Declarator for the function. 905 Decl *Res = TemplateInfo.TemplateParams? 906 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(), 907 MultiTemplateParamsArg(Actions, 908 TemplateInfo.TemplateParams->data(), 909 TemplateInfo.TemplateParams->size()), 910 D) 911 : Actions.ActOnStartOfFunctionDef(getCurScope(), D); 912 913 // Break out of the ParsingDeclarator context before we parse the body. 914 D.complete(Res); 915 916 // Break out of the ParsingDeclSpec context, too. This const_cast is 917 // safe because we're always the sole owner. 918 D.getMutableDeclSpec().abort(); 919 920 if (Tok.is(tok::equal)) { 921 assert(getLang().CPlusPlus && "Only C++ function definitions have '='"); 922 ConsumeToken(); 923 924 Actions.ActOnFinishFunctionBody(Res, 0, false); 925 926 bool Delete = false; 927 SourceLocation KWLoc; 928 if (Tok.is(tok::kw_delete)) { 929 Diag(Tok, getLang().CPlusPlus0x ? 930 diag::warn_cxx98_compat_deleted_function : 931 diag::ext_deleted_function); 932 933 KWLoc = ConsumeToken(); 934 Actions.SetDeclDeleted(Res, KWLoc); 935 Delete = true; 936 } else if (Tok.is(tok::kw_default)) { 937 Diag(Tok, getLang().CPlusPlus0x ? 938 diag::warn_cxx98_compat_defaulted_function : 939 diag::ext_defaulted_function); 940 941 KWLoc = ConsumeToken(); 942 Actions.SetDeclDefaulted(Res, KWLoc); 943 } else { 944 llvm_unreachable("function definition after = not 'delete' or 'default'"); 945 } 946 947 if (Tok.is(tok::comma)) { 948 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) 949 << Delete; 950 SkipUntil(tok::semi); 951 } else { 952 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 953 Delete ? "delete" : "default", tok::semi); 954 } 955 956 return Res; 957 } 958 959 if (Tok.is(tok::kw_try)) 960 return ParseFunctionTryBlock(Res, BodyScope); 961 962 // If we have a colon, then we're probably parsing a C++ 963 // ctor-initializer. 964 if (Tok.is(tok::colon)) { 965 ParseConstructorInitializer(Res); 966 967 // Recover from error. 968 if (!Tok.is(tok::l_brace)) { 969 BodyScope.Exit(); 970 Actions.ActOnFinishFunctionBody(Res, 0); 971 return Res; 972 } 973 } else 974 Actions.ActOnDefaultCtorInitializers(Res); 975 976 return ParseFunctionStatementBody(Res, BodyScope); 977 } 978 979 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides 980 /// types for a function with a K&R-style identifier list for arguments. 981 void Parser::ParseKNRParamDeclarations(Declarator &D) { 982 // We know that the top-level of this declarator is a function. 983 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 984 985 // Enter function-declaration scope, limiting any declarators to the 986 // function prototype scope, including parameter declarators. 987 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope); 988 989 // Read all the argument declarations. 990 while (isDeclarationSpecifier()) { 991 SourceLocation DSStart = Tok.getLocation(); 992 993 // Parse the common declaration-specifiers piece. 994 DeclSpec DS(AttrFactory); 995 ParseDeclarationSpecifiers(DS); 996 997 // C99 6.9.1p6: 'each declaration in the declaration list shall have at 998 // least one declarator'. 999 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with 1000 // the declarations though. It's trivial to ignore them, really hard to do 1001 // anything else with them. 1002 if (Tok.is(tok::semi)) { 1003 Diag(DSStart, diag::err_declaration_does_not_declare_param); 1004 ConsumeToken(); 1005 continue; 1006 } 1007 1008 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other 1009 // than register. 1010 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1011 DS.getStorageClassSpec() != DeclSpec::SCS_register) { 1012 Diag(DS.getStorageClassSpecLoc(), 1013 diag::err_invalid_storage_class_in_func_decl); 1014 DS.ClearStorageClassSpecs(); 1015 } 1016 if (DS.isThreadSpecified()) { 1017 Diag(DS.getThreadSpecLoc(), 1018 diag::err_invalid_storage_class_in_func_decl); 1019 DS.ClearStorageClassSpecs(); 1020 } 1021 1022 // Parse the first declarator attached to this declspec. 1023 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext); 1024 ParseDeclarator(ParmDeclarator); 1025 1026 // Handle the full declarator list. 1027 while (1) { 1028 // If attributes are present, parse them. 1029 MaybeParseGNUAttributes(ParmDeclarator); 1030 1031 // Ask the actions module to compute the type for this declarator. 1032 Decl *Param = 1033 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 1034 1035 if (Param && 1036 // A missing identifier has already been diagnosed. 1037 ParmDeclarator.getIdentifier()) { 1038 1039 // Scan the argument list looking for the correct param to apply this 1040 // type. 1041 for (unsigned i = 0; ; ++i) { 1042 // C99 6.9.1p6: those declarators shall declare only identifiers from 1043 // the identifier list. 1044 if (i == FTI.NumArgs) { 1045 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param) 1046 << ParmDeclarator.getIdentifier(); 1047 break; 1048 } 1049 1050 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) { 1051 // Reject redefinitions of parameters. 1052 if (FTI.ArgInfo[i].Param) { 1053 Diag(ParmDeclarator.getIdentifierLoc(), 1054 diag::err_param_redefinition) 1055 << ParmDeclarator.getIdentifier(); 1056 } else { 1057 FTI.ArgInfo[i].Param = Param; 1058 } 1059 break; 1060 } 1061 } 1062 } 1063 1064 // If we don't have a comma, it is either the end of the list (a ';') or 1065 // an error, bail out. 1066 if (Tok.isNot(tok::comma)) 1067 break; 1068 1069 ParmDeclarator.clear(); 1070 1071 // Consume the comma. 1072 ParmDeclarator.setCommaLoc(ConsumeToken()); 1073 1074 // Parse the next declarator. 1075 ParseDeclarator(ParmDeclarator); 1076 } 1077 1078 if (Tok.is(tok::semi)) { 1079 ConsumeToken(); 1080 } else { 1081 Diag(Tok, diag::err_parse_error); 1082 // Skip to end of block or statement 1083 SkipUntil(tok::semi, true); 1084 if (Tok.is(tok::semi)) 1085 ConsumeToken(); 1086 } 1087 } 1088 1089 // The actions module must verify that all arguments were declared. 1090 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation()); 1091 } 1092 1093 1094 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not 1095 /// allowed to be a wide string, and is not subject to character translation. 1096 /// 1097 /// [GNU] asm-string-literal: 1098 /// string-literal 1099 /// 1100 Parser::ExprResult Parser::ParseAsmStringLiteral() { 1101 switch (Tok.getKind()) { 1102 case tok::string_literal: 1103 break; 1104 case tok::wide_string_literal: { 1105 SourceLocation L = Tok.getLocation(); 1106 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1107 << SourceRange(L, L); 1108 return ExprError(); 1109 } 1110 default: 1111 Diag(Tok, diag::err_expected_string_literal); 1112 return ExprError(); 1113 } 1114 1115 ExprResult Res(ParseStringLiteralExpression()); 1116 if (Res.isInvalid()) return move(Res); 1117 1118 return move(Res); 1119 } 1120 1121 /// ParseSimpleAsm 1122 /// 1123 /// [GNU] simple-asm-expr: 1124 /// 'asm' '(' asm-string-literal ')' 1125 /// 1126 Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) { 1127 assert(Tok.is(tok::kw_asm) && "Not an asm!"); 1128 SourceLocation Loc = ConsumeToken(); 1129 1130 if (Tok.is(tok::kw_volatile)) { 1131 // Remove from the end of 'asm' to the end of 'volatile'. 1132 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc), 1133 PP.getLocForEndOfToken(Tok.getLocation())); 1134 1135 Diag(Tok, diag::warn_file_asm_volatile) 1136 << FixItHint::CreateRemoval(RemovalRange); 1137 ConsumeToken(); 1138 } 1139 1140 BalancedDelimiterTracker T(*this, tok::l_paren); 1141 if (T.consumeOpen()) { 1142 Diag(Tok, diag::err_expected_lparen_after) << "asm"; 1143 return ExprError(); 1144 } 1145 1146 ExprResult Result(ParseAsmStringLiteral()); 1147 1148 if (Result.isInvalid()) { 1149 SkipUntil(tok::r_paren, true, true); 1150 if (EndLoc) 1151 *EndLoc = Tok.getLocation(); 1152 ConsumeAnyToken(); 1153 } else { 1154 // Close the paren and get the location of the end bracket 1155 T.consumeClose(); 1156 if (EndLoc) 1157 *EndLoc = T.getCloseLocation(); 1158 } 1159 1160 return move(Result); 1161 } 1162 1163 /// \brief Get the TemplateIdAnnotation from the token and put it in the 1164 /// cleanup pool so that it gets destroyed when parsing the current top level 1165 /// declaration is finished. 1166 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) { 1167 assert(tok.is(tok::annot_template_id) && "Expected template-id token"); 1168 TemplateIdAnnotation * 1169 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue()); 1170 TopLevelDeclCleanupPool.delayMemberFunc< TemplateIdAnnotation, 1171 &TemplateIdAnnotation::Destroy>(Id); 1172 return Id; 1173 } 1174 1175 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 1176 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 1177 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 1178 /// with a single annotation token representing the typename or C++ scope 1179 /// respectively. 1180 /// This simplifies handling of C++ scope specifiers and allows efficient 1181 /// backtracking without the need to re-parse and resolve nested-names and 1182 /// typenames. 1183 /// It will mainly be called when we expect to treat identifiers as typenames 1184 /// (if they are typenames). For example, in C we do not expect identifiers 1185 /// inside expressions to be treated as typenames so it will not be called 1186 /// for expressions in C. 1187 /// The benefit for C/ObjC is that a typename will be annotated and 1188 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName 1189 /// will not be called twice, once to check whether we have a declaration 1190 /// specifier, and another one to get the actual type inside 1191 /// ParseDeclarationSpecifiers). 1192 /// 1193 /// This returns true if an error occurred. 1194 /// 1195 /// Note that this routine emits an error if you call it with ::new or ::delete 1196 /// as the current tokens, so only call it in contexts where these are invalid. 1197 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) { 1198 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) 1199 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) 1200 || Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!"); 1201 1202 if (Tok.is(tok::kw_typename)) { 1203 // Parse a C++ typename-specifier, e.g., "typename T::type". 1204 // 1205 // typename-specifier: 1206 // 'typename' '::' [opt] nested-name-specifier identifier 1207 // 'typename' '::' [opt] nested-name-specifier template [opt] 1208 // simple-template-id 1209 SourceLocation TypenameLoc = ConsumeToken(); 1210 CXXScopeSpec SS; 1211 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(), 1212 /*EnteringContext=*/false, 1213 0, /*IsTypename*/true)) 1214 return true; 1215 if (!SS.isSet()) { 1216 if (getLang().MicrosoftExt) 1217 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename); 1218 else 1219 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); 1220 return true; 1221 } 1222 1223 TypeResult Ty; 1224 if (Tok.is(tok::identifier)) { 1225 // FIXME: check whether the next token is '<', first! 1226 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1227 *Tok.getIdentifierInfo(), 1228 Tok.getLocation()); 1229 } else if (Tok.is(tok::annot_template_id)) { 1230 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1231 if (TemplateId->Kind == TNK_Function_template) { 1232 Diag(Tok, diag::err_typename_refers_to_non_type_template) 1233 << Tok.getAnnotationRange(); 1234 return true; 1235 } 1236 1237 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 1238 TemplateId->getTemplateArgs(), 1239 TemplateId->NumArgs); 1240 1241 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1242 /*FIXME:*/SourceLocation(), 1243 TemplateId->Template, 1244 TemplateId->TemplateNameLoc, 1245 TemplateId->LAngleLoc, 1246 TemplateArgsPtr, 1247 TemplateId->RAngleLoc); 1248 } else { 1249 Diag(Tok, diag::err_expected_type_name_after_typename) 1250 << SS.getRange(); 1251 return true; 1252 } 1253 1254 SourceLocation EndLoc = Tok.getLastLoc(); 1255 Tok.setKind(tok::annot_typename); 1256 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get()); 1257 Tok.setAnnotationEndLoc(EndLoc); 1258 Tok.setLocation(TypenameLoc); 1259 PP.AnnotateCachedTokens(Tok); 1260 return false; 1261 } 1262 1263 // Remembers whether the token was originally a scope annotation. 1264 bool wasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1265 1266 CXXScopeSpec SS; 1267 if (getLang().CPlusPlus) 1268 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1269 return true; 1270 1271 if (Tok.is(tok::identifier)) { 1272 IdentifierInfo *CorrectedII = 0; 1273 // Determine whether the identifier is a type name. 1274 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(), 1275 Tok.getLocation(), getCurScope(), 1276 &SS, false, 1277 NextToken().is(tok::period), 1278 ParsedType(), 1279 /*NonTrivialTypeSourceInfo*/true, 1280 NeedType ? &CorrectedII : NULL)) { 1281 // A FixIt was applied as a result of typo correction 1282 if (CorrectedII) 1283 Tok.setIdentifierInfo(CorrectedII); 1284 // This is a typename. Replace the current token in-place with an 1285 // annotation type token. 1286 Tok.setKind(tok::annot_typename); 1287 setTypeAnnotation(Tok, Ty); 1288 Tok.setAnnotationEndLoc(Tok.getLocation()); 1289 if (SS.isNotEmpty()) // it was a C++ qualified type name. 1290 Tok.setLocation(SS.getBeginLoc()); 1291 1292 // In case the tokens were cached, have Preprocessor replace 1293 // them with the annotation token. 1294 PP.AnnotateCachedTokens(Tok); 1295 return false; 1296 } 1297 1298 if (!getLang().CPlusPlus) { 1299 // If we're in C, we can't have :: tokens at all (the lexer won't return 1300 // them). If the identifier is not a type, then it can't be scope either, 1301 // just early exit. 1302 return false; 1303 } 1304 1305 // If this is a template-id, annotate with a template-id or type token. 1306 if (NextToken().is(tok::less)) { 1307 TemplateTy Template; 1308 UnqualifiedId TemplateName; 1309 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1310 bool MemberOfUnknownSpecialization; 1311 if (TemplateNameKind TNK 1312 = Actions.isTemplateName(getCurScope(), SS, 1313 /*hasTemplateKeyword=*/false, TemplateName, 1314 /*ObjectType=*/ ParsedType(), 1315 EnteringContext, 1316 Template, MemberOfUnknownSpecialization)) { 1317 // Consume the identifier. 1318 ConsumeToken(); 1319 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName)) { 1320 // If an unrecoverable error occurred, we need to return true here, 1321 // because the token stream is in a damaged state. We may not return 1322 // a valid identifier. 1323 return true; 1324 } 1325 } 1326 } 1327 1328 // The current token, which is either an identifier or a 1329 // template-id, is not part of the annotation. Fall through to 1330 // push that token back into the stream and complete the C++ scope 1331 // specifier annotation. 1332 } 1333 1334 if (Tok.is(tok::annot_template_id)) { 1335 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1336 if (TemplateId->Kind == TNK_Type_template) { 1337 // A template-id that refers to a type was parsed into a 1338 // template-id annotation in a context where we weren't allowed 1339 // to produce a type annotation token. Update the template-id 1340 // annotation token to a type annotation token now. 1341 AnnotateTemplateIdTokenAsType(); 1342 return false; 1343 } 1344 } 1345 1346 if (SS.isEmpty()) 1347 return false; 1348 1349 // A C++ scope specifier that isn't followed by a typename. 1350 // Push the current token back into the token stream (or revert it if it is 1351 // cached) and use an annotation scope token for current token. 1352 if (PP.isBacktrackEnabled()) 1353 PP.RevertCachedTokens(1); 1354 else 1355 PP.EnterToken(Tok); 1356 Tok.setKind(tok::annot_cxxscope); 1357 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1358 Tok.setAnnotationRange(SS.getRange()); 1359 1360 // In case the tokens were cached, have Preprocessor replace them 1361 // with the annotation token. We don't need to do this if we've 1362 // just reverted back to the state we were in before being called. 1363 if (!wasScopeAnnotation) 1364 PP.AnnotateCachedTokens(Tok); 1365 return false; 1366 } 1367 1368 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only 1369 /// annotates C++ scope specifiers and template-ids. This returns 1370 /// true if the token was annotated or there was an error that could not be 1371 /// recovered from. 1372 /// 1373 /// Note that this routine emits an error if you call it with ::new or ::delete 1374 /// as the current tokens, so only call it in contexts where these are invalid. 1375 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { 1376 assert(getLang().CPlusPlus && 1377 "Call sites of this function should be guarded by checking for C++"); 1378 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 1379 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || 1380 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!"); 1381 1382 CXXScopeSpec SS; 1383 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1384 return true; 1385 if (SS.isEmpty()) 1386 return false; 1387 1388 // Push the current token back into the token stream (or revert it if it is 1389 // cached) and use an annotation scope token for current token. 1390 if (PP.isBacktrackEnabled()) 1391 PP.RevertCachedTokens(1); 1392 else 1393 PP.EnterToken(Tok); 1394 Tok.setKind(tok::annot_cxxscope); 1395 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1396 Tok.setAnnotationRange(SS.getRange()); 1397 1398 // In case the tokens were cached, have Preprocessor replace them with the 1399 // annotation token. 1400 PP.AnnotateCachedTokens(Tok); 1401 return false; 1402 } 1403 1404 bool Parser::isTokenEqualOrEqualTypo() { 1405 tok::TokenKind Kind = Tok.getKind(); 1406 switch (Kind) { 1407 default: 1408 return false; 1409 case tok::ampequal: // &= 1410 case tok::starequal: // *= 1411 case tok::plusequal: // += 1412 case tok::minusequal: // -= 1413 case tok::exclaimequal: // != 1414 case tok::slashequal: // /= 1415 case tok::percentequal: // %= 1416 case tok::lessequal: // <= 1417 case tok::lesslessequal: // <<= 1418 case tok::greaterequal: // >= 1419 case tok::greatergreaterequal: // >>= 1420 case tok::caretequal: // ^= 1421 case tok::pipeequal: // |= 1422 case tok::equalequal: // == 1423 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal) 1424 << getTokenSimpleSpelling(Kind) 1425 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "="); 1426 case tok::equal: 1427 return true; 1428 } 1429 } 1430 1431 SourceLocation Parser::handleUnexpectedCodeCompletionToken() { 1432 assert(Tok.is(tok::code_completion)); 1433 PrevTokLocation = Tok.getLocation(); 1434 1435 for (Scope *S = getCurScope(); S; S = S->getParent()) { 1436 if (S->getFlags() & Scope::FnScope) { 1437 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction); 1438 cutOffParsing(); 1439 return PrevTokLocation; 1440 } 1441 1442 if (S->getFlags() & Scope::ClassScope) { 1443 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); 1444 cutOffParsing(); 1445 return PrevTokLocation; 1446 } 1447 } 1448 1449 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); 1450 cutOffParsing(); 1451 return PrevTokLocation; 1452 } 1453 1454 // Anchor the Parser::FieldCallback vtable to this translation unit. 1455 // We use a spurious method instead of the destructor because 1456 // destroying FieldCallbacks can actually be slightly 1457 // performance-sensitive. 1458 void Parser::FieldCallback::_anchor() { 1459 } 1460 1461 // Code-completion pass-through functions 1462 1463 void Parser::CodeCompleteDirective(bool InConditional) { 1464 Actions.CodeCompletePreprocessorDirective(InConditional); 1465 } 1466 1467 void Parser::CodeCompleteInConditionalExclusion() { 1468 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope()); 1469 } 1470 1471 void Parser::CodeCompleteMacroName(bool IsDefinition) { 1472 Actions.CodeCompletePreprocessorMacroName(IsDefinition); 1473 } 1474 1475 void Parser::CodeCompletePreprocessorExpression() { 1476 Actions.CodeCompletePreprocessorExpression(); 1477 } 1478 1479 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro, 1480 MacroInfo *MacroInfo, 1481 unsigned ArgumentIndex) { 1482 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 1483 ArgumentIndex); 1484 } 1485 1486 void Parser::CodeCompleteNaturalLanguage() { 1487 Actions.CodeCompleteNaturalLanguage(); 1488 } 1489 1490 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { 1491 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) && 1492 "Expected '__if_exists' or '__if_not_exists'"); 1493 Result.IsIfExists = Tok.is(tok::kw___if_exists); 1494 Result.KeywordLoc = ConsumeToken(); 1495 1496 BalancedDelimiterTracker T(*this, tok::l_paren); 1497 if (T.consumeOpen()) { 1498 Diag(Tok, diag::err_expected_lparen_after) 1499 << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); 1500 return true; 1501 } 1502 1503 // Parse nested-name-specifier. 1504 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(), 1505 /*EnteringContext=*/false); 1506 1507 // Check nested-name specifier. 1508 if (Result.SS.isInvalid()) { 1509 T.skipToEnd(); 1510 return true; 1511 } 1512 1513 // Parse the unqualified-id. 1514 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(), 1515 Result.Name)) { 1516 T.skipToEnd(); 1517 return true; 1518 } 1519 1520 if (T.consumeClose()) 1521 return true; 1522 1523 // Check if the symbol exists. 1524 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, 1525 Result.IsIfExists, Result.SS, 1526 Result.Name)) { 1527 case Sema::IER_Exists: 1528 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip; 1529 break; 1530 1531 case Sema::IER_DoesNotExist: 1532 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip; 1533 break; 1534 1535 case Sema::IER_Dependent: 1536 Result.Behavior = IEB_Dependent; 1537 break; 1538 1539 case Sema::IER_Error: 1540 return true; 1541 } 1542 1543 return false; 1544 } 1545 1546 void Parser::ParseMicrosoftIfExistsExternalDeclaration() { 1547 IfExistsCondition Result; 1548 if (ParseMicrosoftIfExistsCondition(Result)) 1549 return; 1550 1551 BalancedDelimiterTracker Braces(*this, tok::l_brace); 1552 if (Braces.consumeOpen()) { 1553 Diag(Tok, diag::err_expected_lbrace); 1554 return; 1555 } 1556 1557 switch (Result.Behavior) { 1558 case IEB_Parse: 1559 // Parse declarations below. 1560 break; 1561 1562 case IEB_Dependent: 1563 llvm_unreachable("Cannot have a dependent external declaration"); 1564 1565 case IEB_Skip: 1566 Braces.skipToEnd(); 1567 return; 1568 } 1569 1570 // Parse the declarations. 1571 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1572 ParsedAttributesWithRange attrs(AttrFactory); 1573 MaybeParseCXX0XAttributes(attrs); 1574 MaybeParseMicrosoftAttributes(attrs); 1575 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs); 1576 if (Result && !getCurScope()->getParent()) 1577 Actions.getASTConsumer().HandleTopLevelDecl(Result.get()); 1578 } 1579 Braces.consumeClose(); 1580 } 1581 1582 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) { 1583 assert(Tok.isObjCAtKeyword(tok::objc_import) && 1584 "Improper start to module import"); 1585 SourceLocation ImportLoc = ConsumeToken(); 1586 1587 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1588 1589 // Parse the module path. 1590 do { 1591 if (!Tok.is(tok::identifier)) { 1592 Diag(Tok, diag::err_module_expected_ident); 1593 SkipUntil(tok::semi); 1594 return DeclGroupPtrTy(); 1595 } 1596 1597 // Record this part of the module path. 1598 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); 1599 ConsumeToken(); 1600 1601 if (Tok.is(tok::period)) { 1602 ConsumeToken(); 1603 continue; 1604 } 1605 1606 break; 1607 } while (true); 1608 1609 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path); 1610 ExpectAndConsumeSemi(diag::err_module_expected_semi); 1611 if (Import.isInvalid()) 1612 return DeclGroupPtrTy(); 1613 1614 return Actions.ConvertDeclToDeclGroup(Import.get()); 1615 } 1616 1617 bool Parser::BalancedDelimiterTracker::consumeOpen() { 1618 // Try to consume the token we are holding 1619 if (P.Tok.is(Kind)) { 1620 P.QuantityTracker.push(Kind); 1621 Cleanup = true; 1622 if (P.QuantityTracker.getDepth(Kind) < MaxDepth) { 1623 LOpen = P.ConsumeAnyToken(); 1624 return false; 1625 } else { 1626 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow); 1627 P.SkipUntil(tok::eof); 1628 } 1629 } 1630 return true; 1631 } 1632 1633 bool Parser::BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, 1634 const char *Msg, 1635 tok::TokenKind SkipToToc ) { 1636 LOpen = P.Tok.getLocation(); 1637 if (!P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc)) { 1638 P.QuantityTracker.push(Kind); 1639 Cleanup = true; 1640 if (P.QuantityTracker.getDepth(Kind) < MaxDepth) { 1641 return false; 1642 } else { 1643 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow); 1644 P.SkipUntil(tok::eof); 1645 } 1646 } 1647 return true; 1648 } 1649 1650 bool Parser::BalancedDelimiterTracker::consumeClose() { 1651 if (P.Tok.is(Close)) { 1652 LClose = P.ConsumeAnyToken(); 1653 if (Cleanup) 1654 P.QuantityTracker.pop(Kind); 1655 1656 Cleanup = false; 1657 return false; 1658 } else { 1659 const char *LHSName = "unknown"; 1660 diag::kind DID = diag::err_parse_error; 1661 switch (Close) { 1662 default: break; 1663 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break; 1664 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break; 1665 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break; 1666 case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break; 1667 case tok::greatergreatergreater: 1668 LHSName = "<<<"; DID = diag::err_expected_ggg; break; 1669 } 1670 P.Diag(P.Tok, DID); 1671 P.Diag(LOpen, diag::note_matching) << LHSName; 1672 if (P.SkipUntil(Close)) 1673 LClose = P.Tok.getLocation(); 1674 } 1675 return true; 1676 } 1677 1678 void Parser::BalancedDelimiterTracker::skipToEnd() { 1679 P.SkipUntil(Close, false); 1680 Cleanup = false; 1681 } 1682