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