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