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