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::annot_pragma_vis: 547 HandlePragmaVisibility(); 548 return DeclGroupPtrTy(); 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_extraneous_closing_brace); 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 case tok::minus: 588 case tok::plus: 589 if (!getLang().ObjC1) { 590 Diag(Tok, diag::err_expected_external_declaration); 591 ConsumeToken(); 592 return DeclGroupPtrTy(); 593 } 594 SingleDecl = ParseObjCMethodDefinition(); 595 break; 596 case tok::code_completion: 597 Actions.CodeCompleteOrdinaryName(getCurScope(), 598 ObjCImpDecl? Sema::PCC_ObjCImplementation 599 : Sema::PCC_Namespace); 600 cutOffParsing(); 601 return DeclGroupPtrTy(); 602 case tok::kw_using: 603 case tok::kw_namespace: 604 case tok::kw_typedef: 605 case tok::kw_template: 606 case tok::kw_export: // As in 'export template' 607 case tok::kw_static_assert: 608 case tok::kw__Static_assert: 609 // A function definition cannot start with a these keywords. 610 { 611 SourceLocation DeclEnd; 612 StmtVector Stmts(Actions); 613 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 614 } 615 616 case tok::kw_static: 617 // Parse (then ignore) 'static' prior to a template instantiation. This is 618 // a GCC extension that we intentionally do not support. 619 if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) { 620 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 621 << 0; 622 SourceLocation DeclEnd; 623 StmtVector Stmts(Actions); 624 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 625 } 626 goto dont_know; 627 628 case tok::kw_inline: 629 if (getLang().CPlusPlus) { 630 tok::TokenKind NextKind = NextToken().getKind(); 631 632 // Inline namespaces. Allowed as an extension even in C++03. 633 if (NextKind == tok::kw_namespace) { 634 SourceLocation DeclEnd; 635 StmtVector Stmts(Actions); 636 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 637 } 638 639 // Parse (then ignore) 'inline' prior to a template instantiation. This is 640 // a GCC extension that we intentionally do not support. 641 if (NextKind == tok::kw_template) { 642 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) 643 << 1; 644 SourceLocation DeclEnd; 645 StmtVector Stmts(Actions); 646 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs); 647 } 648 } 649 goto dont_know; 650 651 case tok::kw_extern: 652 if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) { 653 // Extern templates 654 SourceLocation ExternLoc = ConsumeToken(); 655 SourceLocation TemplateLoc = ConsumeToken(); 656 Diag(ExternLoc, getLang().CPlusPlus0x ? 657 diag::warn_cxx98_compat_extern_template : 658 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc); 659 SourceLocation DeclEnd; 660 return Actions.ConvertDeclToDeclGroup( 661 ParseExplicitInstantiation(Declarator::FileContext, 662 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 default: 673 dont_know: 674 // We can't tell whether this is a function-definition or declaration yet. 675 if (DS) { 676 DS->takeAttributesFrom(attrs); 677 return ParseDeclarationOrFunctionDefinition(*DS); 678 } else { 679 return ParseDeclarationOrFunctionDefinition(attrs); 680 } 681 } 682 683 // This routine returns a DeclGroup, if the thing we parsed only contains a 684 // single decl, convert it now. 685 return Actions.ConvertDeclToDeclGroup(SingleDecl); 686 } 687 688 /// \brief Determine whether the current token, if it occurs after a 689 /// declarator, continues a declaration or declaration list. 690 bool Parser::isDeclarationAfterDeclarator() { 691 // Check for '= delete' or '= default' 692 if (getLang().CPlusPlus && Tok.is(tok::equal)) { 693 const Token &KW = NextToken(); 694 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete)) 695 return false; 696 } 697 698 return Tok.is(tok::equal) || // int X()= -> not a function def 699 Tok.is(tok::comma) || // int X(), -> not a function def 700 Tok.is(tok::semi) || // int X(); -> not a function def 701 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def 702 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def 703 (getLang().CPlusPlus && 704 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++] 705 } 706 707 /// \brief Determine whether the current token, if it occurs after a 708 /// declarator, indicates the start of a function definition. 709 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) { 710 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator"); 711 if (Tok.is(tok::l_brace)) // int X() {} 712 return true; 713 714 // Handle K&R C argument lists: int X(f) int f; {} 715 if (!getLang().CPlusPlus && 716 Declarator.getFunctionTypeInfo().isKNRPrototype()) 717 return isDeclarationSpecifier(); 718 719 if (getLang().CPlusPlus && Tok.is(tok::equal)) { 720 const Token &KW = NextToken(); 721 return KW.is(tok::kw_default) || KW.is(tok::kw_delete); 722 } 723 724 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors) 725 Tok.is(tok::kw_try); // X() try { ... } 726 } 727 728 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or 729 /// a declaration. We can't tell which we have until we read up to the 730 /// compound-statement in function-definition. TemplateParams, if 731 /// non-NULL, provides the template parameters when we're parsing a 732 /// C++ template-declaration. 733 /// 734 /// function-definition: [C99 6.9.1] 735 /// decl-specs declarator declaration-list[opt] compound-statement 736 /// [C90] function-definition: [C99 6.7.1] - implicit int result 737 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 738 /// 739 /// declaration: [C99 6.7] 740 /// declaration-specifiers init-declarator-list[opt] ';' 741 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode] 742 /// [OMP] threadprivate-directive [TODO] 743 /// 744 Parser::DeclGroupPtrTy 745 Parser::ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS, 746 AccessSpecifier AS) { 747 // Parse the common declaration-specifiers piece. 748 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level); 749 750 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 751 // declaration-specifiers init-declarator-list[opt] ';' 752 if (Tok.is(tok::semi)) { 753 ConsumeToken(); 754 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS); 755 DS.complete(TheDecl); 756 return Actions.ConvertDeclToDeclGroup(TheDecl); 757 } 758 759 // ObjC2 allows prefix attributes on class interfaces and protocols. 760 // FIXME: This still needs better diagnostics. We should only accept 761 // attributes here, no types, etc. 762 if (getLang().ObjC2 && Tok.is(tok::at)) { 763 SourceLocation AtLoc = ConsumeToken(); // the "@" 764 if (!Tok.isObjCAtKeyword(tok::objc_interface) && 765 !Tok.isObjCAtKeyword(tok::objc_protocol)) { 766 Diag(Tok, diag::err_objc_unexpected_attr); 767 SkipUntil(tok::semi); // FIXME: better skip? 768 return DeclGroupPtrTy(); 769 } 770 771 DS.abort(); 772 773 const char *PrevSpec = 0; 774 unsigned DiagID; 775 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID)) 776 Diag(AtLoc, DiagID) << PrevSpec; 777 778 if (Tok.isObjCAtKeyword(tok::objc_protocol)) 779 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()); 780 781 return Actions.ConvertDeclToDeclGroup( 782 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes())); 783 } 784 785 // If the declspec consisted only of 'extern' and we have a string 786 // literal following it, this must be a C++ linkage specifier like 787 // 'extern "C"'. 788 if (Tok.is(tok::string_literal) && getLang().CPlusPlus && 789 DS.getStorageClassSpec() == DeclSpec::SCS_extern && 790 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) { 791 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext); 792 return Actions.ConvertDeclToDeclGroup(TheDecl); 793 } 794 795 return ParseDeclGroup(DS, Declarator::FileContext, true); 796 } 797 798 Parser::DeclGroupPtrTy 799 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributes &attrs, 800 AccessSpecifier AS) { 801 ParsingDeclSpec DS(*this); 802 DS.takeAttributesFrom(attrs); 803 // Must temporarily exit the objective-c container scope for 804 // parsing c constructs and re-enter objc container scope 805 // afterwards. 806 ObjCDeclContextSwitch ObjCDC(*this); 807 808 return ParseDeclarationOrFunctionDefinition(DS, AS); 809 } 810 811 /// ParseFunctionDefinition - We parsed and verified that the specified 812 /// Declarator is well formed. If this is a K&R-style function, read the 813 /// parameters declaration-list, then start the compound-statement. 814 /// 815 /// function-definition: [C99 6.9.1] 816 /// decl-specs declarator declaration-list[opt] compound-statement 817 /// [C90] function-definition: [C99 6.7.1] - implicit int result 818 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement 819 /// [C++] function-definition: [C++ 8.4] 820 /// decl-specifier-seq[opt] declarator ctor-initializer[opt] 821 /// function-body 822 /// [C++] function-definition: [C++ 8.4] 823 /// decl-specifier-seq[opt] declarator function-try-block 824 /// 825 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, 826 const ParsedTemplateInfo &TemplateInfo) { 827 // Poison the SEH identifiers so they are flagged as illegal in function bodies 828 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 829 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 830 831 // If this is C90 and the declspecs were completely missing, fudge in an 832 // implicit int. We do this here because this is the only place where 833 // declaration-specifiers are completely optional in the grammar. 834 if (getLang().ImplicitInt && D.getDeclSpec().isEmpty()) { 835 const char *PrevSpec; 836 unsigned DiagID; 837 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int, 838 D.getIdentifierLoc(), 839 PrevSpec, DiagID); 840 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin()); 841 } 842 843 // If this declaration was formed with a K&R-style identifier list for the 844 // arguments, parse declarations for all of the args next. 845 // int foo(a,b) int a; float b; {} 846 if (FTI.isKNRPrototype()) 847 ParseKNRParamDeclarations(D); 848 849 850 // We should have either an opening brace or, in a C++ constructor, 851 // we may have a colon. 852 if (Tok.isNot(tok::l_brace) && 853 (!getLang().CPlusPlus || 854 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && 855 Tok.isNot(tok::equal)))) { 856 Diag(Tok, diag::err_expected_fn_body); 857 858 // Skip over garbage, until we get to '{'. Don't eat the '{'. 859 SkipUntil(tok::l_brace, true, true); 860 861 // If we didn't find the '{', bail out. 862 if (Tok.isNot(tok::l_brace)) 863 return 0; 864 } 865 866 // In delayed template parsing mode, for function template we consume the 867 // tokens and store them for late parsing at the end of the translation unit. 868 if (getLang().DelayedTemplateParsing && 869 TemplateInfo.Kind == ParsedTemplateInfo::Template) { 870 MultiTemplateParamsArg TemplateParameterLists(Actions, 871 TemplateInfo.TemplateParams->data(), 872 TemplateInfo.TemplateParams->size()); 873 874 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); 875 Scope *ParentScope = getCurScope()->getParent(); 876 877 D.setFunctionDefinitionKind(FDK_Definition); 878 Decl *DP = Actions.HandleDeclarator(ParentScope, D, 879 move(TemplateParameterLists)); 880 D.complete(DP); 881 D.getMutableDeclSpec().abort(); 882 883 if (DP) { 884 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP); 885 886 FunctionDecl *FnD = 0; 887 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP)) 888 FnD = FunTmpl->getTemplatedDecl(); 889 else 890 FnD = cast<FunctionDecl>(DP); 891 Actions.CheckForFunctionRedefinition(FnD); 892 893 LateParsedTemplateMap[FnD] = LPT; 894 Actions.MarkAsLateParsedTemplate(FnD); 895 LexTemplateFunctionForLateParsing(LPT->Toks); 896 } else { 897 CachedTokens Toks; 898 LexTemplateFunctionForLateParsing(Toks); 899 } 900 return DP; 901 } 902 903 // Enter a scope for the function body. 904 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); 905 906 // Tell the actions module that we have entered a function definition with the 907 // specified Declarator for the function. 908 Decl *Res = TemplateInfo.TemplateParams? 909 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(), 910 MultiTemplateParamsArg(Actions, 911 TemplateInfo.TemplateParams->data(), 912 TemplateInfo.TemplateParams->size()), 913 D) 914 : Actions.ActOnStartOfFunctionDef(getCurScope(), D); 915 916 // Break out of the ParsingDeclarator context before we parse the body. 917 D.complete(Res); 918 919 // Break out of the ParsingDeclSpec context, too. This const_cast is 920 // safe because we're always the sole owner. 921 D.getMutableDeclSpec().abort(); 922 923 if (Tok.is(tok::equal)) { 924 assert(getLang().CPlusPlus && "Only C++ function definitions have '='"); 925 ConsumeToken(); 926 927 Actions.ActOnFinishFunctionBody(Res, 0, false); 928 929 bool Delete = false; 930 SourceLocation KWLoc; 931 if (Tok.is(tok::kw_delete)) { 932 Diag(Tok, getLang().CPlusPlus0x ? 933 diag::warn_cxx98_compat_deleted_function : 934 diag::ext_deleted_function); 935 936 KWLoc = ConsumeToken(); 937 Actions.SetDeclDeleted(Res, KWLoc); 938 Delete = true; 939 } else if (Tok.is(tok::kw_default)) { 940 Diag(Tok, getLang().CPlusPlus0x ? 941 diag::warn_cxx98_compat_defaulted_function : 942 diag::ext_defaulted_function); 943 944 KWLoc = ConsumeToken(); 945 Actions.SetDeclDefaulted(Res, KWLoc); 946 } else { 947 llvm_unreachable("function definition after = not 'delete' or 'default'"); 948 } 949 950 if (Tok.is(tok::comma)) { 951 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) 952 << Delete; 953 SkipUntil(tok::semi); 954 } else { 955 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 956 Delete ? "delete" : "default", tok::semi); 957 } 958 959 return Res; 960 } 961 962 if (Tok.is(tok::kw_try)) 963 return ParseFunctionTryBlock(Res, BodyScope); 964 965 // If we have a colon, then we're probably parsing a C++ 966 // ctor-initializer. 967 if (Tok.is(tok::colon)) { 968 ParseConstructorInitializer(Res); 969 970 // Recover from error. 971 if (!Tok.is(tok::l_brace)) { 972 BodyScope.Exit(); 973 Actions.ActOnFinishFunctionBody(Res, 0); 974 return Res; 975 } 976 } else 977 Actions.ActOnDefaultCtorInitializers(Res); 978 979 return ParseFunctionStatementBody(Res, BodyScope); 980 } 981 982 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides 983 /// types for a function with a K&R-style identifier list for arguments. 984 void Parser::ParseKNRParamDeclarations(Declarator &D) { 985 // We know that the top-level of this declarator is a function. 986 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 987 988 // Enter function-declaration scope, limiting any declarators to the 989 // function prototype scope, including parameter declarators. 990 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope); 991 992 // Read all the argument declarations. 993 while (isDeclarationSpecifier()) { 994 SourceLocation DSStart = Tok.getLocation(); 995 996 // Parse the common declaration-specifiers piece. 997 DeclSpec DS(AttrFactory); 998 ParseDeclarationSpecifiers(DS); 999 1000 // C99 6.9.1p6: 'each declaration in the declaration list shall have at 1001 // least one declarator'. 1002 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with 1003 // the declarations though. It's trivial to ignore them, really hard to do 1004 // anything else with them. 1005 if (Tok.is(tok::semi)) { 1006 Diag(DSStart, diag::err_declaration_does_not_declare_param); 1007 ConsumeToken(); 1008 continue; 1009 } 1010 1011 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other 1012 // than register. 1013 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1014 DS.getStorageClassSpec() != DeclSpec::SCS_register) { 1015 Diag(DS.getStorageClassSpecLoc(), 1016 diag::err_invalid_storage_class_in_func_decl); 1017 DS.ClearStorageClassSpecs(); 1018 } 1019 if (DS.isThreadSpecified()) { 1020 Diag(DS.getThreadSpecLoc(), 1021 diag::err_invalid_storage_class_in_func_decl); 1022 DS.ClearStorageClassSpecs(); 1023 } 1024 1025 // Parse the first declarator attached to this declspec. 1026 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext); 1027 ParseDeclarator(ParmDeclarator); 1028 1029 // Handle the full declarator list. 1030 while (1) { 1031 // If attributes are present, parse them. 1032 MaybeParseGNUAttributes(ParmDeclarator); 1033 1034 // Ask the actions module to compute the type for this declarator. 1035 Decl *Param = 1036 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); 1037 1038 if (Param && 1039 // A missing identifier has already been diagnosed. 1040 ParmDeclarator.getIdentifier()) { 1041 1042 // Scan the argument list looking for the correct param to apply this 1043 // type. 1044 for (unsigned i = 0; ; ++i) { 1045 // C99 6.9.1p6: those declarators shall declare only identifiers from 1046 // the identifier list. 1047 if (i == FTI.NumArgs) { 1048 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param) 1049 << ParmDeclarator.getIdentifier(); 1050 break; 1051 } 1052 1053 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) { 1054 // Reject redefinitions of parameters. 1055 if (FTI.ArgInfo[i].Param) { 1056 Diag(ParmDeclarator.getIdentifierLoc(), 1057 diag::err_param_redefinition) 1058 << ParmDeclarator.getIdentifier(); 1059 } else { 1060 FTI.ArgInfo[i].Param = Param; 1061 } 1062 break; 1063 } 1064 } 1065 } 1066 1067 // If we don't have a comma, it is either the end of the list (a ';') or 1068 // an error, bail out. 1069 if (Tok.isNot(tok::comma)) 1070 break; 1071 1072 ParmDeclarator.clear(); 1073 1074 // Consume the comma. 1075 ParmDeclarator.setCommaLoc(ConsumeToken()); 1076 1077 // Parse the next declarator. 1078 ParseDeclarator(ParmDeclarator); 1079 } 1080 1081 if (Tok.is(tok::semi)) { 1082 ConsumeToken(); 1083 } else { 1084 Diag(Tok, diag::err_parse_error); 1085 // Skip to end of block or statement 1086 SkipUntil(tok::semi, true); 1087 if (Tok.is(tok::semi)) 1088 ConsumeToken(); 1089 } 1090 } 1091 1092 // The actions module must verify that all arguments were declared. 1093 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation()); 1094 } 1095 1096 1097 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not 1098 /// allowed to be a wide string, and is not subject to character translation. 1099 /// 1100 /// [GNU] asm-string-literal: 1101 /// string-literal 1102 /// 1103 Parser::ExprResult Parser::ParseAsmStringLiteral() { 1104 switch (Tok.getKind()) { 1105 case tok::string_literal: 1106 break; 1107 case tok::wide_string_literal: { 1108 SourceLocation L = Tok.getLocation(); 1109 Diag(Tok, diag::err_asm_operand_wide_string_literal) 1110 << SourceRange(L, L); 1111 return ExprError(); 1112 } 1113 default: 1114 Diag(Tok, diag::err_expected_string_literal); 1115 return ExprError(); 1116 } 1117 1118 ExprResult Res(ParseStringLiteralExpression()); 1119 if (Res.isInvalid()) return move(Res); 1120 1121 return move(Res); 1122 } 1123 1124 /// ParseSimpleAsm 1125 /// 1126 /// [GNU] simple-asm-expr: 1127 /// 'asm' '(' asm-string-literal ')' 1128 /// 1129 Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) { 1130 assert(Tok.is(tok::kw_asm) && "Not an asm!"); 1131 SourceLocation Loc = ConsumeToken(); 1132 1133 if (Tok.is(tok::kw_volatile)) { 1134 // Remove from the end of 'asm' to the end of 'volatile'. 1135 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc), 1136 PP.getLocForEndOfToken(Tok.getLocation())); 1137 1138 Diag(Tok, diag::warn_file_asm_volatile) 1139 << FixItHint::CreateRemoval(RemovalRange); 1140 ConsumeToken(); 1141 } 1142 1143 BalancedDelimiterTracker T(*this, tok::l_paren); 1144 if (T.consumeOpen()) { 1145 Diag(Tok, diag::err_expected_lparen_after) << "asm"; 1146 return ExprError(); 1147 } 1148 1149 ExprResult Result(ParseAsmStringLiteral()); 1150 1151 if (Result.isInvalid()) { 1152 SkipUntil(tok::r_paren, true, true); 1153 if (EndLoc) 1154 *EndLoc = Tok.getLocation(); 1155 ConsumeAnyToken(); 1156 } else { 1157 // Close the paren and get the location of the end bracket 1158 T.consumeClose(); 1159 if (EndLoc) 1160 *EndLoc = T.getCloseLocation(); 1161 } 1162 1163 return move(Result); 1164 } 1165 1166 /// \brief Get the TemplateIdAnnotation from the token and put it in the 1167 /// cleanup pool so that it gets destroyed when parsing the current top level 1168 /// declaration is finished. 1169 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) { 1170 assert(tok.is(tok::annot_template_id) && "Expected template-id token"); 1171 TemplateIdAnnotation * 1172 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue()); 1173 TopLevelDeclCleanupPool.delayMemberFunc< TemplateIdAnnotation, 1174 &TemplateIdAnnotation::Destroy>(Id); 1175 return Id; 1176 } 1177 1178 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 1179 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 1180 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 1181 /// with a single annotation token representing the typename or C++ scope 1182 /// respectively. 1183 /// This simplifies handling of C++ scope specifiers and allows efficient 1184 /// backtracking without the need to re-parse and resolve nested-names and 1185 /// typenames. 1186 /// It will mainly be called when we expect to treat identifiers as typenames 1187 /// (if they are typenames). For example, in C we do not expect identifiers 1188 /// inside expressions to be treated as typenames so it will not be called 1189 /// for expressions in C. 1190 /// The benefit for C/ObjC is that a typename will be annotated and 1191 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName 1192 /// will not be called twice, once to check whether we have a declaration 1193 /// specifier, and another one to get the actual type inside 1194 /// ParseDeclarationSpecifiers). 1195 /// 1196 /// This returns true if an error occurred. 1197 /// 1198 /// Note that this routine emits an error if you call it with ::new or ::delete 1199 /// as the current tokens, so only call it in contexts where these are invalid. 1200 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) { 1201 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) 1202 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) 1203 || Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!"); 1204 1205 if (Tok.is(tok::kw_typename)) { 1206 // Parse a C++ typename-specifier, e.g., "typename T::type". 1207 // 1208 // typename-specifier: 1209 // 'typename' '::' [opt] nested-name-specifier identifier 1210 // 'typename' '::' [opt] nested-name-specifier template [opt] 1211 // simple-template-id 1212 SourceLocation TypenameLoc = ConsumeToken(); 1213 CXXScopeSpec SS; 1214 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(), 1215 /*EnteringContext=*/false, 1216 0, /*IsTypename*/true)) 1217 return true; 1218 if (!SS.isSet()) { 1219 if (getLang().MicrosoftExt) 1220 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename); 1221 else 1222 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); 1223 return true; 1224 } 1225 1226 TypeResult Ty; 1227 if (Tok.is(tok::identifier)) { 1228 // FIXME: check whether the next token is '<', first! 1229 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1230 *Tok.getIdentifierInfo(), 1231 Tok.getLocation()); 1232 } else if (Tok.is(tok::annot_template_id)) { 1233 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1234 if (TemplateId->Kind == TNK_Function_template) { 1235 Diag(Tok, diag::err_typename_refers_to_non_type_template) 1236 << Tok.getAnnotationRange(); 1237 return true; 1238 } 1239 1240 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 1241 TemplateId->getTemplateArgs(), 1242 TemplateId->NumArgs); 1243 1244 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 1245 /*FIXME:*/SourceLocation(), 1246 TemplateId->Template, 1247 TemplateId->TemplateNameLoc, 1248 TemplateId->LAngleLoc, 1249 TemplateArgsPtr, 1250 TemplateId->RAngleLoc); 1251 } else { 1252 Diag(Tok, diag::err_expected_type_name_after_typename) 1253 << SS.getRange(); 1254 return true; 1255 } 1256 1257 SourceLocation EndLoc = Tok.getLastLoc(); 1258 Tok.setKind(tok::annot_typename); 1259 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get()); 1260 Tok.setAnnotationEndLoc(EndLoc); 1261 Tok.setLocation(TypenameLoc); 1262 PP.AnnotateCachedTokens(Tok); 1263 return false; 1264 } 1265 1266 // Remembers whether the token was originally a scope annotation. 1267 bool wasScopeAnnotation = Tok.is(tok::annot_cxxscope); 1268 1269 CXXScopeSpec SS; 1270 if (getLang().CPlusPlus) 1271 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1272 return true; 1273 1274 if (Tok.is(tok::identifier)) { 1275 IdentifierInfo *CorrectedII = 0; 1276 // Determine whether the identifier is a type name. 1277 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(), 1278 Tok.getLocation(), getCurScope(), 1279 &SS, false, 1280 NextToken().is(tok::period), 1281 ParsedType(), 1282 /*IsCtorOrDtorName=*/false, 1283 /*NonTrivialTypeSourceInfo*/true, 1284 NeedType ? &CorrectedII : NULL)) { 1285 // A FixIt was applied as a result of typo correction 1286 if (CorrectedII) 1287 Tok.setIdentifierInfo(CorrectedII); 1288 // This is a typename. Replace the current token in-place with an 1289 // annotation type token. 1290 Tok.setKind(tok::annot_typename); 1291 setTypeAnnotation(Tok, Ty); 1292 Tok.setAnnotationEndLoc(Tok.getLocation()); 1293 if (SS.isNotEmpty()) // it was a C++ qualified type name. 1294 Tok.setLocation(SS.getBeginLoc()); 1295 1296 // In case the tokens were cached, have Preprocessor replace 1297 // them with the annotation token. 1298 PP.AnnotateCachedTokens(Tok); 1299 return false; 1300 } 1301 1302 if (!getLang().CPlusPlus) { 1303 // If we're in C, we can't have :: tokens at all (the lexer won't return 1304 // them). If the identifier is not a type, then it can't be scope either, 1305 // just early exit. 1306 return false; 1307 } 1308 1309 // If this is a template-id, annotate with a template-id or type token. 1310 if (NextToken().is(tok::less)) { 1311 TemplateTy Template; 1312 UnqualifiedId TemplateName; 1313 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1314 bool MemberOfUnknownSpecialization; 1315 if (TemplateNameKind TNK 1316 = Actions.isTemplateName(getCurScope(), SS, 1317 /*hasTemplateKeyword=*/false, TemplateName, 1318 /*ObjectType=*/ ParsedType(), 1319 EnteringContext, 1320 Template, MemberOfUnknownSpecialization)) { 1321 // Consume the identifier. 1322 ConsumeToken(); 1323 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 1324 TemplateName)) { 1325 // If an unrecoverable error occurred, we need to return true here, 1326 // because the token stream is in a damaged state. We may not return 1327 // a valid identifier. 1328 return true; 1329 } 1330 } 1331 } 1332 1333 // The current token, which is either an identifier or a 1334 // template-id, is not part of the annotation. Fall through to 1335 // push that token back into the stream and complete the C++ scope 1336 // specifier annotation. 1337 } 1338 1339 if (Tok.is(tok::annot_template_id)) { 1340 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1341 if (TemplateId->Kind == TNK_Type_template) { 1342 // A template-id that refers to a type was parsed into a 1343 // template-id annotation in a context where we weren't allowed 1344 // to produce a type annotation token. Update the template-id 1345 // annotation token to a type annotation token now. 1346 AnnotateTemplateIdTokenAsType(); 1347 return false; 1348 } 1349 } 1350 1351 if (SS.isEmpty()) 1352 return false; 1353 1354 // A C++ scope specifier that isn't followed by a typename. 1355 // Push the current token back into the token stream (or revert it if it is 1356 // cached) and use an annotation scope token for current token. 1357 if (PP.isBacktrackEnabled()) 1358 PP.RevertCachedTokens(1); 1359 else 1360 PP.EnterToken(Tok); 1361 Tok.setKind(tok::annot_cxxscope); 1362 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1363 Tok.setAnnotationRange(SS.getRange()); 1364 1365 // In case the tokens were cached, have Preprocessor replace them 1366 // with the annotation token. We don't need to do this if we've 1367 // just reverted back to the state we were in before being called. 1368 if (!wasScopeAnnotation) 1369 PP.AnnotateCachedTokens(Tok); 1370 return false; 1371 } 1372 1373 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only 1374 /// annotates C++ scope specifiers and template-ids. This returns 1375 /// true if the token was annotated or there was an error that could not be 1376 /// recovered from. 1377 /// 1378 /// Note that this routine emits an error if you call it with ::new or ::delete 1379 /// as the current tokens, so only call it in contexts where these are invalid. 1380 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { 1381 assert(getLang().CPlusPlus && 1382 "Call sites of this function should be guarded by checking for C++"); 1383 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || 1384 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || 1385 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!"); 1386 1387 CXXScopeSpec SS; 1388 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1389 return true; 1390 if (SS.isEmpty()) 1391 return false; 1392 1393 // Push the current token back into the token stream (or revert it if it is 1394 // cached) and use an annotation scope token for current token. 1395 if (PP.isBacktrackEnabled()) 1396 PP.RevertCachedTokens(1); 1397 else 1398 PP.EnterToken(Tok); 1399 Tok.setKind(tok::annot_cxxscope); 1400 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); 1401 Tok.setAnnotationRange(SS.getRange()); 1402 1403 // In case the tokens were cached, have Preprocessor replace them with the 1404 // annotation token. 1405 PP.AnnotateCachedTokens(Tok); 1406 return false; 1407 } 1408 1409 bool Parser::isTokenEqualOrEqualTypo() { 1410 tok::TokenKind Kind = Tok.getKind(); 1411 switch (Kind) { 1412 default: 1413 return false; 1414 case tok::ampequal: // &= 1415 case tok::starequal: // *= 1416 case tok::plusequal: // += 1417 case tok::minusequal: // -= 1418 case tok::exclaimequal: // != 1419 case tok::slashequal: // /= 1420 case tok::percentequal: // %= 1421 case tok::lessequal: // <= 1422 case tok::lesslessequal: // <<= 1423 case tok::greaterequal: // >= 1424 case tok::greatergreaterequal: // >>= 1425 case tok::caretequal: // ^= 1426 case tok::pipeequal: // |= 1427 case tok::equalequal: // == 1428 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal) 1429 << getTokenSimpleSpelling(Kind) 1430 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "="); 1431 case tok::equal: 1432 return true; 1433 } 1434 } 1435 1436 SourceLocation Parser::handleUnexpectedCodeCompletionToken() { 1437 assert(Tok.is(tok::code_completion)); 1438 PrevTokLocation = Tok.getLocation(); 1439 1440 for (Scope *S = getCurScope(); S; S = S->getParent()) { 1441 if (S->getFlags() & Scope::FnScope) { 1442 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction); 1443 cutOffParsing(); 1444 return PrevTokLocation; 1445 } 1446 1447 if (S->getFlags() & Scope::ClassScope) { 1448 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); 1449 cutOffParsing(); 1450 return PrevTokLocation; 1451 } 1452 } 1453 1454 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); 1455 cutOffParsing(); 1456 return PrevTokLocation; 1457 } 1458 1459 // Anchor the Parser::FieldCallback vtable to this translation unit. 1460 // We use a spurious method instead of the destructor because 1461 // destroying FieldCallbacks can actually be slightly 1462 // performance-sensitive. 1463 void Parser::FieldCallback::_anchor() { 1464 } 1465 1466 // Code-completion pass-through functions 1467 1468 void Parser::CodeCompleteDirective(bool InConditional) { 1469 Actions.CodeCompletePreprocessorDirective(InConditional); 1470 } 1471 1472 void Parser::CodeCompleteInConditionalExclusion() { 1473 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope()); 1474 } 1475 1476 void Parser::CodeCompleteMacroName(bool IsDefinition) { 1477 Actions.CodeCompletePreprocessorMacroName(IsDefinition); 1478 } 1479 1480 void Parser::CodeCompletePreprocessorExpression() { 1481 Actions.CodeCompletePreprocessorExpression(); 1482 } 1483 1484 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro, 1485 MacroInfo *MacroInfo, 1486 unsigned ArgumentIndex) { 1487 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 1488 ArgumentIndex); 1489 } 1490 1491 void Parser::CodeCompleteNaturalLanguage() { 1492 Actions.CodeCompleteNaturalLanguage(); 1493 } 1494 1495 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { 1496 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) && 1497 "Expected '__if_exists' or '__if_not_exists'"); 1498 Result.IsIfExists = Tok.is(tok::kw___if_exists); 1499 Result.KeywordLoc = ConsumeToken(); 1500 1501 BalancedDelimiterTracker T(*this, tok::l_paren); 1502 if (T.consumeOpen()) { 1503 Diag(Tok, diag::err_expected_lparen_after) 1504 << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); 1505 return true; 1506 } 1507 1508 // Parse nested-name-specifier. 1509 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(), 1510 /*EnteringContext=*/false); 1511 1512 // Check nested-name specifier. 1513 if (Result.SS.isInvalid()) { 1514 T.skipToEnd(); 1515 return true; 1516 } 1517 1518 // Parse the unqualified-id. 1519 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused. 1520 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(), 1521 TemplateKWLoc, Result.Name)) { 1522 T.skipToEnd(); 1523 return true; 1524 } 1525 1526 if (T.consumeClose()) 1527 return true; 1528 1529 // Check if the symbol exists. 1530 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, 1531 Result.IsIfExists, Result.SS, 1532 Result.Name)) { 1533 case Sema::IER_Exists: 1534 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip; 1535 break; 1536 1537 case Sema::IER_DoesNotExist: 1538 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip; 1539 break; 1540 1541 case Sema::IER_Dependent: 1542 Result.Behavior = IEB_Dependent; 1543 break; 1544 1545 case Sema::IER_Error: 1546 return true; 1547 } 1548 1549 return false; 1550 } 1551 1552 void Parser::ParseMicrosoftIfExistsExternalDeclaration() { 1553 IfExistsCondition Result; 1554 if (ParseMicrosoftIfExistsCondition(Result)) 1555 return; 1556 1557 BalancedDelimiterTracker Braces(*this, tok::l_brace); 1558 if (Braces.consumeOpen()) { 1559 Diag(Tok, diag::err_expected_lbrace); 1560 return; 1561 } 1562 1563 switch (Result.Behavior) { 1564 case IEB_Parse: 1565 // Parse declarations below. 1566 break; 1567 1568 case IEB_Dependent: 1569 llvm_unreachable("Cannot have a dependent external declaration"); 1570 1571 case IEB_Skip: 1572 Braces.skipToEnd(); 1573 return; 1574 } 1575 1576 // Parse the declarations. 1577 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1578 ParsedAttributesWithRange attrs(AttrFactory); 1579 MaybeParseCXX0XAttributes(attrs); 1580 MaybeParseMicrosoftAttributes(attrs); 1581 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs); 1582 if (Result && !getCurScope()->getParent()) 1583 Actions.getASTConsumer().HandleTopLevelDecl(Result.get()); 1584 } 1585 Braces.consumeClose(); 1586 } 1587 1588 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) { 1589 assert(Tok.isObjCAtKeyword(tok::objc_import) && 1590 "Improper start to module import"); 1591 SourceLocation ImportLoc = ConsumeToken(); 1592 1593 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1594 1595 // Parse the module path. 1596 do { 1597 if (!Tok.is(tok::identifier)) { 1598 if (Tok.is(tok::code_completion)) { 1599 Actions.CodeCompleteModuleImport(ImportLoc, Path); 1600 ConsumeCodeCompletionToken(); 1601 SkipUntil(tok::semi); 1602 return DeclGroupPtrTy(); 1603 } 1604 1605 Diag(Tok, diag::err_module_expected_ident); 1606 SkipUntil(tok::semi); 1607 return DeclGroupPtrTy(); 1608 } 1609 1610 // Record this part of the module path. 1611 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); 1612 ConsumeToken(); 1613 1614 if (Tok.is(tok::period)) { 1615 ConsumeToken(); 1616 continue; 1617 } 1618 1619 break; 1620 } while (true); 1621 1622 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path); 1623 ExpectAndConsumeSemi(diag::err_module_expected_semi); 1624 if (Import.isInvalid()) 1625 return DeclGroupPtrTy(); 1626 1627 return Actions.ConvertDeclToDeclGroup(Import.get()); 1628 } 1629 1630 bool Parser::BalancedDelimiterTracker::consumeOpen() { 1631 // Try to consume the token we are holding 1632 if (P.Tok.is(Kind)) { 1633 P.QuantityTracker.push(Kind); 1634 Cleanup = true; 1635 if (P.QuantityTracker.getDepth(Kind) < MaxDepth) { 1636 LOpen = P.ConsumeAnyToken(); 1637 return false; 1638 } else { 1639 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow); 1640 P.SkipUntil(tok::eof); 1641 } 1642 } 1643 return true; 1644 } 1645 1646 bool Parser::BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, 1647 const char *Msg, 1648 tok::TokenKind SkipToToc ) { 1649 LOpen = P.Tok.getLocation(); 1650 if (!P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc)) { 1651 P.QuantityTracker.push(Kind); 1652 Cleanup = true; 1653 if (P.QuantityTracker.getDepth(Kind) < MaxDepth) { 1654 return false; 1655 } else { 1656 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow); 1657 P.SkipUntil(tok::eof); 1658 } 1659 } 1660 return true; 1661 } 1662 1663 bool Parser::BalancedDelimiterTracker::consumeClose() { 1664 if (P.Tok.is(Close)) { 1665 LClose = P.ConsumeAnyToken(); 1666 if (Cleanup) 1667 P.QuantityTracker.pop(Kind); 1668 1669 Cleanup = false; 1670 return false; 1671 } else { 1672 const char *LHSName = "unknown"; 1673 diag::kind DID = diag::err_parse_error; 1674 switch (Close) { 1675 default: break; 1676 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break; 1677 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break; 1678 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break; 1679 case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break; 1680 case tok::greatergreatergreater: 1681 LHSName = "<<<"; DID = diag::err_expected_ggg; break; 1682 } 1683 P.Diag(P.Tok, DID); 1684 P.Diag(LOpen, diag::note_matching) << LHSName; 1685 if (P.SkipUntil(Close)) 1686 LClose = P.Tok.getLocation(); 1687 } 1688 return true; 1689 } 1690 1691 void Parser::BalancedDelimiterTracker::skipToEnd() { 1692 P.SkipUntil(Close, false); 1693 Cleanup = false; 1694 } 1695