ParseDecl.cpp revision d81e961f905e3ea57f6808e5a5686a8324270984
1//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===// 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 Declaration portions of the Parser interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Parse/Parser.h" 15#include "clang/Parse/ParseDiagnostic.h" 16#include "clang/Basic/OpenCL.h" 17#include "clang/Sema/Scope.h" 18#include "clang/Sema/ParsedTemplate.h" 19#include "clang/Sema/PrettyDeclStackTrace.h" 20#include "RAIIObjectsForParser.h" 21#include "llvm/ADT/SmallSet.h" 22#include "llvm/ADT/SmallString.h" 23#include "llvm/ADT/StringSwitch.h" 24using namespace clang; 25 26//===----------------------------------------------------------------------===// 27// C99 6.7: Declarations. 28//===----------------------------------------------------------------------===// 29 30/// ParseTypeName 31/// type-name: [C99 6.7.6] 32/// specifier-qualifier-list abstract-declarator[opt] 33/// 34/// Called type-id in C++. 35TypeResult Parser::ParseTypeName(SourceRange *Range, 36 Declarator::TheContext Context, 37 AccessSpecifier AS, 38 Decl **OwnedType) { 39 // Parse the common declaration-specifiers piece. 40 DeclSpec DS(AttrFactory); 41 ParseSpecifierQualifierList(DS, AS); 42 if (OwnedType) 43 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0; 44 45 // Parse the abstract-declarator, if present. 46 Declarator DeclaratorInfo(DS, Context); 47 ParseDeclarator(DeclaratorInfo); 48 if (Range) 49 *Range = DeclaratorInfo.getSourceRange(); 50 51 if (DeclaratorInfo.isInvalidType()) 52 return true; 53 54 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 55} 56 57 58/// isAttributeLateParsed - Return true if the attribute has arguments that 59/// require late parsing. 60static bool isAttributeLateParsed(const IdentifierInfo &II) { 61 return llvm::StringSwitch<bool>(II.getName()) 62#include "clang/Parse/AttrLateParsed.inc" 63 .Default(false); 64} 65 66 67/// ParseGNUAttributes - Parse a non-empty attributes list. 68/// 69/// [GNU] attributes: 70/// attribute 71/// attributes attribute 72/// 73/// [GNU] attribute: 74/// '__attribute__' '(' '(' attribute-list ')' ')' 75/// 76/// [GNU] attribute-list: 77/// attrib 78/// attribute_list ',' attrib 79/// 80/// [GNU] attrib: 81/// empty 82/// attrib-name 83/// attrib-name '(' identifier ')' 84/// attrib-name '(' identifier ',' nonempty-expr-list ')' 85/// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 86/// 87/// [GNU] attrib-name: 88/// identifier 89/// typespec 90/// typequal 91/// storageclass 92/// 93/// FIXME: The GCC grammar/code for this construct implies we need two 94/// token lookahead. Comment from gcc: "If they start with an identifier 95/// which is followed by a comma or close parenthesis, then the arguments 96/// start with that identifier; otherwise they are an expression list." 97/// 98/// GCC does not require the ',' between attribs in an attribute-list. 99/// 100/// At the moment, I am not doing 2 token lookahead. I am also unaware of 101/// any attributes that don't work (based on my limited testing). Most 102/// attributes are very simple in practice. Until we find a bug, I don't see 103/// a pressing need to implement the 2 token lookahead. 104 105void Parser::ParseGNUAttributes(ParsedAttributes &attrs, 106 SourceLocation *endLoc, 107 LateParsedAttrList *LateAttrs) { 108 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!"); 109 110 while (Tok.is(tok::kw___attribute)) { 111 ConsumeToken(); 112 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 113 "attribute")) { 114 SkipUntil(tok::r_paren, true); // skip until ) or ; 115 return; 116 } 117 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 118 SkipUntil(tok::r_paren, true); // skip until ) or ; 119 return; 120 } 121 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 122 while (Tok.is(tok::identifier) || isDeclarationSpecifier() || 123 Tok.is(tok::comma)) { 124 if (Tok.is(tok::comma)) { 125 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,)) 126 ConsumeToken(); 127 continue; 128 } 129 // we have an identifier or declaration specifier (const, int, etc.) 130 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 131 SourceLocation AttrNameLoc = ConsumeToken(); 132 133 if (Tok.is(tok::l_paren)) { 134 // handle "parameterized" attributes 135 if (LateAttrs && isAttributeLateParsed(*AttrName)) { 136 LateParsedAttribute *LA = 137 new LateParsedAttribute(this, *AttrName, AttrNameLoc); 138 LateAttrs->push_back(LA); 139 140 // Attributes in a class are parsed at the end of the class, along 141 // with other late-parsed declarations. 142 if (!ClassStack.empty()) 143 getCurrentClass().LateParsedDeclarations.push_back(LA); 144 145 // consume everything up to and including the matching right parens 146 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false); 147 148 Token Eof; 149 Eof.startToken(); 150 Eof.setLocation(Tok.getLocation()); 151 LA->Toks.push_back(Eof); 152 } else { 153 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc); 154 } 155 } else { 156 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 157 0, SourceLocation(), 0, 0); 158 } 159 } 160 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 161 SkipUntil(tok::r_paren, false); 162 SourceLocation Loc = Tok.getLocation(); 163 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 164 SkipUntil(tok::r_paren, false); 165 } 166 if (endLoc) 167 *endLoc = Loc; 168 } 169} 170 171 172/// Parse the arguments to a parameterized GNU attribute 173void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName, 174 SourceLocation AttrNameLoc, 175 ParsedAttributes &Attrs, 176 SourceLocation *EndLoc) { 177 178 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 179 180 // Availability attributes have their own grammar. 181 if (AttrName->isStr("availability")) { 182 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc); 183 return; 184 } 185 // Thread safety attributes fit into the FIXME case above, so we 186 // just parse the arguments as a list of expressions 187 if (IsThreadSafetyAttribute(AttrName->getName())) { 188 ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc); 189 return; 190 } 191 192 ConsumeParen(); // ignore the left paren loc for now 193 194 IdentifierInfo *ParmName = 0; 195 SourceLocation ParmLoc; 196 bool BuiltinType = false; 197 198 switch (Tok.getKind()) { 199 case tok::kw_char: 200 case tok::kw_wchar_t: 201 case tok::kw_char16_t: 202 case tok::kw_char32_t: 203 case tok::kw_bool: 204 case tok::kw_short: 205 case tok::kw_int: 206 case tok::kw_long: 207 case tok::kw___int64: 208 case tok::kw_signed: 209 case tok::kw_unsigned: 210 case tok::kw_float: 211 case tok::kw_double: 212 case tok::kw_void: 213 case tok::kw_typeof: 214 // __attribute__(( vec_type_hint(char) )) 215 // FIXME: Don't just discard the builtin type token. 216 ConsumeToken(); 217 BuiltinType = true; 218 break; 219 220 case tok::identifier: 221 ParmName = Tok.getIdentifierInfo(); 222 ParmLoc = ConsumeToken(); 223 break; 224 225 default: 226 break; 227 } 228 229 ExprVector ArgExprs(Actions); 230 231 if (!BuiltinType && 232 (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) { 233 // Eat the comma. 234 if (ParmLoc.isValid()) 235 ConsumeToken(); 236 237 // Parse the non-empty comma-separated list of expressions. 238 while (1) { 239 ExprResult ArgExpr(ParseAssignmentExpression()); 240 if (ArgExpr.isInvalid()) { 241 SkipUntil(tok::r_paren); 242 return; 243 } 244 ArgExprs.push_back(ArgExpr.release()); 245 if (Tok.isNot(tok::comma)) 246 break; 247 ConsumeToken(); // Eat the comma, move to the next argument 248 } 249 } 250 else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) { 251 if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<", 252 tok::greater)) { 253 while (Tok.is(tok::identifier)) { 254 ConsumeToken(); 255 if (Tok.is(tok::greater)) 256 break; 257 if (Tok.is(tok::comma)) { 258 ConsumeToken(); 259 continue; 260 } 261 } 262 if (Tok.isNot(tok::greater)) 263 Diag(Tok, diag::err_iboutletcollection_with_protocol); 264 SkipUntil(tok::r_paren, false, true); // skip until ')' 265 } 266 } 267 268 SourceLocation RParen = Tok.getLocation(); 269 if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 270 AttributeList *attr = 271 Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrNameLoc, 272 ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size()); 273 if (BuiltinType && attr->getKind() == AttributeList::AT_IBOutletCollection) 274 Diag(Tok, diag::err_iboutletcollection_builtintype); 275 } 276} 277 278 279/// ParseMicrosoftDeclSpec - Parse an __declspec construct 280/// 281/// [MS] decl-specifier: 282/// __declspec ( extended-decl-modifier-seq ) 283/// 284/// [MS] extended-decl-modifier-seq: 285/// extended-decl-modifier[opt] 286/// extended-decl-modifier extended-decl-modifier-seq 287 288void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) { 289 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 290 291 ConsumeToken(); 292 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 293 "declspec")) { 294 SkipUntil(tok::r_paren, true); // skip until ) or ; 295 return; 296 } 297 298 while (Tok.getIdentifierInfo()) { 299 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 300 SourceLocation AttrNameLoc = ConsumeToken(); 301 302 // FIXME: Remove this when we have proper __declspec(property()) support. 303 // Just skip everything inside property(). 304 if (AttrName->getName() == "property") { 305 ConsumeParen(); 306 SkipUntil(tok::r_paren); 307 } 308 if (Tok.is(tok::l_paren)) { 309 ConsumeParen(); 310 // FIXME: This doesn't parse __declspec(property(get=get_func_name)) 311 // correctly. 312 ExprResult ArgExpr(ParseAssignmentExpression()); 313 if (!ArgExpr.isInvalid()) { 314 Expr *ExprList = ArgExpr.take(); 315 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 316 SourceLocation(), &ExprList, 1, true); 317 } 318 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 319 SkipUntil(tok::r_paren, false); 320 } else { 321 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 322 0, SourceLocation(), 0, 0, true); 323 } 324 } 325 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 326 SkipUntil(tok::r_paren, false); 327 return; 328} 329 330void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) { 331 // Treat these like attributes 332 // FIXME: Allow Sema to distinguish between these and real attributes! 333 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) || 334 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) || 335 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) || 336 Tok.is(tok::kw___ptr32) || 337 Tok.is(tok::kw___unaligned)) { 338 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 339 SourceLocation AttrNameLoc = ConsumeToken(); 340 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) || 341 Tok.is(tok::kw___ptr32)) 342 // FIXME: Support these properly! 343 continue; 344 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 345 SourceLocation(), 0, 0, true); 346 } 347} 348 349void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { 350 // Treat these like attributes 351 while (Tok.is(tok::kw___pascal)) { 352 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 353 SourceLocation AttrNameLoc = ConsumeToken(); 354 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 355 SourceLocation(), 0, 0, true); 356 } 357} 358 359void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) { 360 // Treat these like attributes 361 while (Tok.is(tok::kw___kernel)) { 362 SourceLocation AttrNameLoc = ConsumeToken(); 363 attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"), 364 AttrNameLoc, 0, AttrNameLoc, 0, 365 SourceLocation(), 0, 0, false); 366 } 367} 368 369void Parser::ParseOpenCLQualifiers(DeclSpec &DS) { 370 SourceLocation Loc = Tok.getLocation(); 371 switch(Tok.getKind()) { 372 // OpenCL qualifiers: 373 case tok::kw___private: 374 case tok::kw_private: 375 DS.getAttributes().addNewInteger( 376 Actions.getASTContext(), 377 PP.getIdentifierInfo("address_space"), Loc, 0); 378 break; 379 380 case tok::kw___global: 381 DS.getAttributes().addNewInteger( 382 Actions.getASTContext(), 383 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global); 384 break; 385 386 case tok::kw___local: 387 DS.getAttributes().addNewInteger( 388 Actions.getASTContext(), 389 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local); 390 break; 391 392 case tok::kw___constant: 393 DS.getAttributes().addNewInteger( 394 Actions.getASTContext(), 395 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant); 396 break; 397 398 case tok::kw___read_only: 399 DS.getAttributes().addNewInteger( 400 Actions.getASTContext(), 401 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only); 402 break; 403 404 case tok::kw___write_only: 405 DS.getAttributes().addNewInteger( 406 Actions.getASTContext(), 407 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only); 408 break; 409 410 case tok::kw___read_write: 411 DS.getAttributes().addNewInteger( 412 Actions.getASTContext(), 413 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write); 414 break; 415 default: break; 416 } 417} 418 419/// \brief Parse a version number. 420/// 421/// version: 422/// simple-integer 423/// simple-integer ',' simple-integer 424/// simple-integer ',' simple-integer ',' simple-integer 425VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { 426 Range = Tok.getLocation(); 427 428 if (!Tok.is(tok::numeric_constant)) { 429 Diag(Tok, diag::err_expected_version); 430 SkipUntil(tok::comma, tok::r_paren, true, true, true); 431 return VersionTuple(); 432 } 433 434 // Parse the major (and possibly minor and subminor) versions, which 435 // are stored in the numeric constant. We utilize a quirk of the 436 // lexer, which is that it handles something like 1.2.3 as a single 437 // numeric constant, rather than two separate tokens. 438 SmallString<512> Buffer; 439 Buffer.resize(Tok.getLength()+1); 440 const char *ThisTokBegin = &Buffer[0]; 441 442 // Get the spelling of the token, which eliminates trigraphs, etc. 443 bool Invalid = false; 444 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 445 if (Invalid) 446 return VersionTuple(); 447 448 // Parse the major version. 449 unsigned AfterMajor = 0; 450 unsigned Major = 0; 451 while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) { 452 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0'; 453 ++AfterMajor; 454 } 455 456 if (AfterMajor == 0) { 457 Diag(Tok, diag::err_expected_version); 458 SkipUntil(tok::comma, tok::r_paren, true, true, true); 459 return VersionTuple(); 460 } 461 462 if (AfterMajor == ActualLength) { 463 ConsumeToken(); 464 465 // We only had a single version component. 466 if (Major == 0) { 467 Diag(Tok, diag::err_zero_version); 468 return VersionTuple(); 469 } 470 471 return VersionTuple(Major); 472 } 473 474 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) { 475 Diag(Tok, diag::err_expected_version); 476 SkipUntil(tok::comma, tok::r_paren, true, true, true); 477 return VersionTuple(); 478 } 479 480 // Parse the minor version. 481 unsigned AfterMinor = AfterMajor + 1; 482 unsigned Minor = 0; 483 while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) { 484 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0'; 485 ++AfterMinor; 486 } 487 488 if (AfterMinor == ActualLength) { 489 ConsumeToken(); 490 491 // We had major.minor. 492 if (Major == 0 && Minor == 0) { 493 Diag(Tok, diag::err_zero_version); 494 return VersionTuple(); 495 } 496 497 return VersionTuple(Major, Minor); 498 } 499 500 // If what follows is not a '.', we have a problem. 501 if (ThisTokBegin[AfterMinor] != '.') { 502 Diag(Tok, diag::err_expected_version); 503 SkipUntil(tok::comma, tok::r_paren, true, true, true); 504 return VersionTuple(); 505 } 506 507 // Parse the subminor version. 508 unsigned AfterSubminor = AfterMinor + 1; 509 unsigned Subminor = 0; 510 while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) { 511 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0'; 512 ++AfterSubminor; 513 } 514 515 if (AfterSubminor != ActualLength) { 516 Diag(Tok, diag::err_expected_version); 517 SkipUntil(tok::comma, tok::r_paren, true, true, true); 518 return VersionTuple(); 519 } 520 ConsumeToken(); 521 return VersionTuple(Major, Minor, Subminor); 522} 523 524/// \brief Parse the contents of the "availability" attribute. 525/// 526/// availability-attribute: 527/// 'availability' '(' platform ',' version-arg-list, opt-message')' 528/// 529/// platform: 530/// identifier 531/// 532/// version-arg-list: 533/// version-arg 534/// version-arg ',' version-arg-list 535/// 536/// version-arg: 537/// 'introduced' '=' version 538/// 'deprecated' '=' version 539/// 'removed' = version 540/// 'unavailable' 541/// opt-message: 542/// 'message' '=' <string> 543void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, 544 SourceLocation AvailabilityLoc, 545 ParsedAttributes &attrs, 546 SourceLocation *endLoc) { 547 SourceLocation PlatformLoc; 548 IdentifierInfo *Platform = 0; 549 550 enum { Introduced, Deprecated, Obsoleted, Unknown }; 551 AvailabilityChange Changes[Unknown]; 552 ExprResult MessageExpr; 553 554 // Opening '('. 555 BalancedDelimiterTracker T(*this, tok::l_paren); 556 if (T.consumeOpen()) { 557 Diag(Tok, diag::err_expected_lparen); 558 return; 559 } 560 561 // Parse the platform name, 562 if (Tok.isNot(tok::identifier)) { 563 Diag(Tok, diag::err_availability_expected_platform); 564 SkipUntil(tok::r_paren); 565 return; 566 } 567 Platform = Tok.getIdentifierInfo(); 568 PlatformLoc = ConsumeToken(); 569 570 // Parse the ',' following the platform name. 571 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren)) 572 return; 573 574 // If we haven't grabbed the pointers for the identifiers 575 // "introduced", "deprecated", and "obsoleted", do so now. 576 if (!Ident_introduced) { 577 Ident_introduced = PP.getIdentifierInfo("introduced"); 578 Ident_deprecated = PP.getIdentifierInfo("deprecated"); 579 Ident_obsoleted = PP.getIdentifierInfo("obsoleted"); 580 Ident_unavailable = PP.getIdentifierInfo("unavailable"); 581 Ident_message = PP.getIdentifierInfo("message"); 582 } 583 584 // Parse the set of introductions/deprecations/removals. 585 SourceLocation UnavailableLoc; 586 do { 587 if (Tok.isNot(tok::identifier)) { 588 Diag(Tok, diag::err_availability_expected_change); 589 SkipUntil(tok::r_paren); 590 return; 591 } 592 IdentifierInfo *Keyword = Tok.getIdentifierInfo(); 593 SourceLocation KeywordLoc = ConsumeToken(); 594 595 if (Keyword == Ident_unavailable) { 596 if (UnavailableLoc.isValid()) { 597 Diag(KeywordLoc, diag::err_availability_redundant) 598 << Keyword << SourceRange(UnavailableLoc); 599 } 600 UnavailableLoc = KeywordLoc; 601 602 if (Tok.isNot(tok::comma)) 603 break; 604 605 ConsumeToken(); 606 continue; 607 } 608 609 if (Tok.isNot(tok::equal)) { 610 Diag(Tok, diag::err_expected_equal_after) 611 << Keyword; 612 SkipUntil(tok::r_paren); 613 return; 614 } 615 ConsumeToken(); 616 if (Keyword == Ident_message) { 617 if (!isTokenStringLiteral()) { 618 Diag(Tok, diag::err_expected_string_literal); 619 SkipUntil(tok::r_paren); 620 return; 621 } 622 MessageExpr = ParseStringLiteralExpression(); 623 break; 624 } 625 626 SourceRange VersionRange; 627 VersionTuple Version = ParseVersionTuple(VersionRange); 628 629 if (Version.empty()) { 630 SkipUntil(tok::r_paren); 631 return; 632 } 633 634 unsigned Index; 635 if (Keyword == Ident_introduced) 636 Index = Introduced; 637 else if (Keyword == Ident_deprecated) 638 Index = Deprecated; 639 else if (Keyword == Ident_obsoleted) 640 Index = Obsoleted; 641 else 642 Index = Unknown; 643 644 if (Index < Unknown) { 645 if (!Changes[Index].KeywordLoc.isInvalid()) { 646 Diag(KeywordLoc, diag::err_availability_redundant) 647 << Keyword 648 << SourceRange(Changes[Index].KeywordLoc, 649 Changes[Index].VersionRange.getEnd()); 650 } 651 652 Changes[Index].KeywordLoc = KeywordLoc; 653 Changes[Index].Version = Version; 654 Changes[Index].VersionRange = VersionRange; 655 } else { 656 Diag(KeywordLoc, diag::err_availability_unknown_change) 657 << Keyword << VersionRange; 658 } 659 660 if (Tok.isNot(tok::comma)) 661 break; 662 663 ConsumeToken(); 664 } while (true); 665 666 // Closing ')'. 667 if (T.consumeClose()) 668 return; 669 670 if (endLoc) 671 *endLoc = T.getCloseLocation(); 672 673 // The 'unavailable' availability cannot be combined with any other 674 // availability changes. Make sure that hasn't happened. 675 if (UnavailableLoc.isValid()) { 676 bool Complained = false; 677 for (unsigned Index = Introduced; Index != Unknown; ++Index) { 678 if (Changes[Index].KeywordLoc.isValid()) { 679 if (!Complained) { 680 Diag(UnavailableLoc, diag::warn_availability_and_unavailable) 681 << SourceRange(Changes[Index].KeywordLoc, 682 Changes[Index].VersionRange.getEnd()); 683 Complained = true; 684 } 685 686 // Clear out the availability. 687 Changes[Index] = AvailabilityChange(); 688 } 689 } 690 } 691 692 // Record this attribute 693 attrs.addNew(&Availability, 694 SourceRange(AvailabilityLoc, T.getCloseLocation()), 695 0, AvailabilityLoc, 696 Platform, PlatformLoc, 697 Changes[Introduced], 698 Changes[Deprecated], 699 Changes[Obsoleted], 700 UnavailableLoc, MessageExpr.take(), 701 false, false); 702} 703 704 705// Late Parsed Attributes: 706// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods 707 708void Parser::LateParsedDeclaration::ParseLexedAttributes() {} 709 710void Parser::LateParsedClass::ParseLexedAttributes() { 711 Self->ParseLexedAttributes(*Class); 712} 713 714void Parser::LateParsedAttribute::ParseLexedAttributes() { 715 Self->ParseLexedAttribute(*this, true, false); 716} 717 718/// Wrapper class which calls ParseLexedAttribute, after setting up the 719/// scope appropriately. 720void Parser::ParseLexedAttributes(ParsingClass &Class) { 721 // Deal with templates 722 // FIXME: Test cases to make sure this does the right thing for templates. 723 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 724 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, 725 HasTemplateScope); 726 if (HasTemplateScope) 727 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 728 729 // Set or update the scope flags to include Scope::ThisScope. 730 bool AlreadyHasClassScope = Class.TopLevelClass; 731 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope|Scope::ThisScope; 732 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); 733 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); 734 735 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i) { 736 Class.LateParsedDeclarations[i]->ParseLexedAttributes(); 737 } 738} 739 740 741/// \brief Parse all attributes in LAs, and attach them to Decl D. 742void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 743 bool EnterScope, bool OnDefinition) { 744 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) { 745 LAs[i]->setDecl(D); 746 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition); 747 } 748 LAs.clear(); 749} 750 751 752/// \brief Finish parsing an attribute for which parsing was delayed. 753/// This will be called at the end of parsing a class declaration 754/// for each LateParsedAttribute. We consume the saved tokens and 755/// create an attribute with the arguments filled in. We add this 756/// to the Attribute list for the decl. 757void Parser::ParseLexedAttribute(LateParsedAttribute &LA, 758 bool EnterScope, bool OnDefinition) { 759 // Save the current token position. 760 SourceLocation OrigLoc = Tok.getLocation(); 761 762 // Append the current token at the end of the new token stream so that it 763 // doesn't get lost. 764 LA.Toks.push_back(Tok); 765 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false); 766 // Consume the previously pushed token. 767 ConsumeAnyToken(); 768 769 if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) { 770 Diag(Tok, diag::warn_attribute_on_function_definition) 771 << LA.AttrName.getName(); 772 } 773 774 ParsedAttributes Attrs(AttrFactory); 775 SourceLocation endLoc; 776 777 // If the Decl is templatized, add template parameters to scope. 778 bool HasTemplateScope = EnterScope && LA.D && LA.D->isTemplateDecl(); 779 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope); 780 if (HasTemplateScope) 781 Actions.ActOnReenterTemplateScope(Actions.CurScope, LA.D); 782 783 // If the Decl is on a function, add function parameters to the scope. 784 bool HasFunctionScope = EnterScope && LA.D && 785 LA.D->isFunctionOrFunctionTemplate(); 786 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunctionScope); 787 if (HasFunctionScope) 788 Actions.ActOnReenterFunctionContext(Actions.CurScope, LA.D); 789 790 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc); 791 792 if (HasFunctionScope) { 793 Actions.ActOnExitFunctionContext(); 794 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver 795 } 796 if (HasTemplateScope) { 797 TempScope.Exit(); 798 } 799 800 // Late parsed attributes must be attached to Decls by hand. If the 801 // LA.D is not set, then this was not done properly. 802 assert(LA.D && "No decl attached to late parsed attribute"); 803 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.D, Attrs); 804 805 if (Tok.getLocation() != OrigLoc) { 806 // Due to a parsing error, we either went over the cached tokens or 807 // there are still cached tokens left, so we skip the leftover tokens. 808 // Since this is an uncommon situation that should be avoided, use the 809 // expensive isBeforeInTranslationUnit call. 810 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), 811 OrigLoc)) 812 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof)) 813 ConsumeAnyToken(); 814 } 815} 816 817/// \brief Wrapper around a case statement checking if AttrName is 818/// one of the thread safety attributes 819bool Parser::IsThreadSafetyAttribute(llvm::StringRef AttrName){ 820 return llvm::StringSwitch<bool>(AttrName) 821 .Case("guarded_by", true) 822 .Case("guarded_var", true) 823 .Case("pt_guarded_by", true) 824 .Case("pt_guarded_var", true) 825 .Case("lockable", true) 826 .Case("scoped_lockable", true) 827 .Case("no_thread_safety_analysis", true) 828 .Case("acquired_after", true) 829 .Case("acquired_before", true) 830 .Case("exclusive_lock_function", true) 831 .Case("shared_lock_function", true) 832 .Case("exclusive_trylock_function", true) 833 .Case("shared_trylock_function", true) 834 .Case("unlock_function", true) 835 .Case("lock_returned", true) 836 .Case("locks_excluded", true) 837 .Case("exclusive_locks_required", true) 838 .Case("shared_locks_required", true) 839 .Default(false); 840} 841 842/// \brief Parse the contents of thread safety attributes. These 843/// should always be parsed as an expression list. 844/// 845/// We need to special case the parsing due to the fact that if the first token 846/// of the first argument is an identifier, the main parse loop will store 847/// that token as a "parameter" and the rest of 848/// the arguments will be added to a list of "arguments". However, 849/// subsequent tokens in the first argument are lost. We instead parse each 850/// argument as an expression and add all arguments to the list of "arguments". 851/// In future, we will take advantage of this special case to also 852/// deal with some argument scoping issues here (for example, referring to a 853/// function parameter in the attribute on that function). 854void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName, 855 SourceLocation AttrNameLoc, 856 ParsedAttributes &Attrs, 857 SourceLocation *EndLoc) { 858 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); 859 860 BalancedDelimiterTracker T(*this, tok::l_paren); 861 T.consumeOpen(); 862 863 ExprVector ArgExprs(Actions); 864 bool ArgExprsOk = true; 865 866 // now parse the list of expressions 867 while (Tok.isNot(tok::r_paren)) { 868 ExprResult ArgExpr(ParseAssignmentExpression()); 869 if (ArgExpr.isInvalid()) { 870 ArgExprsOk = false; 871 T.consumeClose(); 872 break; 873 } else { 874 ArgExprs.push_back(ArgExpr.release()); 875 } 876 if (Tok.isNot(tok::comma)) 877 break; 878 ConsumeToken(); // Eat the comma, move to the next argument 879 } 880 // Match the ')'. 881 if (ArgExprsOk && !T.consumeClose()) { 882 Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(), 883 ArgExprs.take(), ArgExprs.size()); 884 } 885 if (EndLoc) 886 *EndLoc = T.getCloseLocation(); 887} 888 889void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) { 890 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) 891 << attrs.Range; 892} 893 894/// ParseDeclaration - Parse a full 'declaration', which consists of 895/// declaration-specifiers, some number of declarators, and a semicolon. 896/// 'Context' should be a Declarator::TheContext value. This returns the 897/// location of the semicolon in DeclEnd. 898/// 899/// declaration: [C99 6.7] 900/// block-declaration -> 901/// simple-declaration 902/// others [FIXME] 903/// [C++] template-declaration 904/// [C++] namespace-definition 905/// [C++] using-directive 906/// [C++] using-declaration 907/// [C++0x/C11] static_assert-declaration 908/// others... [FIXME] 909/// 910Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts, 911 unsigned Context, 912 SourceLocation &DeclEnd, 913 ParsedAttributesWithRange &attrs) { 914 ParenBraceBracketBalancer BalancerRAIIObj(*this); 915 // Must temporarily exit the objective-c container scope for 916 // parsing c none objective-c decls. 917 ObjCDeclContextSwitch ObjCDC(*this); 918 919 Decl *SingleDecl = 0; 920 Decl *OwnedType = 0; 921 switch (Tok.getKind()) { 922 case tok::kw_template: 923 case tok::kw_export: 924 ProhibitAttributes(attrs); 925 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 926 break; 927 case tok::kw_inline: 928 // Could be the start of an inline namespace. Allowed as an ext in C++03. 929 if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) { 930 ProhibitAttributes(attrs); 931 SourceLocation InlineLoc = ConsumeToken(); 932 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc); 933 break; 934 } 935 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, 936 true); 937 case tok::kw_namespace: 938 ProhibitAttributes(attrs); 939 SingleDecl = ParseNamespace(Context, DeclEnd); 940 break; 941 case tok::kw_using: 942 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), 943 DeclEnd, attrs, &OwnedType); 944 break; 945 case tok::kw_static_assert: 946 case tok::kw__Static_assert: 947 ProhibitAttributes(attrs); 948 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 949 break; 950 default: 951 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true); 952 } 953 954 // This routine returns a DeclGroup, if the thing we parsed only contains a 955 // single decl, convert it now. Alias declarations can also declare a type; 956 // include that too if it is present. 957 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType); 958} 959 960/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 961/// declaration-specifiers init-declarator-list[opt] ';' 962///[C90/C++]init-declarator-list ';' [TODO] 963/// [OMP] threadprivate-directive [TODO] 964/// 965/// for-range-declaration: [C++0x 6.5p1: stmt.ranged] 966/// attribute-specifier-seq[opt] type-specifier-seq declarator 967/// 968/// If RequireSemi is false, this does not check for a ';' at the end of the 969/// declaration. If it is true, it checks for and eats it. 970/// 971/// If FRI is non-null, we might be parsing a for-range-declaration instead 972/// of a simple-declaration. If we find that we are, we also parse the 973/// for-range-initializer, and place it here. 974Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts, 975 unsigned Context, 976 SourceLocation &DeclEnd, 977 ParsedAttributes &attrs, 978 bool RequireSemi, 979 ForRangeInit *FRI) { 980 // Parse the common declaration-specifiers piece. 981 ParsingDeclSpec DS(*this); 982 DS.takeAttributesFrom(attrs); 983 984 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, 985 getDeclSpecContextFromDeclaratorContext(Context)); 986 987 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 988 // declaration-specifiers init-declarator-list[opt] ';' 989 if (Tok.is(tok::semi)) { 990 if (RequireSemi) ConsumeToken(); 991 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 992 DS); 993 DS.complete(TheDecl); 994 return Actions.ConvertDeclToDeclGroup(TheDecl); 995 } 996 997 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI); 998} 999 1000/// Returns true if this might be the start of a declarator, or a common typo 1001/// for a declarator. 1002bool Parser::MightBeDeclarator(unsigned Context) { 1003 switch (Tok.getKind()) { 1004 case tok::annot_cxxscope: 1005 case tok::annot_template_id: 1006 case tok::caret: 1007 case tok::code_completion: 1008 case tok::coloncolon: 1009 case tok::ellipsis: 1010 case tok::kw___attribute: 1011 case tok::kw_operator: 1012 case tok::l_paren: 1013 case tok::star: 1014 return true; 1015 1016 case tok::amp: 1017 case tok::ampamp: 1018 return getLang().CPlusPlus; 1019 1020 case tok::l_square: // Might be an attribute on an unnamed bit-field. 1021 return Context == Declarator::MemberContext && getLang().CPlusPlus0x && 1022 NextToken().is(tok::l_square); 1023 1024 case tok::colon: // Might be a typo for '::' or an unnamed bit-field. 1025 return Context == Declarator::MemberContext || getLang().CPlusPlus; 1026 1027 case tok::identifier: 1028 switch (NextToken().getKind()) { 1029 case tok::code_completion: 1030 case tok::coloncolon: 1031 case tok::comma: 1032 case tok::equal: 1033 case tok::equalequal: // Might be a typo for '='. 1034 case tok::kw_alignas: 1035 case tok::kw_asm: 1036 case tok::kw___attribute: 1037 case tok::l_brace: 1038 case tok::l_paren: 1039 case tok::l_square: 1040 case tok::less: 1041 case tok::r_brace: 1042 case tok::r_paren: 1043 case tok::r_square: 1044 case tok::semi: 1045 return true; 1046 1047 case tok::colon: 1048 // At namespace scope, 'identifier:' is probably a typo for 'identifier::' 1049 // and in block scope it's probably a label. Inside a class definition, 1050 // this is a bit-field. 1051 return Context == Declarator::MemberContext || 1052 (getLang().CPlusPlus && Context == Declarator::FileContext); 1053 1054 case tok::identifier: // Possible virt-specifier. 1055 return getLang().CPlusPlus0x && isCXX0XVirtSpecifier(NextToken()); 1056 1057 default: 1058 return false; 1059 } 1060 1061 default: 1062 return false; 1063 } 1064} 1065 1066/// ParseDeclGroup - Having concluded that this is either a function 1067/// definition or a group of object declarations, actually parse the 1068/// result. 1069Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, 1070 unsigned Context, 1071 bool AllowFunctionDefinitions, 1072 SourceLocation *DeclEnd, 1073 ForRangeInit *FRI) { 1074 // Parse the first declarator. 1075 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context)); 1076 ParseDeclarator(D); 1077 1078 // Bail out if the first declarator didn't seem well-formed. 1079 if (!D.hasName() && !D.mayOmitIdentifier()) { 1080 // Skip until ; or }. 1081 SkipUntil(tok::r_brace, true, true); 1082 if (Tok.is(tok::semi)) 1083 ConsumeToken(); 1084 return DeclGroupPtrTy(); 1085 } 1086 1087 // Save late-parsed attributes for now; they need to be parsed in the 1088 // appropriate function scope after the function Decl has been constructed. 1089 LateParsedAttrList LateParsedAttrs; 1090 if (D.isFunctionDeclarator()) 1091 MaybeParseGNUAttributes(D, &LateParsedAttrs); 1092 1093 // Check to see if we have a function *definition* which must have a body. 1094 if (AllowFunctionDefinitions && D.isFunctionDeclarator() && 1095 // Look at the next token to make sure that this isn't a function 1096 // declaration. We have to check this because __attribute__ might be the 1097 // start of a function definition in GCC-extended K&R C. 1098 !isDeclarationAfterDeclarator()) { 1099 1100 if (isStartOfFunctionDefinition(D)) { 1101 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1102 Diag(Tok, diag::err_function_declared_typedef); 1103 1104 // Recover by treating the 'typedef' as spurious. 1105 DS.ClearStorageClassSpecs(); 1106 } 1107 1108 Decl *TheDecl = 1109 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs); 1110 return Actions.ConvertDeclToDeclGroup(TheDecl); 1111 } 1112 1113 if (isDeclarationSpecifier()) { 1114 // If there is an invalid declaration specifier right after the function 1115 // prototype, then we must be in a missing semicolon case where this isn't 1116 // actually a body. Just fall through into the code that handles it as a 1117 // prototype, and let the top-level code handle the erroneous declspec 1118 // where it would otherwise expect a comma or semicolon. 1119 } else { 1120 Diag(Tok, diag::err_expected_fn_body); 1121 SkipUntil(tok::semi); 1122 return DeclGroupPtrTy(); 1123 } 1124 } 1125 1126 if (ParseAsmAttributesAfterDeclarator(D)) 1127 return DeclGroupPtrTy(); 1128 1129 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we 1130 // must parse and analyze the for-range-initializer before the declaration is 1131 // analyzed. 1132 if (FRI && Tok.is(tok::colon)) { 1133 FRI->ColonLoc = ConsumeToken(); 1134 if (Tok.is(tok::l_brace)) 1135 FRI->RangeExpr = ParseBraceInitializer(); 1136 else 1137 FRI->RangeExpr = ParseExpression(); 1138 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 1139 Actions.ActOnCXXForRangeDecl(ThisDecl); 1140 Actions.FinalizeDeclaration(ThisDecl); 1141 D.complete(ThisDecl); 1142 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1); 1143 } 1144 1145 SmallVector<Decl *, 8> DeclsInGroup; 1146 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D); 1147 if (LateParsedAttrs.size() > 0) 1148 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false); 1149 D.complete(FirstDecl); 1150 if (FirstDecl) 1151 DeclsInGroup.push_back(FirstDecl); 1152 1153 bool ExpectSemi = Context != Declarator::ForContext; 1154 1155 // If we don't have a comma, it is either the end of the list (a ';') or an 1156 // error, bail out. 1157 while (Tok.is(tok::comma)) { 1158 SourceLocation CommaLoc = ConsumeToken(); 1159 1160 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) { 1161 // This comma was followed by a line-break and something which can't be 1162 // the start of a declarator. The comma was probably a typo for a 1163 // semicolon. 1164 Diag(CommaLoc, diag::err_expected_semi_declaration) 1165 << FixItHint::CreateReplacement(CommaLoc, ";"); 1166 ExpectSemi = false; 1167 break; 1168 } 1169 1170 // Parse the next declarator. 1171 D.clear(); 1172 D.setCommaLoc(CommaLoc); 1173 1174 // Accept attributes in an init-declarator. In the first declarator in a 1175 // declaration, these would be part of the declspec. In subsequent 1176 // declarators, they become part of the declarator itself, so that they 1177 // don't apply to declarators after *this* one. Examples: 1178 // short __attribute__((common)) var; -> declspec 1179 // short var __attribute__((common)); -> declarator 1180 // short x, __attribute__((common)) var; -> declarator 1181 MaybeParseGNUAttributes(D); 1182 1183 ParseDeclarator(D); 1184 if (!D.isInvalidType()) { 1185 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 1186 D.complete(ThisDecl); 1187 if (ThisDecl) 1188 DeclsInGroup.push_back(ThisDecl); 1189 } 1190 } 1191 1192 if (DeclEnd) 1193 *DeclEnd = Tok.getLocation(); 1194 1195 if (ExpectSemi && 1196 ExpectAndConsume(tok::semi, 1197 Context == Declarator::FileContext 1198 ? diag::err_invalid_token_after_toplevel_declarator 1199 : diag::err_expected_semi_declaration)) { 1200 // Okay, there was no semicolon and one was expected. If we see a 1201 // declaration specifier, just assume it was missing and continue parsing. 1202 // Otherwise things are very confused and we skip to recover. 1203 if (!isDeclarationSpecifier()) { 1204 SkipUntil(tok::r_brace, true, true); 1205 if (Tok.is(tok::semi)) 1206 ConsumeToken(); 1207 } 1208 } 1209 1210 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, 1211 DeclsInGroup.data(), 1212 DeclsInGroup.size()); 1213} 1214 1215/// Parse an optional simple-asm-expr and attributes, and attach them to a 1216/// declarator. Returns true on an error. 1217bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) { 1218 // If a simple-asm-expr is present, parse it. 1219 if (Tok.is(tok::kw_asm)) { 1220 SourceLocation Loc; 1221 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1222 if (AsmLabel.isInvalid()) { 1223 SkipUntil(tok::semi, true, true); 1224 return true; 1225 } 1226 1227 D.setAsmLabel(AsmLabel.release()); 1228 D.SetRangeEnd(Loc); 1229 } 1230 1231 MaybeParseGNUAttributes(D); 1232 return false; 1233} 1234 1235/// \brief Parse 'declaration' after parsing 'declaration-specifiers 1236/// declarator'. This method parses the remainder of the declaration 1237/// (including any attributes or initializer, among other things) and 1238/// finalizes the declaration. 1239/// 1240/// init-declarator: [C99 6.7] 1241/// declarator 1242/// declarator '=' initializer 1243/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 1244/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 1245/// [C++] declarator initializer[opt] 1246/// 1247/// [C++] initializer: 1248/// [C++] '=' initializer-clause 1249/// [C++] '(' expression-list ')' 1250/// [C++0x] '=' 'default' [TODO] 1251/// [C++0x] '=' 'delete' 1252/// [C++0x] braced-init-list 1253/// 1254/// According to the standard grammar, =default and =delete are function 1255/// definitions, but that definitely doesn't fit with the parser here. 1256/// 1257Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D, 1258 const ParsedTemplateInfo &TemplateInfo) { 1259 if (ParseAsmAttributesAfterDeclarator(D)) 1260 return 0; 1261 1262 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); 1263} 1264 1265Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D, 1266 const ParsedTemplateInfo &TemplateInfo) { 1267 // Inform the current actions module that we just parsed this declarator. 1268 Decl *ThisDecl = 0; 1269 switch (TemplateInfo.Kind) { 1270 case ParsedTemplateInfo::NonTemplate: 1271 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 1272 break; 1273 1274 case ParsedTemplateInfo::Template: 1275 case ParsedTemplateInfo::ExplicitSpecialization: 1276 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 1277 MultiTemplateParamsArg(Actions, 1278 TemplateInfo.TemplateParams->data(), 1279 TemplateInfo.TemplateParams->size()), 1280 D); 1281 break; 1282 1283 case ParsedTemplateInfo::ExplicitInstantiation: { 1284 DeclResult ThisRes 1285 = Actions.ActOnExplicitInstantiation(getCurScope(), 1286 TemplateInfo.ExternLoc, 1287 TemplateInfo.TemplateLoc, 1288 D); 1289 if (ThisRes.isInvalid()) { 1290 SkipUntil(tok::semi, true, true); 1291 return 0; 1292 } 1293 1294 ThisDecl = ThisRes.get(); 1295 break; 1296 } 1297 } 1298 1299 bool TypeContainsAuto = 1300 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 1301 1302 // Parse declarator '=' initializer. 1303 // If a '==' or '+=' is found, suggest a fixit to '='. 1304 if (isTokenEqualOrEqualTypo()) { 1305 ConsumeToken(); 1306 if (Tok.is(tok::kw_delete)) { 1307 if (D.isFunctionDeclarator()) 1308 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 1309 << 1 /* delete */; 1310 else 1311 Diag(ConsumeToken(), diag::err_deleted_non_function); 1312 } else if (Tok.is(tok::kw_default)) { 1313 if (D.isFunctionDeclarator()) 1314 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 1315 << 0 /* default */; 1316 else 1317 Diag(ConsumeToken(), diag::err_default_special_members); 1318 } else { 1319 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1320 EnterScope(0); 1321 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1322 } 1323 1324 if (Tok.is(tok::code_completion)) { 1325 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 1326 cutOffParsing(); 1327 return 0; 1328 } 1329 1330 ExprResult Init(ParseInitializer()); 1331 1332 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1333 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1334 ExitScope(); 1335 } 1336 1337 if (Init.isInvalid()) { 1338 SkipUntil(tok::comma, true, true); 1339 Actions.ActOnInitializerError(ThisDecl); 1340 } else 1341 Actions.AddInitializerToDecl(ThisDecl, Init.take(), 1342 /*DirectInit=*/false, TypeContainsAuto); 1343 } 1344 } else if (Tok.is(tok::l_paren)) { 1345 // Parse C++ direct initializer: '(' expression-list ')' 1346 BalancedDelimiterTracker T(*this, tok::l_paren); 1347 T.consumeOpen(); 1348 1349 ExprVector Exprs(Actions); 1350 CommaLocsTy CommaLocs; 1351 1352 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1353 EnterScope(0); 1354 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1355 } 1356 1357 if (ParseExpressionList(Exprs, CommaLocs)) { 1358 SkipUntil(tok::r_paren); 1359 1360 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1361 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1362 ExitScope(); 1363 } 1364 } else { 1365 // Match the ')'. 1366 T.consumeClose(); 1367 1368 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 1369 "Unexpected number of commas!"); 1370 1371 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1372 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1373 ExitScope(); 1374 } 1375 1376 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(), 1377 T.getCloseLocation(), 1378 move_arg(Exprs)); 1379 Actions.AddInitializerToDecl(ThisDecl, Initializer.take(), 1380 /*DirectInit=*/true, TypeContainsAuto); 1381 } 1382 } else if (getLang().CPlusPlus0x && Tok.is(tok::l_brace)) { 1383 // Parse C++0x braced-init-list. 1384 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 1385 1386 if (D.getCXXScopeSpec().isSet()) { 1387 EnterScope(0); 1388 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1389 } 1390 1391 ExprResult Init(ParseBraceInitializer()); 1392 1393 if (D.getCXXScopeSpec().isSet()) { 1394 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1395 ExitScope(); 1396 } 1397 1398 if (Init.isInvalid()) { 1399 Actions.ActOnInitializerError(ThisDecl); 1400 } else 1401 Actions.AddInitializerToDecl(ThisDecl, Init.take(), 1402 /*DirectInit=*/true, TypeContainsAuto); 1403 1404 } else { 1405 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); 1406 } 1407 1408 Actions.FinalizeDeclaration(ThisDecl); 1409 1410 return ThisDecl; 1411} 1412 1413/// ParseSpecifierQualifierList 1414/// specifier-qualifier-list: 1415/// type-specifier specifier-qualifier-list[opt] 1416/// type-qualifier specifier-qualifier-list[opt] 1417/// [GNU] attributes specifier-qualifier-list[opt] 1418/// 1419void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS) { 1420 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 1421 /// parse declaration-specifiers and complain about extra stuff. 1422 /// TODO: diagnose attribute-specifiers and alignment-specifiers. 1423 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS); 1424 1425 // Validate declspec for type-name. 1426 unsigned Specs = DS.getParsedSpecifiers(); 1427 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && 1428 !DS.hasAttributes()) 1429 Diag(Tok, diag::err_typename_requires_specqual); 1430 1431 // Issue diagnostic and remove storage class if present. 1432 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 1433 if (DS.getStorageClassSpecLoc().isValid()) 1434 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 1435 else 1436 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); 1437 DS.ClearStorageClassSpecs(); 1438 } 1439 1440 // Issue diagnostic and remove function specfier if present. 1441 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 1442 if (DS.isInlineSpecified()) 1443 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 1444 if (DS.isVirtualSpecified()) 1445 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 1446 if (DS.isExplicitSpecified()) 1447 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 1448 DS.ClearFunctionSpecs(); 1449 } 1450} 1451 1452/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 1453/// specified token is valid after the identifier in a declarator which 1454/// immediately follows the declspec. For example, these things are valid: 1455/// 1456/// int x [ 4]; // direct-declarator 1457/// int x ( int y); // direct-declarator 1458/// int(int x ) // direct-declarator 1459/// int x ; // simple-declaration 1460/// int x = 17; // init-declarator-list 1461/// int x , y; // init-declarator-list 1462/// int x __asm__ ("foo"); // init-declarator-list 1463/// int x : 4; // struct-declarator 1464/// int x { 5}; // C++'0x unified initializers 1465/// 1466/// This is not, because 'x' does not immediately follow the declspec (though 1467/// ')' happens to be valid anyway). 1468/// int (x) 1469/// 1470static bool isValidAfterIdentifierInDeclarator(const Token &T) { 1471 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) || 1472 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) || 1473 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon); 1474} 1475 1476 1477/// ParseImplicitInt - This method is called when we have an non-typename 1478/// identifier in a declspec (which normally terminates the decl spec) when 1479/// the declspec has no type specifier. In this case, the declspec is either 1480/// malformed or is "implicit int" (in K&R and C89). 1481/// 1482/// This method handles diagnosing this prettily and returns false if the 1483/// declspec is done being processed. If it recovers and thinks there may be 1484/// other pieces of declspec after it, it returns true. 1485/// 1486bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 1487 const ParsedTemplateInfo &TemplateInfo, 1488 AccessSpecifier AS) { 1489 assert(Tok.is(tok::identifier) && "should have identifier"); 1490 1491 SourceLocation Loc = Tok.getLocation(); 1492 // If we see an identifier that is not a type name, we normally would 1493 // parse it as the identifer being declared. However, when a typename 1494 // is typo'd or the definition is not included, this will incorrectly 1495 // parse the typename as the identifier name and fall over misparsing 1496 // later parts of the diagnostic. 1497 // 1498 // As such, we try to do some look-ahead in cases where this would 1499 // otherwise be an "implicit-int" case to see if this is invalid. For 1500 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 1501 // an identifier with implicit int, we'd get a parse error because the 1502 // next token is obviously invalid for a type. Parse these as a case 1503 // with an invalid type specifier. 1504 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 1505 1506 // Since we know that this either implicit int (which is rare) or an 1507 // error, we'd do lookahead to try to do better recovery. 1508 if (isValidAfterIdentifierInDeclarator(NextToken())) { 1509 // If this token is valid for implicit int, e.g. "static x = 4", then 1510 // we just avoid eating the identifier, so it will be parsed as the 1511 // identifier in the declarator. 1512 return false; 1513 } 1514 1515 // Otherwise, if we don't consume this token, we are going to emit an 1516 // error anyway. Try to recover from various common problems. Check 1517 // to see if this was a reference to a tag name without a tag specified. 1518 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 1519 // 1520 // C++ doesn't need this, and isTagName doesn't take SS. 1521 if (SS == 0) { 1522 const char *TagName = 0, *FixitTagName = 0; 1523 tok::TokenKind TagKind = tok::unknown; 1524 1525 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 1526 default: break; 1527 case DeclSpec::TST_enum: 1528 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break; 1529 case DeclSpec::TST_union: 1530 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break; 1531 case DeclSpec::TST_struct: 1532 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break; 1533 case DeclSpec::TST_class: 1534 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break; 1535 } 1536 1537 if (TagName) { 1538 Diag(Loc, diag::err_use_of_tag_name_without_tag) 1539 << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus 1540 << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName); 1541 1542 // Parse this as a tag as if the missing tag were present. 1543 if (TagKind == tok::kw_enum) 1544 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS); 1545 else 1546 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS); 1547 return true; 1548 } 1549 } 1550 1551 // This is almost certainly an invalid type name. Let the action emit a 1552 // diagnostic and attempt to recover. 1553 ParsedType T; 1554 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc, 1555 getCurScope(), SS, T)) { 1556 // The action emitted a diagnostic, so we don't have to. 1557 if (T) { 1558 // The action has suggested that the type T could be used. Set that as 1559 // the type in the declaration specifiers, consume the would-be type 1560 // name token, and we're done. 1561 const char *PrevSpec; 1562 unsigned DiagID; 1563 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T); 1564 DS.SetRangeEnd(Tok.getLocation()); 1565 ConsumeToken(); 1566 1567 // There may be other declaration specifiers after this. 1568 return true; 1569 } 1570 1571 // Fall through; the action had no suggestion for us. 1572 } else { 1573 // The action did not emit a diagnostic, so emit one now. 1574 SourceRange R; 1575 if (SS) R = SS->getRange(); 1576 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R; 1577 } 1578 1579 // Mark this as an error. 1580 const char *PrevSpec; 1581 unsigned DiagID; 1582 DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID); 1583 DS.SetRangeEnd(Tok.getLocation()); 1584 ConsumeToken(); 1585 1586 // TODO: Could inject an invalid typedef decl in an enclosing scope to 1587 // avoid rippling error messages on subsequent uses of the same type, 1588 // could be useful if #include was forgotten. 1589 return false; 1590} 1591 1592/// \brief Determine the declaration specifier context from the declarator 1593/// context. 1594/// 1595/// \param Context the declarator context, which is one of the 1596/// Declarator::TheContext enumerator values. 1597Parser::DeclSpecContext 1598Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { 1599 if (Context == Declarator::MemberContext) 1600 return DSC_class; 1601 if (Context == Declarator::FileContext) 1602 return DSC_top_level; 1603 return DSC_normal; 1604} 1605 1606/// ParseAlignArgument - Parse the argument to an alignment-specifier. 1607/// 1608/// FIXME: Simply returns an alignof() expression if the argument is a 1609/// type. Ideally, the type should be propagated directly into Sema. 1610/// 1611/// [C11] type-id 1612/// [C11] constant-expression 1613/// [C++0x] type-id ...[opt] 1614/// [C++0x] assignment-expression ...[opt] 1615ExprResult Parser::ParseAlignArgument(SourceLocation Start, 1616 SourceLocation &EllipsisLoc) { 1617 ExprResult ER; 1618 if (isTypeIdInParens()) { 1619 SourceLocation TypeLoc = Tok.getLocation(); 1620 ParsedType Ty = ParseTypeName().get(); 1621 SourceRange TypeRange(Start, Tok.getLocation()); 1622 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true, 1623 Ty.getAsOpaquePtr(), TypeRange); 1624 } else 1625 ER = ParseConstantExpression(); 1626 1627 if (getLang().CPlusPlus0x && Tok.is(tok::ellipsis)) 1628 EllipsisLoc = ConsumeToken(); 1629 1630 return ER; 1631} 1632 1633/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the 1634/// attribute to Attrs. 1635/// 1636/// alignment-specifier: 1637/// [C11] '_Alignas' '(' type-id ')' 1638/// [C11] '_Alignas' '(' constant-expression ')' 1639/// [C++0x] 'alignas' '(' type-id ...[opt] ')' 1640/// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')' 1641void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs, 1642 SourceLocation *endLoc) { 1643 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) && 1644 "Not an alignment-specifier!"); 1645 1646 SourceLocation KWLoc = Tok.getLocation(); 1647 ConsumeToken(); 1648 1649 BalancedDelimiterTracker T(*this, tok::l_paren); 1650 if (T.expectAndConsume(diag::err_expected_lparen)) 1651 return; 1652 1653 SourceLocation EllipsisLoc; 1654 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc); 1655 if (ArgExpr.isInvalid()) { 1656 SkipUntil(tok::r_paren); 1657 return; 1658 } 1659 1660 T.consumeClose(); 1661 if (endLoc) 1662 *endLoc = T.getCloseLocation(); 1663 1664 // FIXME: Handle pack-expansions here. 1665 if (EllipsisLoc.isValid()) { 1666 Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported); 1667 return; 1668 } 1669 1670 ExprVector ArgExprs(Actions); 1671 ArgExprs.push_back(ArgExpr.release()); 1672 Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc, 1673 0, T.getOpenLocation(), ArgExprs.take(), 1, false, true); 1674} 1675 1676/// ParseDeclarationSpecifiers 1677/// declaration-specifiers: [C99 6.7] 1678/// storage-class-specifier declaration-specifiers[opt] 1679/// type-specifier declaration-specifiers[opt] 1680/// [C99] function-specifier declaration-specifiers[opt] 1681/// [C11] alignment-specifier declaration-specifiers[opt] 1682/// [GNU] attributes declaration-specifiers[opt] 1683/// [Clang] '__module_private__' declaration-specifiers[opt] 1684/// 1685/// storage-class-specifier: [C99 6.7.1] 1686/// 'typedef' 1687/// 'extern' 1688/// 'static' 1689/// 'auto' 1690/// 'register' 1691/// [C++] 'mutable' 1692/// [GNU] '__thread' 1693/// function-specifier: [C99 6.7.4] 1694/// [C99] 'inline' 1695/// [C++] 'virtual' 1696/// [C++] 'explicit' 1697/// [OpenCL] '__kernel' 1698/// 'friend': [C++ dcl.friend] 1699/// 'constexpr': [C++0x dcl.constexpr] 1700 1701/// 1702void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 1703 const ParsedTemplateInfo &TemplateInfo, 1704 AccessSpecifier AS, 1705 DeclSpecContext DSContext) { 1706 if (DS.getSourceRange().isInvalid()) { 1707 DS.SetRangeStart(Tok.getLocation()); 1708 DS.SetRangeEnd(Tok.getLocation()); 1709 } 1710 1711 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); 1712 while (1) { 1713 bool isInvalid = false; 1714 const char *PrevSpec = 0; 1715 unsigned DiagID = 0; 1716 1717 SourceLocation Loc = Tok.getLocation(); 1718 1719 switch (Tok.getKind()) { 1720 default: 1721 DoneWithDeclSpec: 1722 // [C++0x] decl-specifier-seq: decl-specifier attribute-specifier-seq[opt] 1723 MaybeParseCXX0XAttributes(DS.getAttributes()); 1724 1725 // If this is not a declaration specifier token, we're done reading decl 1726 // specifiers. First verify that DeclSpec's are consistent. 1727 DS.Finish(Diags, PP); 1728 return; 1729 1730 case tok::code_completion: { 1731 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 1732 if (DS.hasTypeSpecifier()) { 1733 bool AllowNonIdentifiers 1734 = (getCurScope()->getFlags() & (Scope::ControlScope | 1735 Scope::BlockScope | 1736 Scope::TemplateParamScope | 1737 Scope::FunctionPrototypeScope | 1738 Scope::AtCatchScope)) == 0; 1739 bool AllowNestedNameSpecifiers 1740 = DSContext == DSC_top_level || 1741 (DSContext == DSC_class && DS.isFriendSpecified()); 1742 1743 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 1744 AllowNonIdentifiers, 1745 AllowNestedNameSpecifiers); 1746 return cutOffParsing(); 1747 } 1748 1749 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) 1750 CCC = Sema::PCC_LocalDeclarationSpecifiers; 1751 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 1752 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate 1753 : Sema::PCC_Template; 1754 else if (DSContext == DSC_class) 1755 CCC = Sema::PCC_Class; 1756 else if (CurParsedObjCImpl) 1757 CCC = Sema::PCC_ObjCImplementation; 1758 1759 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 1760 return cutOffParsing(); 1761 } 1762 1763 case tok::coloncolon: // ::foo::bar 1764 // C++ scope specifier. Annotate and loop, or bail out on error. 1765 if (TryAnnotateCXXScopeToken(true)) { 1766 if (!DS.hasTypeSpecifier()) 1767 DS.SetTypeSpecError(); 1768 goto DoneWithDeclSpec; 1769 } 1770 if (Tok.is(tok::coloncolon)) // ::new or ::delete 1771 goto DoneWithDeclSpec; 1772 continue; 1773 1774 case tok::annot_cxxscope: { 1775 if (DS.hasTypeSpecifier()) 1776 goto DoneWithDeclSpec; 1777 1778 CXXScopeSpec SS; 1779 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 1780 Tok.getAnnotationRange(), 1781 SS); 1782 1783 // We are looking for a qualified typename. 1784 Token Next = NextToken(); 1785 if (Next.is(tok::annot_template_id) && 1786 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 1787 ->Kind == TNK_Type_template) { 1788 // We have a qualified template-id, e.g., N::A<int> 1789 1790 // C++ [class.qual]p2: 1791 // In a lookup in which the constructor is an acceptable lookup 1792 // result and the nested-name-specifier nominates a class C: 1793 // 1794 // - if the name specified after the 1795 // nested-name-specifier, when looked up in C, is the 1796 // injected-class-name of C (Clause 9), or 1797 // 1798 // - if the name specified after the nested-name-specifier 1799 // is the same as the identifier or the 1800 // simple-template-id's template-name in the last 1801 // component of the nested-name-specifier, 1802 // 1803 // the name is instead considered to name the constructor of 1804 // class C. 1805 // 1806 // Thus, if the template-name is actually the constructor 1807 // name, then the code is ill-formed; this interpretation is 1808 // reinforced by the NAD status of core issue 635. 1809 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 1810 if ((DSContext == DSC_top_level || 1811 (DSContext == DSC_class && DS.isFriendSpecified())) && 1812 TemplateId->Name && 1813 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 1814 if (isConstructorDeclarator()) { 1815 // The user meant this to be an out-of-line constructor 1816 // definition, but template arguments are not allowed 1817 // there. Just allow this as a constructor; we'll 1818 // complain about it later. 1819 goto DoneWithDeclSpec; 1820 } 1821 1822 // The user meant this to name a type, but it actually names 1823 // a constructor with some extraneous template 1824 // arguments. Complain, then parse it as a type as the user 1825 // intended. 1826 Diag(TemplateId->TemplateNameLoc, 1827 diag::err_out_of_line_template_id_names_constructor) 1828 << TemplateId->Name; 1829 } 1830 1831 DS.getTypeSpecScope() = SS; 1832 ConsumeToken(); // The C++ scope. 1833 assert(Tok.is(tok::annot_template_id) && 1834 "ParseOptionalCXXScopeSpecifier not working"); 1835 AnnotateTemplateIdTokenAsType(); 1836 continue; 1837 } 1838 1839 if (Next.is(tok::annot_typename)) { 1840 DS.getTypeSpecScope() = SS; 1841 ConsumeToken(); // The C++ scope. 1842 if (Tok.getAnnotationValue()) { 1843 ParsedType T = getTypeAnnotation(Tok); 1844 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 1845 Tok.getAnnotationEndLoc(), 1846 PrevSpec, DiagID, T); 1847 } 1848 else 1849 DS.SetTypeSpecError(); 1850 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1851 ConsumeToken(); // The typename 1852 } 1853 1854 if (Next.isNot(tok::identifier)) 1855 goto DoneWithDeclSpec; 1856 1857 // If we're in a context where the identifier could be a class name, 1858 // check whether this is a constructor declaration. 1859 if ((DSContext == DSC_top_level || 1860 (DSContext == DSC_class && DS.isFriendSpecified())) && 1861 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 1862 &SS)) { 1863 if (isConstructorDeclarator()) 1864 goto DoneWithDeclSpec; 1865 1866 // As noted in C++ [class.qual]p2 (cited above), when the name 1867 // of the class is qualified in a context where it could name 1868 // a constructor, its a constructor name. However, we've 1869 // looked at the declarator, and the user probably meant this 1870 // to be a type. Complain that it isn't supposed to be treated 1871 // as a type, then proceed to parse it as a type. 1872 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 1873 << Next.getIdentifierInfo(); 1874 } 1875 1876 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 1877 Next.getLocation(), 1878 getCurScope(), &SS, 1879 false, false, ParsedType(), 1880 /*IsCtorOrDtorName=*/false, 1881 /*NonTrivialSourceInfo=*/true); 1882 1883 // If the referenced identifier is not a type, then this declspec is 1884 // erroneous: We already checked about that it has no type specifier, and 1885 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 1886 // typename. 1887 if (TypeRep == 0) { 1888 ConsumeToken(); // Eat the scope spec so the identifier is current. 1889 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue; 1890 goto DoneWithDeclSpec; 1891 } 1892 1893 DS.getTypeSpecScope() = SS; 1894 ConsumeToken(); // The C++ scope. 1895 1896 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1897 DiagID, TypeRep); 1898 if (isInvalid) 1899 break; 1900 1901 DS.SetRangeEnd(Tok.getLocation()); 1902 ConsumeToken(); // The typename. 1903 1904 continue; 1905 } 1906 1907 case tok::annot_typename: { 1908 if (Tok.getAnnotationValue()) { 1909 ParsedType T = getTypeAnnotation(Tok); 1910 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1911 DiagID, T); 1912 } else 1913 DS.SetTypeSpecError(); 1914 1915 if (isInvalid) 1916 break; 1917 1918 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1919 ConsumeToken(); // The typename 1920 1921 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1922 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1923 // Objective-C interface. 1924 if (Tok.is(tok::less) && getLang().ObjC1) 1925 ParseObjCProtocolQualifiers(DS); 1926 1927 continue; 1928 } 1929 1930 case tok::kw___is_signed: 1931 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang 1932 // typically treats it as a trait. If we see __is_signed as it appears 1933 // in libstdc++, e.g., 1934 // 1935 // static const bool __is_signed; 1936 // 1937 // then treat __is_signed as an identifier rather than as a keyword. 1938 if (DS.getTypeSpecType() == TST_bool && 1939 DS.getTypeQualifiers() == DeclSpec::TQ_const && 1940 DS.getStorageClassSpec() == DeclSpec::SCS_static) { 1941 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 1942 Tok.setKind(tok::identifier); 1943 } 1944 1945 // We're done with the declaration-specifiers. 1946 goto DoneWithDeclSpec; 1947 1948 // typedef-name 1949 case tok::kw_decltype: 1950 case tok::identifier: { 1951 // In C++, check to see if this is a scope specifier like foo::bar::, if 1952 // so handle it as such. This is important for ctor parsing. 1953 if (getLang().CPlusPlus) { 1954 if (TryAnnotateCXXScopeToken(true)) { 1955 if (!DS.hasTypeSpecifier()) 1956 DS.SetTypeSpecError(); 1957 goto DoneWithDeclSpec; 1958 } 1959 if (!Tok.is(tok::identifier)) 1960 continue; 1961 } 1962 1963 // This identifier can only be a typedef name if we haven't already seen 1964 // a type-specifier. Without this check we misparse: 1965 // typedef int X; struct Y { short X; }; as 'short int'. 1966 if (DS.hasTypeSpecifier()) 1967 goto DoneWithDeclSpec; 1968 1969 // Check for need to substitute AltiVec keyword tokens. 1970 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 1971 break; 1972 1973 // It has to be available as a typedef too! 1974 ParsedType TypeRep = 1975 Actions.getTypeName(*Tok.getIdentifierInfo(), 1976 Tok.getLocation(), getCurScope()); 1977 1978 // If this is not a typedef name, don't parse it as part of the declspec, 1979 // it must be an implicit int or an error. 1980 if (!TypeRep) { 1981 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue; 1982 goto DoneWithDeclSpec; 1983 } 1984 1985 // If we're in a context where the identifier could be a class name, 1986 // check whether this is a constructor declaration. 1987 if (getLang().CPlusPlus && DSContext == DSC_class && 1988 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 1989 isConstructorDeclarator()) 1990 goto DoneWithDeclSpec; 1991 1992 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1993 DiagID, TypeRep); 1994 if (isInvalid) 1995 break; 1996 1997 DS.SetRangeEnd(Tok.getLocation()); 1998 ConsumeToken(); // The identifier 1999 2000 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 2001 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 2002 // Objective-C interface. 2003 if (Tok.is(tok::less) && getLang().ObjC1) 2004 ParseObjCProtocolQualifiers(DS); 2005 2006 // Need to support trailing type qualifiers (e.g. "id<p> const"). 2007 // If a type specifier follows, it will be diagnosed elsewhere. 2008 continue; 2009 } 2010 2011 // type-name 2012 case tok::annot_template_id: { 2013 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2014 if (TemplateId->Kind != TNK_Type_template) { 2015 // This template-id does not refer to a type name, so we're 2016 // done with the type-specifiers. 2017 goto DoneWithDeclSpec; 2018 } 2019 2020 // If we're in a context where the template-id could be a 2021 // constructor name or specialization, check whether this is a 2022 // constructor declaration. 2023 if (getLang().CPlusPlus && DSContext == DSC_class && 2024 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 2025 isConstructorDeclarator()) 2026 goto DoneWithDeclSpec; 2027 2028 // Turn the template-id annotation token into a type annotation 2029 // token, then try again to parse it as a type-specifier. 2030 AnnotateTemplateIdTokenAsType(); 2031 continue; 2032 } 2033 2034 // GNU attributes support. 2035 case tok::kw___attribute: 2036 ParseGNUAttributes(DS.getAttributes()); 2037 continue; 2038 2039 // Microsoft declspec support. 2040 case tok::kw___declspec: 2041 ParseMicrosoftDeclSpec(DS.getAttributes()); 2042 continue; 2043 2044 // Microsoft single token adornments. 2045 case tok::kw___forceinline: 2046 // FIXME: Add handling here! 2047 break; 2048 2049 case tok::kw___ptr64: 2050 case tok::kw___ptr32: 2051 case tok::kw___w64: 2052 case tok::kw___cdecl: 2053 case tok::kw___stdcall: 2054 case tok::kw___fastcall: 2055 case tok::kw___thiscall: 2056 case tok::kw___unaligned: 2057 ParseMicrosoftTypeAttributes(DS.getAttributes()); 2058 continue; 2059 2060 // Borland single token adornments. 2061 case tok::kw___pascal: 2062 ParseBorlandTypeAttributes(DS.getAttributes()); 2063 continue; 2064 2065 // OpenCL single token adornments. 2066 case tok::kw___kernel: 2067 ParseOpenCLAttributes(DS.getAttributes()); 2068 continue; 2069 2070 // storage-class-specifier 2071 case tok::kw_typedef: 2072 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc, 2073 PrevSpec, DiagID); 2074 break; 2075 case tok::kw_extern: 2076 if (DS.isThreadSpecified()) 2077 Diag(Tok, diag::ext_thread_before) << "extern"; 2078 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc, 2079 PrevSpec, DiagID); 2080 break; 2081 case tok::kw___private_extern__: 2082 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern, 2083 Loc, PrevSpec, DiagID); 2084 break; 2085 case tok::kw_static: 2086 if (DS.isThreadSpecified()) 2087 Diag(Tok, diag::ext_thread_before) << "static"; 2088 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc, 2089 PrevSpec, DiagID); 2090 break; 2091 case tok::kw_auto: 2092 if (getLang().CPlusPlus0x) { 2093 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 2094 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 2095 PrevSpec, DiagID); 2096 if (!isInvalid) 2097 Diag(Tok, diag::ext_auto_storage_class) 2098 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 2099 } else 2100 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 2101 DiagID); 2102 } else 2103 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 2104 PrevSpec, DiagID); 2105 break; 2106 case tok::kw_register: 2107 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc, 2108 PrevSpec, DiagID); 2109 break; 2110 case tok::kw_mutable: 2111 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc, 2112 PrevSpec, DiagID); 2113 break; 2114 case tok::kw___thread: 2115 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); 2116 break; 2117 2118 // function-specifier 2119 case tok::kw_inline: 2120 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 2121 break; 2122 case tok::kw_virtual: 2123 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID); 2124 break; 2125 case tok::kw_explicit: 2126 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID); 2127 break; 2128 2129 // alignment-specifier 2130 case tok::kw__Alignas: 2131 if (!getLang().C11) 2132 Diag(Tok, diag::ext_c11_alignas); 2133 ParseAlignmentSpecifier(DS.getAttributes()); 2134 continue; 2135 2136 // friend 2137 case tok::kw_friend: 2138 if (DSContext == DSC_class) 2139 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 2140 else { 2141 PrevSpec = ""; // not actually used by the diagnostic 2142 DiagID = diag::err_friend_invalid_in_context; 2143 isInvalid = true; 2144 } 2145 break; 2146 2147 // Modules 2148 case tok::kw___module_private__: 2149 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID); 2150 break; 2151 2152 // constexpr 2153 case tok::kw_constexpr: 2154 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 2155 break; 2156 2157 // type-specifier 2158 case tok::kw_short: 2159 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 2160 DiagID); 2161 break; 2162 case tok::kw_long: 2163 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 2164 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 2165 DiagID); 2166 else 2167 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 2168 DiagID); 2169 break; 2170 case tok::kw___int64: 2171 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 2172 DiagID); 2173 break; 2174 case tok::kw_signed: 2175 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 2176 DiagID); 2177 break; 2178 case tok::kw_unsigned: 2179 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 2180 DiagID); 2181 break; 2182 case tok::kw__Complex: 2183 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 2184 DiagID); 2185 break; 2186 case tok::kw__Imaginary: 2187 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 2188 DiagID); 2189 break; 2190 case tok::kw_void: 2191 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 2192 DiagID); 2193 break; 2194 case tok::kw_char: 2195 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 2196 DiagID); 2197 break; 2198 case tok::kw_int: 2199 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 2200 DiagID); 2201 break; 2202 case tok::kw_half: 2203 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, 2204 DiagID); 2205 break; 2206 case tok::kw_float: 2207 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 2208 DiagID); 2209 break; 2210 case tok::kw_double: 2211 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 2212 DiagID); 2213 break; 2214 case tok::kw_wchar_t: 2215 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 2216 DiagID); 2217 break; 2218 case tok::kw_char16_t: 2219 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 2220 DiagID); 2221 break; 2222 case tok::kw_char32_t: 2223 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 2224 DiagID); 2225 break; 2226 case tok::kw_bool: 2227 case tok::kw__Bool: 2228 if (Tok.is(tok::kw_bool) && 2229 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 2230 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 2231 PrevSpec = ""; // Not used by the diagnostic. 2232 DiagID = diag::err_bool_redeclaration; 2233 // For better error recovery. 2234 Tok.setKind(tok::identifier); 2235 isInvalid = true; 2236 } else { 2237 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 2238 DiagID); 2239 } 2240 break; 2241 case tok::kw__Decimal32: 2242 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 2243 DiagID); 2244 break; 2245 case tok::kw__Decimal64: 2246 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 2247 DiagID); 2248 break; 2249 case tok::kw__Decimal128: 2250 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 2251 DiagID); 2252 break; 2253 case tok::kw___vector: 2254 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 2255 break; 2256 case tok::kw___pixel: 2257 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 2258 break; 2259 case tok::kw___unknown_anytype: 2260 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 2261 PrevSpec, DiagID); 2262 break; 2263 2264 // class-specifier: 2265 case tok::kw_class: 2266 case tok::kw_struct: 2267 case tok::kw_union: { 2268 tok::TokenKind Kind = Tok.getKind(); 2269 ConsumeToken(); 2270 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, EnteringContext); 2271 continue; 2272 } 2273 2274 // enum-specifier: 2275 case tok::kw_enum: 2276 ConsumeToken(); 2277 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS); 2278 continue; 2279 2280 // cv-qualifier: 2281 case tok::kw_const: 2282 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 2283 getLang()); 2284 break; 2285 case tok::kw_volatile: 2286 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 2287 getLang()); 2288 break; 2289 case tok::kw_restrict: 2290 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 2291 getLang()); 2292 break; 2293 2294 // C++ typename-specifier: 2295 case tok::kw_typename: 2296 if (TryAnnotateTypeOrScopeToken()) { 2297 DS.SetTypeSpecError(); 2298 goto DoneWithDeclSpec; 2299 } 2300 if (!Tok.is(tok::kw_typename)) 2301 continue; 2302 break; 2303 2304 // GNU typeof support. 2305 case tok::kw_typeof: 2306 ParseTypeofSpecifier(DS); 2307 continue; 2308 2309 case tok::annot_decltype: 2310 ParseDecltypeSpecifier(DS); 2311 continue; 2312 2313 case tok::kw___underlying_type: 2314 ParseUnderlyingTypeSpecifier(DS); 2315 continue; 2316 2317 case tok::kw__Atomic: 2318 ParseAtomicSpecifier(DS); 2319 continue; 2320 2321 // OpenCL qualifiers: 2322 case tok::kw_private: 2323 if (!getLang().OpenCL) 2324 goto DoneWithDeclSpec; 2325 case tok::kw___private: 2326 case tok::kw___global: 2327 case tok::kw___local: 2328 case tok::kw___constant: 2329 case tok::kw___read_only: 2330 case tok::kw___write_only: 2331 case tok::kw___read_write: 2332 ParseOpenCLQualifiers(DS); 2333 break; 2334 2335 case tok::less: 2336 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 2337 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 2338 // but we support it. 2339 if (DS.hasTypeSpecifier() || !getLang().ObjC1) 2340 goto DoneWithDeclSpec; 2341 2342 if (!ParseObjCProtocolQualifiers(DS)) 2343 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 2344 << FixItHint::CreateInsertion(Loc, "id") 2345 << SourceRange(Loc, DS.getSourceRange().getEnd()); 2346 2347 // Need to support trailing type qualifiers (e.g. "id<p> const"). 2348 // If a type specifier follows, it will be diagnosed elsewhere. 2349 continue; 2350 } 2351 // If the specifier wasn't legal, issue a diagnostic. 2352 if (isInvalid) { 2353 assert(PrevSpec && "Method did not return previous specifier!"); 2354 assert(DiagID); 2355 2356 if (DiagID == diag::ext_duplicate_declspec) 2357 Diag(Tok, DiagID) 2358 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 2359 else 2360 Diag(Tok, DiagID) << PrevSpec; 2361 } 2362 2363 DS.SetRangeEnd(Tok.getLocation()); 2364 if (DiagID != diag::err_bool_redeclaration) 2365 ConsumeToken(); 2366 } 2367} 2368 2369/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We 2370/// primarily follow the C++ grammar with additions for C99 and GNU, 2371/// which together subsume the C grammar. Note that the C++ 2372/// type-specifier also includes the C type-qualifier (for const, 2373/// volatile, and C99 restrict). Returns true if a type-specifier was 2374/// found (and parsed), false otherwise. 2375/// 2376/// type-specifier: [C++ 7.1.5] 2377/// simple-type-specifier 2378/// class-specifier 2379/// enum-specifier 2380/// elaborated-type-specifier [TODO] 2381/// cv-qualifier 2382/// 2383/// cv-qualifier: [C++ 7.1.5.1] 2384/// 'const' 2385/// 'volatile' 2386/// [C99] 'restrict' 2387/// 2388/// simple-type-specifier: [ C++ 7.1.5.2] 2389/// '::'[opt] nested-name-specifier[opt] type-name [TODO] 2390/// '::'[opt] nested-name-specifier 'template' template-id [TODO] 2391/// 'char' 2392/// 'wchar_t' 2393/// 'bool' 2394/// 'short' 2395/// 'int' 2396/// 'long' 2397/// 'signed' 2398/// 'unsigned' 2399/// 'float' 2400/// 'double' 2401/// 'void' 2402/// [C99] '_Bool' 2403/// [C99] '_Complex' 2404/// [C99] '_Imaginary' // Removed in TC2? 2405/// [GNU] '_Decimal32' 2406/// [GNU] '_Decimal64' 2407/// [GNU] '_Decimal128' 2408/// [GNU] typeof-specifier 2409/// [OBJC] class-name objc-protocol-refs[opt] [TODO] 2410/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO] 2411/// [C++0x] 'decltype' ( expression ) 2412/// [AltiVec] '__vector' 2413bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, 2414 const char *&PrevSpec, 2415 unsigned &DiagID, 2416 const ParsedTemplateInfo &TemplateInfo, 2417 bool SuppressDeclarations) { 2418 SourceLocation Loc = Tok.getLocation(); 2419 2420 switch (Tok.getKind()) { 2421 case tok::identifier: // foo::bar 2422 // If we already have a type specifier, this identifier is not a type. 2423 if (DS.getTypeSpecType() != DeclSpec::TST_unspecified || 2424 DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified || 2425 DS.getTypeSpecSign() != DeclSpec::TSS_unspecified) 2426 return false; 2427 // Check for need to substitute AltiVec keyword tokens. 2428 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 2429 break; 2430 // Fall through. 2431 case tok::kw_decltype: 2432 case tok::kw_typename: // typename foo::bar 2433 // Annotate typenames and C++ scope specifiers. If we get one, just 2434 // recurse to handle whatever we get. 2435 if (TryAnnotateTypeOrScopeToken(/*EnteringContext=*/false, 2436 /*NeedType=*/true)) 2437 return true; 2438 if (Tok.is(tok::identifier)) 2439 return false; 2440 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 2441 TemplateInfo, SuppressDeclarations); 2442 case tok::coloncolon: // ::foo::bar 2443 if (NextToken().is(tok::kw_new) || // ::new 2444 NextToken().is(tok::kw_delete)) // ::delete 2445 return false; 2446 2447 // Annotate typenames and C++ scope specifiers. If we get one, just 2448 // recurse to handle whatever we get. 2449 if (TryAnnotateTypeOrScopeToken(/*EnteringContext=*/false, 2450 /*NeedType=*/true)) 2451 return true; 2452 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 2453 TemplateInfo, SuppressDeclarations); 2454 2455 // simple-type-specifier: 2456 case tok::annot_typename: { 2457 if (ParsedType T = getTypeAnnotation(Tok)) { 2458 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 2459 Tok.getAnnotationEndLoc(), PrevSpec, 2460 DiagID, T); 2461 } else 2462 DS.SetTypeSpecError(); 2463 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 2464 ConsumeToken(); // The typename 2465 2466 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 2467 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 2468 // Objective-C interface. If we don't have Objective-C or a '<', this is 2469 // just a normal reference to a typedef name. 2470 if (Tok.is(tok::less) && getLang().ObjC1) 2471 ParseObjCProtocolQualifiers(DS); 2472 2473 return true; 2474 } 2475 2476 case tok::kw_short: 2477 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 2478 break; 2479 case tok::kw_long: 2480 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 2481 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 2482 DiagID); 2483 else 2484 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 2485 DiagID); 2486 break; 2487 case tok::kw___int64: 2488 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 2489 DiagID); 2490 break; 2491 case tok::kw_signed: 2492 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 2493 break; 2494 case tok::kw_unsigned: 2495 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 2496 DiagID); 2497 break; 2498 case tok::kw__Complex: 2499 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 2500 DiagID); 2501 break; 2502 case tok::kw__Imaginary: 2503 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 2504 DiagID); 2505 break; 2506 case tok::kw_void: 2507 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 2508 break; 2509 case tok::kw_char: 2510 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 2511 break; 2512 case tok::kw_int: 2513 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 2514 break; 2515 case tok::kw_half: 2516 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID); 2517 break; 2518 case tok::kw_float: 2519 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 2520 break; 2521 case tok::kw_double: 2522 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 2523 break; 2524 case tok::kw_wchar_t: 2525 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 2526 break; 2527 case tok::kw_char16_t: 2528 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 2529 break; 2530 case tok::kw_char32_t: 2531 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 2532 break; 2533 case tok::kw_bool: 2534 case tok::kw__Bool: 2535 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 2536 break; 2537 case tok::kw__Decimal32: 2538 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 2539 DiagID); 2540 break; 2541 case tok::kw__Decimal64: 2542 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 2543 DiagID); 2544 break; 2545 case tok::kw__Decimal128: 2546 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 2547 DiagID); 2548 break; 2549 case tok::kw___vector: 2550 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 2551 break; 2552 case tok::kw___pixel: 2553 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 2554 break; 2555 2556 // class-specifier: 2557 case tok::kw_class: 2558 case tok::kw_struct: 2559 case tok::kw_union: { 2560 tok::TokenKind Kind = Tok.getKind(); 2561 ConsumeToken(); 2562 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none, 2563 /*EnteringContext=*/false, 2564 SuppressDeclarations); 2565 return true; 2566 } 2567 2568 // enum-specifier: 2569 case tok::kw_enum: 2570 ConsumeToken(); 2571 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none); 2572 return true; 2573 2574 // cv-qualifier: 2575 case tok::kw_const: 2576 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 2577 DiagID, getLang()); 2578 break; 2579 case tok::kw_volatile: 2580 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 2581 DiagID, getLang()); 2582 break; 2583 case tok::kw_restrict: 2584 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 2585 DiagID, getLang()); 2586 break; 2587 2588 // GNU typeof support. 2589 case tok::kw_typeof: 2590 ParseTypeofSpecifier(DS); 2591 return true; 2592 2593 // C++0x decltype support. 2594 case tok::annot_decltype: 2595 ParseDecltypeSpecifier(DS); 2596 return true; 2597 2598 // C++0x type traits support. 2599 case tok::kw___underlying_type: 2600 ParseUnderlyingTypeSpecifier(DS); 2601 return true; 2602 2603 case tok::kw__Atomic: 2604 ParseAtomicSpecifier(DS); 2605 return true; 2606 2607 // OpenCL qualifiers: 2608 case tok::kw_private: 2609 if (!getLang().OpenCL) 2610 return false; 2611 case tok::kw___private: 2612 case tok::kw___global: 2613 case tok::kw___local: 2614 case tok::kw___constant: 2615 case tok::kw___read_only: 2616 case tok::kw___write_only: 2617 case tok::kw___read_write: 2618 ParseOpenCLQualifiers(DS); 2619 break; 2620 2621 // C++0x auto support. 2622 case tok::kw_auto: 2623 // This is only called in situations where a storage-class specifier is 2624 // illegal, so we can assume an auto type specifier was intended even in 2625 // C++98. In C++98 mode, DeclSpec::Finish will produce an appropriate 2626 // extension diagnostic. 2627 if (!getLang().CPlusPlus) 2628 return false; 2629 2630 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID); 2631 break; 2632 2633 case tok::kw___ptr64: 2634 case tok::kw___ptr32: 2635 case tok::kw___w64: 2636 case tok::kw___cdecl: 2637 case tok::kw___stdcall: 2638 case tok::kw___fastcall: 2639 case tok::kw___thiscall: 2640 case tok::kw___unaligned: 2641 ParseMicrosoftTypeAttributes(DS.getAttributes()); 2642 return true; 2643 2644 case tok::kw___pascal: 2645 ParseBorlandTypeAttributes(DS.getAttributes()); 2646 return true; 2647 2648 default: 2649 // Not a type-specifier; do nothing. 2650 return false; 2651 } 2652 2653 // If the specifier combination wasn't legal, issue a diagnostic. 2654 if (isInvalid) { 2655 assert(PrevSpec && "Method did not return previous specifier!"); 2656 // Pick between error or extwarn. 2657 Diag(Tok, DiagID) << PrevSpec; 2658 } 2659 DS.SetRangeEnd(Tok.getLocation()); 2660 ConsumeToken(); // whatever we parsed above. 2661 return true; 2662} 2663 2664/// ParseStructDeclaration - Parse a struct declaration without the terminating 2665/// semicolon. 2666/// 2667/// struct-declaration: 2668/// specifier-qualifier-list struct-declarator-list 2669/// [GNU] __extension__ struct-declaration 2670/// [GNU] specifier-qualifier-list 2671/// struct-declarator-list: 2672/// struct-declarator 2673/// struct-declarator-list ',' struct-declarator 2674/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 2675/// struct-declarator: 2676/// declarator 2677/// [GNU] declarator attributes[opt] 2678/// declarator[opt] ':' constant-expression 2679/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 2680/// 2681void Parser:: 2682ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) { 2683 2684 if (Tok.is(tok::kw___extension__)) { 2685 // __extension__ silences extension warnings in the subexpression. 2686 ExtensionRAIIObject O(Diags); // Use RAII to do this. 2687 ConsumeToken(); 2688 return ParseStructDeclaration(DS, Fields); 2689 } 2690 2691 // Parse the common specifier-qualifiers-list piece. 2692 ParseSpecifierQualifierList(DS); 2693 2694 // If there are no declarators, this is a free-standing declaration 2695 // specifier. Let the actions module cope with it. 2696 if (Tok.is(tok::semi)) { 2697 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS); 2698 return; 2699 } 2700 2701 // Read struct-declarators until we find the semicolon. 2702 bool FirstDeclarator = true; 2703 SourceLocation CommaLoc; 2704 while (1) { 2705 ParsingDeclRAIIObject PD(*this); 2706 FieldDeclarator DeclaratorInfo(DS); 2707 DeclaratorInfo.D.setCommaLoc(CommaLoc); 2708 2709 // Attributes are only allowed here on successive declarators. 2710 if (!FirstDeclarator) 2711 MaybeParseGNUAttributes(DeclaratorInfo.D); 2712 2713 /// struct-declarator: declarator 2714 /// struct-declarator: declarator[opt] ':' constant-expression 2715 if (Tok.isNot(tok::colon)) { 2716 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 2717 ColonProtectionRAIIObject X(*this); 2718 ParseDeclarator(DeclaratorInfo.D); 2719 } 2720 2721 if (Tok.is(tok::colon)) { 2722 ConsumeToken(); 2723 ExprResult Res(ParseConstantExpression()); 2724 if (Res.isInvalid()) 2725 SkipUntil(tok::semi, true, true); 2726 else 2727 DeclaratorInfo.BitfieldSize = Res.release(); 2728 } 2729 2730 // If attributes exist after the declarator, parse them. 2731 MaybeParseGNUAttributes(DeclaratorInfo.D); 2732 2733 // We're done with this declarator; invoke the callback. 2734 Decl *D = Fields.invoke(DeclaratorInfo); 2735 PD.complete(D); 2736 2737 // If we don't have a comma, it is either the end of the list (a ';') 2738 // or an error, bail out. 2739 if (Tok.isNot(tok::comma)) 2740 return; 2741 2742 // Consume the comma. 2743 CommaLoc = ConsumeToken(); 2744 2745 FirstDeclarator = false; 2746 } 2747} 2748 2749/// ParseStructUnionBody 2750/// struct-contents: 2751/// struct-declaration-list 2752/// [EXT] empty 2753/// [GNU] "struct-declaration-list" without terminatoring ';' 2754/// struct-declaration-list: 2755/// struct-declaration 2756/// struct-declaration-list struct-declaration 2757/// [OBC] '@' 'defs' '(' class-name ')' 2758/// 2759void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 2760 unsigned TagType, Decl *TagDecl) { 2761 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 2762 "parsing struct/union body"); 2763 2764 BalancedDelimiterTracker T(*this, tok::l_brace); 2765 if (T.consumeOpen()) 2766 return; 2767 2768 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 2769 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 2770 2771 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 2772 // C++. 2773 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) { 2774 Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union); 2775 Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union); 2776 } 2777 2778 SmallVector<Decl *, 32> FieldDecls; 2779 2780 // While we still have something to read, read the declarations in the struct. 2781 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 2782 // Each iteration of this loop reads one struct-declaration. 2783 2784 // Check for extraneous top-level semicolon. 2785 if (Tok.is(tok::semi)) { 2786 Diag(Tok, diag::ext_extra_struct_semi) 2787 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType) 2788 << FixItHint::CreateRemoval(Tok.getLocation()); 2789 ConsumeToken(); 2790 continue; 2791 } 2792 2793 // Parse all the comma separated declarators. 2794 DeclSpec DS(AttrFactory); 2795 2796 if (!Tok.is(tok::at)) { 2797 struct CFieldCallback : FieldCallback { 2798 Parser &P; 2799 Decl *TagDecl; 2800 SmallVectorImpl<Decl *> &FieldDecls; 2801 2802 CFieldCallback(Parser &P, Decl *TagDecl, 2803 SmallVectorImpl<Decl *> &FieldDecls) : 2804 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 2805 2806 virtual Decl *invoke(FieldDeclarator &FD) { 2807 // Install the declarator into the current TagDecl. 2808 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl, 2809 FD.D.getDeclSpec().getSourceRange().getBegin(), 2810 FD.D, FD.BitfieldSize); 2811 FieldDecls.push_back(Field); 2812 return Field; 2813 } 2814 } Callback(*this, TagDecl, FieldDecls); 2815 2816 ParseStructDeclaration(DS, Callback); 2817 } else { // Handle @defs 2818 ConsumeToken(); 2819 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 2820 Diag(Tok, diag::err_unexpected_at); 2821 SkipUntil(tok::semi, true); 2822 continue; 2823 } 2824 ConsumeToken(); 2825 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 2826 if (!Tok.is(tok::identifier)) { 2827 Diag(Tok, diag::err_expected_ident); 2828 SkipUntil(tok::semi, true); 2829 continue; 2830 } 2831 SmallVector<Decl *, 16> Fields; 2832 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 2833 Tok.getIdentifierInfo(), Fields); 2834 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 2835 ConsumeToken(); 2836 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 2837 } 2838 2839 if (Tok.is(tok::semi)) { 2840 ConsumeToken(); 2841 } else if (Tok.is(tok::r_brace)) { 2842 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 2843 break; 2844 } else { 2845 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 2846 // Skip to end of block or statement to avoid ext-warning on extra ';'. 2847 SkipUntil(tok::r_brace, true, true); 2848 // If we stopped at a ';', eat it. 2849 if (Tok.is(tok::semi)) ConsumeToken(); 2850 } 2851 } 2852 2853 T.consumeClose(); 2854 2855 ParsedAttributes attrs(AttrFactory); 2856 // If attributes exist after struct contents, parse them. 2857 MaybeParseGNUAttributes(attrs); 2858 2859 Actions.ActOnFields(getCurScope(), 2860 RecordLoc, TagDecl, FieldDecls, 2861 T.getOpenLocation(), T.getCloseLocation(), 2862 attrs.getList()); 2863 StructScope.Exit(); 2864 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 2865 T.getCloseLocation()); 2866} 2867 2868/// ParseEnumSpecifier 2869/// enum-specifier: [C99 6.7.2.2] 2870/// 'enum' identifier[opt] '{' enumerator-list '}' 2871///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 2872/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 2873/// '}' attributes[opt] 2874/// 'enum' identifier 2875/// [GNU] 'enum' attributes[opt] identifier 2876/// 2877/// [C++0x] enum-head '{' enumerator-list[opt] '}' 2878/// [C++0x] enum-head '{' enumerator-list ',' '}' 2879/// 2880/// enum-head: [C++0x] 2881/// enum-key attributes[opt] identifier[opt] enum-base[opt] 2882/// enum-key attributes[opt] nested-name-specifier identifier enum-base[opt] 2883/// 2884/// enum-key: [C++0x] 2885/// 'enum' 2886/// 'enum' 'class' 2887/// 'enum' 'struct' 2888/// 2889/// enum-base: [C++0x] 2890/// ':' type-specifier-seq 2891/// 2892/// [C++] elaborated-type-specifier: 2893/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 2894/// 2895void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 2896 const ParsedTemplateInfo &TemplateInfo, 2897 AccessSpecifier AS) { 2898 // Parse the tag portion of this. 2899 if (Tok.is(tok::code_completion)) { 2900 // Code completion for an enum name. 2901 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 2902 return cutOffParsing(); 2903 } 2904 2905 SourceLocation ScopedEnumKWLoc; 2906 bool IsScopedUsingClassTag = false; 2907 2908 if (getLang().CPlusPlus0x && 2909 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) { 2910 Diag(Tok, diag::warn_cxx98_compat_scoped_enum); 2911 IsScopedUsingClassTag = Tok.is(tok::kw_class); 2912 ScopedEnumKWLoc = ConsumeToken(); 2913 } 2914 2915 // If attributes exist after tag, parse them. 2916 ParsedAttributes attrs(AttrFactory); 2917 MaybeParseGNUAttributes(attrs); 2918 2919 bool AllowFixedUnderlyingType 2920 = getLang().CPlusPlus0x || getLang().MicrosoftExt || getLang().ObjC2; 2921 2922 CXXScopeSpec &SS = DS.getTypeSpecScope(); 2923 if (getLang().CPlusPlus) { 2924 // "enum foo : bar;" is not a potential typo for "enum foo::bar;" 2925 // if a fixed underlying type is allowed. 2926 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); 2927 2928 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 2929 /*EnteringContext=*/false)) 2930 return; 2931 2932 if (SS.isSet() && Tok.isNot(tok::identifier)) { 2933 Diag(Tok, diag::err_expected_ident); 2934 if (Tok.isNot(tok::l_brace)) { 2935 // Has no name and is not a definition. 2936 // Skip the rest of this declarator, up until the comma or semicolon. 2937 SkipUntil(tok::comma, true); 2938 return; 2939 } 2940 } 2941 } 2942 2943 // Must have either 'enum name' or 'enum {...}'. 2944 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 2945 (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) { 2946 Diag(Tok, diag::err_expected_ident_lbrace); 2947 2948 // Skip the rest of this declarator, up until the comma or semicolon. 2949 SkipUntil(tok::comma, true); 2950 return; 2951 } 2952 2953 // If an identifier is present, consume and remember it. 2954 IdentifierInfo *Name = 0; 2955 SourceLocation NameLoc; 2956 if (Tok.is(tok::identifier)) { 2957 Name = Tok.getIdentifierInfo(); 2958 NameLoc = ConsumeToken(); 2959 } 2960 2961 if (!Name && ScopedEnumKWLoc.isValid()) { 2962 // C++0x 7.2p2: The optional identifier shall not be omitted in the 2963 // declaration of a scoped enumeration. 2964 Diag(Tok, diag::err_scoped_enum_missing_identifier); 2965 ScopedEnumKWLoc = SourceLocation(); 2966 IsScopedUsingClassTag = false; 2967 } 2968 2969 TypeResult BaseType; 2970 2971 // Parse the fixed underlying type. 2972 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 2973 bool PossibleBitfield = false; 2974 if (getCurScope()->getFlags() & Scope::ClassScope) { 2975 // If we're in class scope, this can either be an enum declaration with 2976 // an underlying type, or a declaration of a bitfield member. We try to 2977 // use a simple disambiguation scheme first to catch the common cases 2978 // (integer literal, sizeof); if it's still ambiguous, we then consider 2979 // anything that's a simple-type-specifier followed by '(' as an 2980 // expression. This suffices because function types are not valid 2981 // underlying types anyway. 2982 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 2983 // If the next token starts an expression, we know we're parsing a 2984 // bit-field. This is the common case. 2985 if (TPR == TPResult::True()) 2986 PossibleBitfield = true; 2987 // If the next token starts a type-specifier-seq, it may be either a 2988 // a fixed underlying type or the start of a function-style cast in C++; 2989 // lookahead one more token to see if it's obvious that we have a 2990 // fixed underlying type. 2991 else if (TPR == TPResult::False() && 2992 GetLookAheadToken(2).getKind() == tok::semi) { 2993 // Consume the ':'. 2994 ConsumeToken(); 2995 } else { 2996 // We have the start of a type-specifier-seq, so we have to perform 2997 // tentative parsing to determine whether we have an expression or a 2998 // type. 2999 TentativeParsingAction TPA(*this); 3000 3001 // Consume the ':'. 3002 ConsumeToken(); 3003 3004 // If we see a type specifier followed by an open-brace, we have an 3005 // ambiguity between an underlying type and a C++11 braced 3006 // function-style cast. Resolve this by always treating it as an 3007 // underlying type. 3008 // FIXME: The standard is not entirely clear on how to disambiguate in 3009 // this case. 3010 if ((getLang().CPlusPlus && 3011 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) || 3012 (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) { 3013 // We'll parse this as a bitfield later. 3014 PossibleBitfield = true; 3015 TPA.Revert(); 3016 } else { 3017 // We have a type-specifier-seq. 3018 TPA.Commit(); 3019 } 3020 } 3021 } else { 3022 // Consume the ':'. 3023 ConsumeToken(); 3024 } 3025 3026 if (!PossibleBitfield) { 3027 SourceRange Range; 3028 BaseType = ParseTypeName(&Range); 3029 3030 if (!getLang().CPlusPlus0x && !getLang().ObjC2) 3031 Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type) 3032 << Range; 3033 if (getLang().CPlusPlus0x) 3034 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); 3035 } 3036 } 3037 3038 // There are four options here. If we have 'friend enum foo;' then this is a 3039 // friend declaration, and cannot have an accompanying definition. If we have 3040 // 'enum foo;', then this is a forward declaration. If we have 3041 // 'enum foo {...' then this is a definition. Otherwise we have something 3042 // like 'enum foo xyz', a reference. 3043 // 3044 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 3045 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 3046 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 3047 // 3048 Sema::TagUseKind TUK; 3049 if (DS.isFriendSpecified()) 3050 TUK = Sema::TUK_Friend; 3051 else if (Tok.is(tok::l_brace)) 3052 TUK = Sema::TUK_Definition; 3053 else if (Tok.is(tok::semi)) 3054 TUK = Sema::TUK_Declaration; 3055 else 3056 TUK = Sema::TUK_Reference; 3057 3058 // enums cannot be templates, although they can be referenced from a 3059 // template. 3060 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 3061 TUK != Sema::TUK_Reference) { 3062 Diag(Tok, diag::err_enum_template); 3063 3064 // Skip the rest of this declarator, up until the comma or semicolon. 3065 SkipUntil(tok::comma, true); 3066 return; 3067 } 3068 3069 if (!Name && TUK != Sema::TUK_Definition) { 3070 Diag(Tok, diag::err_enumerator_unnamed_no_def); 3071 3072 // Skip the rest of this declarator, up until the comma or semicolon. 3073 SkipUntil(tok::comma, true); 3074 return; 3075 } 3076 3077 bool Owned = false; 3078 bool IsDependent = false; 3079 const char *PrevSpec = 0; 3080 unsigned DiagID; 3081 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 3082 StartLoc, SS, Name, NameLoc, attrs.getList(), 3083 AS, DS.getModulePrivateSpecLoc(), 3084 MultiTemplateParamsArg(Actions), 3085 Owned, IsDependent, ScopedEnumKWLoc, 3086 IsScopedUsingClassTag, BaseType); 3087 3088 if (IsDependent) { 3089 // This enum has a dependent nested-name-specifier. Handle it as a 3090 // dependent tag. 3091 if (!Name) { 3092 DS.SetTypeSpecError(); 3093 Diag(Tok, diag::err_expected_type_name_after_typename); 3094 return; 3095 } 3096 3097 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum, 3098 TUK, SS, Name, StartLoc, 3099 NameLoc); 3100 if (Type.isInvalid()) { 3101 DS.SetTypeSpecError(); 3102 return; 3103 } 3104 3105 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 3106 NameLoc.isValid() ? NameLoc : StartLoc, 3107 PrevSpec, DiagID, Type.get())) 3108 Diag(StartLoc, DiagID) << PrevSpec; 3109 3110 return; 3111 } 3112 3113 if (!TagDecl) { 3114 // The action failed to produce an enumeration tag. If this is a 3115 // definition, consume the entire definition. 3116 if (Tok.is(tok::l_brace)) { 3117 ConsumeBrace(); 3118 SkipUntil(tok::r_brace); 3119 } 3120 3121 DS.SetTypeSpecError(); 3122 return; 3123 } 3124 3125 if (Tok.is(tok::l_brace)) { 3126 if (TUK == Sema::TUK_Friend) 3127 Diag(Tok, diag::err_friend_decl_defines_type) 3128 << SourceRange(DS.getFriendSpecLoc()); 3129 ParseEnumBody(StartLoc, TagDecl); 3130 } 3131 3132 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 3133 NameLoc.isValid() ? NameLoc : StartLoc, 3134 PrevSpec, DiagID, TagDecl, Owned)) 3135 Diag(StartLoc, DiagID) << PrevSpec; 3136} 3137 3138/// ParseEnumBody - Parse a {} enclosed enumerator-list. 3139/// enumerator-list: 3140/// enumerator 3141/// enumerator-list ',' enumerator 3142/// enumerator: 3143/// enumeration-constant 3144/// enumeration-constant '=' constant-expression 3145/// enumeration-constant: 3146/// identifier 3147/// 3148void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 3149 // Enter the scope of the enum body and start the definition. 3150 ParseScope EnumScope(this, Scope::DeclScope); 3151 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 3152 3153 BalancedDelimiterTracker T(*this, tok::l_brace); 3154 T.consumeOpen(); 3155 3156 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 3157 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 3158 Diag(Tok, diag::error_empty_enum); 3159 3160 SmallVector<Decl *, 32> EnumConstantDecls; 3161 3162 Decl *LastEnumConstDecl = 0; 3163 3164 // Parse the enumerator-list. 3165 while (Tok.is(tok::identifier)) { 3166 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 3167 SourceLocation IdentLoc = ConsumeToken(); 3168 3169 // If attributes exist after the enumerator, parse them. 3170 ParsedAttributes attrs(AttrFactory); 3171 MaybeParseGNUAttributes(attrs); 3172 3173 SourceLocation EqualLoc; 3174 ExprResult AssignedVal; 3175 ParsingDeclRAIIObject PD(*this); 3176 3177 if (Tok.is(tok::equal)) { 3178 EqualLoc = ConsumeToken(); 3179 AssignedVal = ParseConstantExpression(); 3180 if (AssignedVal.isInvalid()) 3181 SkipUntil(tok::comma, tok::r_brace, true, true); 3182 } 3183 3184 // Install the enumerator constant into EnumDecl. 3185 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 3186 LastEnumConstDecl, 3187 IdentLoc, Ident, 3188 attrs.getList(), EqualLoc, 3189 AssignedVal.release()); 3190 PD.complete(EnumConstDecl); 3191 3192 EnumConstantDecls.push_back(EnumConstDecl); 3193 LastEnumConstDecl = EnumConstDecl; 3194 3195 if (Tok.is(tok::identifier)) { 3196 // We're missing a comma between enumerators. 3197 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 3198 Diag(Loc, diag::err_enumerator_list_missing_comma) 3199 << FixItHint::CreateInsertion(Loc, ", "); 3200 continue; 3201 } 3202 3203 if (Tok.isNot(tok::comma)) 3204 break; 3205 SourceLocation CommaLoc = ConsumeToken(); 3206 3207 if (Tok.isNot(tok::identifier)) { 3208 if (!getLang().C99 && !getLang().CPlusPlus0x) 3209 Diag(CommaLoc, diag::ext_enumerator_list_comma) 3210 << getLang().CPlusPlus 3211 << FixItHint::CreateRemoval(CommaLoc); 3212 else if (getLang().CPlusPlus0x) 3213 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) 3214 << FixItHint::CreateRemoval(CommaLoc); 3215 } 3216 } 3217 3218 // Eat the }. 3219 T.consumeClose(); 3220 3221 // If attributes exist after the identifier list, parse them. 3222 ParsedAttributes attrs(AttrFactory); 3223 MaybeParseGNUAttributes(attrs); 3224 3225 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(), 3226 EnumDecl, EnumConstantDecls.data(), 3227 EnumConstantDecls.size(), getCurScope(), 3228 attrs.getList()); 3229 3230 EnumScope.Exit(); 3231 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, 3232 T.getCloseLocation()); 3233} 3234 3235/// isTypeSpecifierQualifier - Return true if the current token could be the 3236/// start of a type-qualifier-list. 3237bool Parser::isTypeQualifier() const { 3238 switch (Tok.getKind()) { 3239 default: return false; 3240 3241 // type-qualifier only in OpenCL 3242 case tok::kw_private: 3243 return getLang().OpenCL; 3244 3245 // type-qualifier 3246 case tok::kw_const: 3247 case tok::kw_volatile: 3248 case tok::kw_restrict: 3249 case tok::kw___private: 3250 case tok::kw___local: 3251 case tok::kw___global: 3252 case tok::kw___constant: 3253 case tok::kw___read_only: 3254 case tok::kw___read_write: 3255 case tok::kw___write_only: 3256 return true; 3257 } 3258} 3259 3260/// isKnownToBeTypeSpecifier - Return true if we know that the specified token 3261/// is definitely a type-specifier. Return false if it isn't part of a type 3262/// specifier or if we're not sure. 3263bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 3264 switch (Tok.getKind()) { 3265 default: return false; 3266 // type-specifiers 3267 case tok::kw_short: 3268 case tok::kw_long: 3269 case tok::kw___int64: 3270 case tok::kw_signed: 3271 case tok::kw_unsigned: 3272 case tok::kw__Complex: 3273 case tok::kw__Imaginary: 3274 case tok::kw_void: 3275 case tok::kw_char: 3276 case tok::kw_wchar_t: 3277 case tok::kw_char16_t: 3278 case tok::kw_char32_t: 3279 case tok::kw_int: 3280 case tok::kw_half: 3281 case tok::kw_float: 3282 case tok::kw_double: 3283 case tok::kw_bool: 3284 case tok::kw__Bool: 3285 case tok::kw__Decimal32: 3286 case tok::kw__Decimal64: 3287 case tok::kw__Decimal128: 3288 case tok::kw___vector: 3289 3290 // struct-or-union-specifier (C99) or class-specifier (C++) 3291 case tok::kw_class: 3292 case tok::kw_struct: 3293 case tok::kw_union: 3294 // enum-specifier 3295 case tok::kw_enum: 3296 3297 // typedef-name 3298 case tok::annot_typename: 3299 return true; 3300 } 3301} 3302 3303/// isTypeSpecifierQualifier - Return true if the current token could be the 3304/// start of a specifier-qualifier-list. 3305bool Parser::isTypeSpecifierQualifier() { 3306 switch (Tok.getKind()) { 3307 default: return false; 3308 3309 case tok::identifier: // foo::bar 3310 if (TryAltiVecVectorToken()) 3311 return true; 3312 // Fall through. 3313 case tok::kw_typename: // typename T::type 3314 // Annotate typenames and C++ scope specifiers. If we get one, just 3315 // recurse to handle whatever we get. 3316 if (TryAnnotateTypeOrScopeToken()) 3317 return true; 3318 if (Tok.is(tok::identifier)) 3319 return false; 3320 return isTypeSpecifierQualifier(); 3321 3322 case tok::coloncolon: // ::foo::bar 3323 if (NextToken().is(tok::kw_new) || // ::new 3324 NextToken().is(tok::kw_delete)) // ::delete 3325 return false; 3326 3327 if (TryAnnotateTypeOrScopeToken()) 3328 return true; 3329 return isTypeSpecifierQualifier(); 3330 3331 // GNU attributes support. 3332 case tok::kw___attribute: 3333 // GNU typeof support. 3334 case tok::kw_typeof: 3335 3336 // type-specifiers 3337 case tok::kw_short: 3338 case tok::kw_long: 3339 case tok::kw___int64: 3340 case tok::kw_signed: 3341 case tok::kw_unsigned: 3342 case tok::kw__Complex: 3343 case tok::kw__Imaginary: 3344 case tok::kw_void: 3345 case tok::kw_char: 3346 case tok::kw_wchar_t: 3347 case tok::kw_char16_t: 3348 case tok::kw_char32_t: 3349 case tok::kw_int: 3350 case tok::kw_half: 3351 case tok::kw_float: 3352 case tok::kw_double: 3353 case tok::kw_bool: 3354 case tok::kw__Bool: 3355 case tok::kw__Decimal32: 3356 case tok::kw__Decimal64: 3357 case tok::kw__Decimal128: 3358 case tok::kw___vector: 3359 3360 // struct-or-union-specifier (C99) or class-specifier (C++) 3361 case tok::kw_class: 3362 case tok::kw_struct: 3363 case tok::kw_union: 3364 // enum-specifier 3365 case tok::kw_enum: 3366 3367 // type-qualifier 3368 case tok::kw_const: 3369 case tok::kw_volatile: 3370 case tok::kw_restrict: 3371 3372 // typedef-name 3373 case tok::annot_typename: 3374 return true; 3375 3376 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 3377 case tok::less: 3378 return getLang().ObjC1; 3379 3380 case tok::kw___cdecl: 3381 case tok::kw___stdcall: 3382 case tok::kw___fastcall: 3383 case tok::kw___thiscall: 3384 case tok::kw___w64: 3385 case tok::kw___ptr64: 3386 case tok::kw___ptr32: 3387 case tok::kw___pascal: 3388 case tok::kw___unaligned: 3389 3390 case tok::kw___private: 3391 case tok::kw___local: 3392 case tok::kw___global: 3393 case tok::kw___constant: 3394 case tok::kw___read_only: 3395 case tok::kw___read_write: 3396 case tok::kw___write_only: 3397 3398 return true; 3399 3400 case tok::kw_private: 3401 return getLang().OpenCL; 3402 3403 // C11 _Atomic() 3404 case tok::kw__Atomic: 3405 return true; 3406 } 3407} 3408 3409/// isDeclarationSpecifier() - Return true if the current token is part of a 3410/// declaration specifier. 3411/// 3412/// \param DisambiguatingWithExpression True to indicate that the purpose of 3413/// this check is to disambiguate between an expression and a declaration. 3414bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 3415 switch (Tok.getKind()) { 3416 default: return false; 3417 3418 case tok::kw_private: 3419 return getLang().OpenCL; 3420 3421 case tok::identifier: // foo::bar 3422 // Unfortunate hack to support "Class.factoryMethod" notation. 3423 if (getLang().ObjC1 && NextToken().is(tok::period)) 3424 return false; 3425 if (TryAltiVecVectorToken()) 3426 return true; 3427 // Fall through. 3428 case tok::kw_decltype: // decltype(T())::type 3429 case tok::kw_typename: // typename T::type 3430 // Annotate typenames and C++ scope specifiers. If we get one, just 3431 // recurse to handle whatever we get. 3432 if (TryAnnotateTypeOrScopeToken()) 3433 return true; 3434 if (Tok.is(tok::identifier)) 3435 return false; 3436 3437 // If we're in Objective-C and we have an Objective-C class type followed 3438 // by an identifier and then either ':' or ']', in a place where an 3439 // expression is permitted, then this is probably a class message send 3440 // missing the initial '['. In this case, we won't consider this to be 3441 // the start of a declaration. 3442 if (DisambiguatingWithExpression && 3443 isStartOfObjCClassMessageMissingOpenBracket()) 3444 return false; 3445 3446 return isDeclarationSpecifier(); 3447 3448 case tok::coloncolon: // ::foo::bar 3449 if (NextToken().is(tok::kw_new) || // ::new 3450 NextToken().is(tok::kw_delete)) // ::delete 3451 return false; 3452 3453 // Annotate typenames and C++ scope specifiers. If we get one, just 3454 // recurse to handle whatever we get. 3455 if (TryAnnotateTypeOrScopeToken()) 3456 return true; 3457 return isDeclarationSpecifier(); 3458 3459 // storage-class-specifier 3460 case tok::kw_typedef: 3461 case tok::kw_extern: 3462 case tok::kw___private_extern__: 3463 case tok::kw_static: 3464 case tok::kw_auto: 3465 case tok::kw_register: 3466 case tok::kw___thread: 3467 3468 // Modules 3469 case tok::kw___module_private__: 3470 3471 // type-specifiers 3472 case tok::kw_short: 3473 case tok::kw_long: 3474 case tok::kw___int64: 3475 case tok::kw_signed: 3476 case tok::kw_unsigned: 3477 case tok::kw__Complex: 3478 case tok::kw__Imaginary: 3479 case tok::kw_void: 3480 case tok::kw_char: 3481 case tok::kw_wchar_t: 3482 case tok::kw_char16_t: 3483 case tok::kw_char32_t: 3484 3485 case tok::kw_int: 3486 case tok::kw_half: 3487 case tok::kw_float: 3488 case tok::kw_double: 3489 case tok::kw_bool: 3490 case tok::kw__Bool: 3491 case tok::kw__Decimal32: 3492 case tok::kw__Decimal64: 3493 case tok::kw__Decimal128: 3494 case tok::kw___vector: 3495 3496 // struct-or-union-specifier (C99) or class-specifier (C++) 3497 case tok::kw_class: 3498 case tok::kw_struct: 3499 case tok::kw_union: 3500 // enum-specifier 3501 case tok::kw_enum: 3502 3503 // type-qualifier 3504 case tok::kw_const: 3505 case tok::kw_volatile: 3506 case tok::kw_restrict: 3507 3508 // function-specifier 3509 case tok::kw_inline: 3510 case tok::kw_virtual: 3511 case tok::kw_explicit: 3512 3513 // static_assert-declaration 3514 case tok::kw__Static_assert: 3515 3516 // GNU typeof support. 3517 case tok::kw_typeof: 3518 3519 // GNU attributes. 3520 case tok::kw___attribute: 3521 return true; 3522 3523 // C++0x decltype. 3524 case tok::annot_decltype: 3525 return true; 3526 3527 // C11 _Atomic() 3528 case tok::kw__Atomic: 3529 return true; 3530 3531 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 3532 case tok::less: 3533 return getLang().ObjC1; 3534 3535 // typedef-name 3536 case tok::annot_typename: 3537 return !DisambiguatingWithExpression || 3538 !isStartOfObjCClassMessageMissingOpenBracket(); 3539 3540 case tok::kw___declspec: 3541 case tok::kw___cdecl: 3542 case tok::kw___stdcall: 3543 case tok::kw___fastcall: 3544 case tok::kw___thiscall: 3545 case tok::kw___w64: 3546 case tok::kw___ptr64: 3547 case tok::kw___ptr32: 3548 case tok::kw___forceinline: 3549 case tok::kw___pascal: 3550 case tok::kw___unaligned: 3551 3552 case tok::kw___private: 3553 case tok::kw___local: 3554 case tok::kw___global: 3555 case tok::kw___constant: 3556 case tok::kw___read_only: 3557 case tok::kw___read_write: 3558 case tok::kw___write_only: 3559 3560 return true; 3561 } 3562} 3563 3564bool Parser::isConstructorDeclarator() { 3565 TentativeParsingAction TPA(*this); 3566 3567 // Parse the C++ scope specifier. 3568 CXXScopeSpec SS; 3569 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 3570 /*EnteringContext=*/true)) { 3571 TPA.Revert(); 3572 return false; 3573 } 3574 3575 // Parse the constructor name. 3576 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 3577 // We already know that we have a constructor name; just consume 3578 // the token. 3579 ConsumeToken(); 3580 } else { 3581 TPA.Revert(); 3582 return false; 3583 } 3584 3585 // Current class name must be followed by a left parentheses. 3586 if (Tok.isNot(tok::l_paren)) { 3587 TPA.Revert(); 3588 return false; 3589 } 3590 ConsumeParen(); 3591 3592 // A right parentheses or ellipsis signals that we have a constructor. 3593 if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) { 3594 TPA.Revert(); 3595 return true; 3596 } 3597 3598 // If we need to, enter the specified scope. 3599 DeclaratorScopeObj DeclScopeObj(*this, SS); 3600 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 3601 DeclScopeObj.EnterDeclaratorScope(); 3602 3603 // Optionally skip Microsoft attributes. 3604 ParsedAttributes Attrs(AttrFactory); 3605 MaybeParseMicrosoftAttributes(Attrs); 3606 3607 // Check whether the next token(s) are part of a declaration 3608 // specifier, in which case we have the start of a parameter and, 3609 // therefore, we know that this is a constructor. 3610 bool IsConstructor = isDeclarationSpecifier(); 3611 TPA.Revert(); 3612 return IsConstructor; 3613} 3614 3615/// ParseTypeQualifierListOpt 3616/// type-qualifier-list: [C99 6.7.5] 3617/// type-qualifier 3618/// [vendor] attributes 3619/// [ only if VendorAttributesAllowed=true ] 3620/// type-qualifier-list type-qualifier 3621/// [vendor] type-qualifier-list attributes 3622/// [ only if VendorAttributesAllowed=true ] 3623/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 3624/// [ only if CXX0XAttributesAllowed=true ] 3625/// Note: vendor can be GNU, MS, etc. 3626/// 3627void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, 3628 bool VendorAttributesAllowed, 3629 bool CXX0XAttributesAllowed) { 3630 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 3631 SourceLocation Loc = Tok.getLocation(); 3632 ParsedAttributesWithRange attrs(AttrFactory); 3633 ParseCXX0XAttributes(attrs); 3634 if (CXX0XAttributesAllowed) 3635 DS.takeAttributesFrom(attrs); 3636 else 3637 Diag(Loc, diag::err_attributes_not_allowed); 3638 } 3639 3640 SourceLocation EndLoc; 3641 3642 while (1) { 3643 bool isInvalid = false; 3644 const char *PrevSpec = 0; 3645 unsigned DiagID = 0; 3646 SourceLocation Loc = Tok.getLocation(); 3647 3648 switch (Tok.getKind()) { 3649 case tok::code_completion: 3650 Actions.CodeCompleteTypeQualifiers(DS); 3651 return cutOffParsing(); 3652 3653 case tok::kw_const: 3654 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 3655 getLang()); 3656 break; 3657 case tok::kw_volatile: 3658 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 3659 getLang()); 3660 break; 3661 case tok::kw_restrict: 3662 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 3663 getLang()); 3664 break; 3665 3666 // OpenCL qualifiers: 3667 case tok::kw_private: 3668 if (!getLang().OpenCL) 3669 goto DoneWithTypeQuals; 3670 case tok::kw___private: 3671 case tok::kw___global: 3672 case tok::kw___local: 3673 case tok::kw___constant: 3674 case tok::kw___read_only: 3675 case tok::kw___write_only: 3676 case tok::kw___read_write: 3677 ParseOpenCLQualifiers(DS); 3678 break; 3679 3680 case tok::kw___w64: 3681 case tok::kw___ptr64: 3682 case tok::kw___ptr32: 3683 case tok::kw___cdecl: 3684 case tok::kw___stdcall: 3685 case tok::kw___fastcall: 3686 case tok::kw___thiscall: 3687 case tok::kw___unaligned: 3688 if (VendorAttributesAllowed) { 3689 ParseMicrosoftTypeAttributes(DS.getAttributes()); 3690 continue; 3691 } 3692 goto DoneWithTypeQuals; 3693 case tok::kw___pascal: 3694 if (VendorAttributesAllowed) { 3695 ParseBorlandTypeAttributes(DS.getAttributes()); 3696 continue; 3697 } 3698 goto DoneWithTypeQuals; 3699 case tok::kw___attribute: 3700 if (VendorAttributesAllowed) { 3701 ParseGNUAttributes(DS.getAttributes()); 3702 continue; // do *not* consume the next token! 3703 } 3704 // otherwise, FALL THROUGH! 3705 default: 3706 DoneWithTypeQuals: 3707 // If this is not a type-qualifier token, we're done reading type 3708 // qualifiers. First verify that DeclSpec's are consistent. 3709 DS.Finish(Diags, PP); 3710 if (EndLoc.isValid()) 3711 DS.SetRangeEnd(EndLoc); 3712 return; 3713 } 3714 3715 // If the specifier combination wasn't legal, issue a diagnostic. 3716 if (isInvalid) { 3717 assert(PrevSpec && "Method did not return previous specifier!"); 3718 Diag(Tok, DiagID) << PrevSpec; 3719 } 3720 EndLoc = ConsumeToken(); 3721 } 3722} 3723 3724 3725/// ParseDeclarator - Parse and verify a newly-initialized declarator. 3726/// 3727void Parser::ParseDeclarator(Declarator &D) { 3728 /// This implements the 'declarator' production in the C grammar, then checks 3729 /// for well-formedness and issues diagnostics. 3730 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 3731} 3732 3733/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 3734/// is parsed by the function passed to it. Pass null, and the direct-declarator 3735/// isn't parsed at all, making this function effectively parse the C++ 3736/// ptr-operator production. 3737/// 3738/// If the grammar of this construct is extended, matching changes must also be 3739/// made to TryParseDeclarator and MightBeDeclarator. 3740/// 3741/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 3742/// [C] pointer[opt] direct-declarator 3743/// [C++] direct-declarator 3744/// [C++] ptr-operator declarator 3745/// 3746/// pointer: [C99 6.7.5] 3747/// '*' type-qualifier-list[opt] 3748/// '*' type-qualifier-list[opt] pointer 3749/// 3750/// ptr-operator: 3751/// '*' cv-qualifier-seq[opt] 3752/// '&' 3753/// [C++0x] '&&' 3754/// [GNU] '&' restrict[opt] attributes[opt] 3755/// [GNU?] '&&' restrict[opt] attributes[opt] 3756/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 3757void Parser::ParseDeclaratorInternal(Declarator &D, 3758 DirectDeclParseFunction DirectDeclParser) { 3759 if (Diags.hasAllExtensionsSilenced()) 3760 D.setExtension(); 3761 3762 // C++ member pointers start with a '::' or a nested-name. 3763 // Member pointers get special handling, since there's no place for the 3764 // scope spec in the generic path below. 3765 if (getLang().CPlusPlus && 3766 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 3767 Tok.is(tok::annot_cxxscope))) { 3768 bool EnteringContext = D.getContext() == Declarator::FileContext || 3769 D.getContext() == Declarator::MemberContext; 3770 CXXScopeSpec SS; 3771 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext); 3772 3773 if (SS.isNotEmpty()) { 3774 if (Tok.isNot(tok::star)) { 3775 // The scope spec really belongs to the direct-declarator. 3776 D.getCXXScopeSpec() = SS; 3777 if (DirectDeclParser) 3778 (this->*DirectDeclParser)(D); 3779 return; 3780 } 3781 3782 SourceLocation Loc = ConsumeToken(); 3783 D.SetRangeEnd(Loc); 3784 DeclSpec DS(AttrFactory); 3785 ParseTypeQualifierListOpt(DS); 3786 D.ExtendWithDeclSpec(DS); 3787 3788 // Recurse to parse whatever is left. 3789 ParseDeclaratorInternal(D, DirectDeclParser); 3790 3791 // Sema will have to catch (syntactically invalid) pointers into global 3792 // scope. It has to catch pointers into namespace scope anyway. 3793 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 3794 Loc), 3795 DS.getAttributes(), 3796 /* Don't replace range end. */SourceLocation()); 3797 return; 3798 } 3799 } 3800 3801 tok::TokenKind Kind = Tok.getKind(); 3802 // Not a pointer, C++ reference, or block. 3803 if (Kind != tok::star && Kind != tok::caret && 3804 (Kind != tok::amp || !getLang().CPlusPlus) && 3805 // We parse rvalue refs in C++03, because otherwise the errors are scary. 3806 (Kind != tok::ampamp || !getLang().CPlusPlus)) { 3807 if (DirectDeclParser) 3808 (this->*DirectDeclParser)(D); 3809 return; 3810 } 3811 3812 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 3813 // '&&' -> rvalue reference 3814 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 3815 D.SetRangeEnd(Loc); 3816 3817 if (Kind == tok::star || Kind == tok::caret) { 3818 // Is a pointer. 3819 DeclSpec DS(AttrFactory); 3820 3821 ParseTypeQualifierListOpt(DS); 3822 D.ExtendWithDeclSpec(DS); 3823 3824 // Recursively parse the declarator. 3825 ParseDeclaratorInternal(D, DirectDeclParser); 3826 if (Kind == tok::star) 3827 // Remember that we parsed a pointer type, and remember the type-quals. 3828 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 3829 DS.getConstSpecLoc(), 3830 DS.getVolatileSpecLoc(), 3831 DS.getRestrictSpecLoc()), 3832 DS.getAttributes(), 3833 SourceLocation()); 3834 else 3835 // Remember that we parsed a Block type, and remember the type-quals. 3836 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 3837 Loc), 3838 DS.getAttributes(), 3839 SourceLocation()); 3840 } else { 3841 // Is a reference 3842 DeclSpec DS(AttrFactory); 3843 3844 // Complain about rvalue references in C++03, but then go on and build 3845 // the declarator. 3846 if (Kind == tok::ampamp) 3847 Diag(Loc, getLang().CPlusPlus0x ? 3848 diag::warn_cxx98_compat_rvalue_reference : 3849 diag::ext_rvalue_reference); 3850 3851 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 3852 // cv-qualifiers are introduced through the use of a typedef or of a 3853 // template type argument, in which case the cv-qualifiers are ignored. 3854 // 3855 // [GNU] Retricted references are allowed. 3856 // [GNU] Attributes on references are allowed. 3857 // [C++0x] Attributes on references are not allowed. 3858 ParseTypeQualifierListOpt(DS, true, false); 3859 D.ExtendWithDeclSpec(DS); 3860 3861 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 3862 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3863 Diag(DS.getConstSpecLoc(), 3864 diag::err_invalid_reference_qualifier_application) << "const"; 3865 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3866 Diag(DS.getVolatileSpecLoc(), 3867 diag::err_invalid_reference_qualifier_application) << "volatile"; 3868 } 3869 3870 // Recursively parse the declarator. 3871 ParseDeclaratorInternal(D, DirectDeclParser); 3872 3873 if (D.getNumTypeObjects() > 0) { 3874 // C++ [dcl.ref]p4: There shall be no references to references. 3875 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 3876 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 3877 if (const IdentifierInfo *II = D.getIdentifier()) 3878 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 3879 << II; 3880 else 3881 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 3882 << "type name"; 3883 3884 // Once we've complained about the reference-to-reference, we 3885 // can go ahead and build the (technically ill-formed) 3886 // declarator: reference collapsing will take care of it. 3887 } 3888 } 3889 3890 // Remember that we parsed a reference type. It doesn't have type-quals. 3891 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 3892 Kind == tok::amp), 3893 DS.getAttributes(), 3894 SourceLocation()); 3895 } 3896} 3897 3898/// ParseDirectDeclarator 3899/// direct-declarator: [C99 6.7.5] 3900/// [C99] identifier 3901/// '(' declarator ')' 3902/// [GNU] '(' attributes declarator ')' 3903/// [C90] direct-declarator '[' constant-expression[opt] ']' 3904/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 3905/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 3906/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 3907/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 3908/// direct-declarator '(' parameter-type-list ')' 3909/// direct-declarator '(' identifier-list[opt] ')' 3910/// [GNU] direct-declarator '(' parameter-forward-declarations 3911/// parameter-type-list[opt] ')' 3912/// [C++] direct-declarator '(' parameter-declaration-clause ')' 3913/// cv-qualifier-seq[opt] exception-specification[opt] 3914/// [C++] declarator-id 3915/// 3916/// declarator-id: [C++ 8] 3917/// '...'[opt] id-expression 3918/// '::'[opt] nested-name-specifier[opt] type-name 3919/// 3920/// id-expression: [C++ 5.1] 3921/// unqualified-id 3922/// qualified-id 3923/// 3924/// unqualified-id: [C++ 5.1] 3925/// identifier 3926/// operator-function-id 3927/// conversion-function-id 3928/// '~' class-name 3929/// template-id 3930/// 3931void Parser::ParseDirectDeclarator(Declarator &D) { 3932 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 3933 3934 if (getLang().CPlusPlus && D.mayHaveIdentifier()) { 3935 // ParseDeclaratorInternal might already have parsed the scope. 3936 if (D.getCXXScopeSpec().isEmpty()) { 3937 bool EnteringContext = D.getContext() == Declarator::FileContext || 3938 D.getContext() == Declarator::MemberContext; 3939 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), 3940 EnteringContext); 3941 } 3942 3943 if (D.getCXXScopeSpec().isValid()) { 3944 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 3945 // Change the declaration context for name lookup, until this function 3946 // is exited (and the declarator has been parsed). 3947 DeclScopeObj.EnterDeclaratorScope(); 3948 } 3949 3950 // C++0x [dcl.fct]p14: 3951 // There is a syntactic ambiguity when an ellipsis occurs at the end 3952 // of a parameter-declaration-clause without a preceding comma. In 3953 // this case, the ellipsis is parsed as part of the 3954 // abstract-declarator if the type of the parameter names a template 3955 // parameter pack that has not been expanded; otherwise, it is parsed 3956 // as part of the parameter-declaration-clause. 3957 if (Tok.is(tok::ellipsis) && 3958 !((D.getContext() == Declarator::PrototypeContext || 3959 D.getContext() == Declarator::BlockLiteralContext) && 3960 NextToken().is(tok::r_paren) && 3961 !Actions.containsUnexpandedParameterPacks(D))) 3962 D.setEllipsisLoc(ConsumeToken()); 3963 3964 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 3965 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 3966 // We found something that indicates the start of an unqualified-id. 3967 // Parse that unqualified-id. 3968 bool AllowConstructorName; 3969 if (D.getDeclSpec().hasTypeSpecifier()) 3970 AllowConstructorName = false; 3971 else if (D.getCXXScopeSpec().isSet()) 3972 AllowConstructorName = 3973 (D.getContext() == Declarator::FileContext || 3974 (D.getContext() == Declarator::MemberContext && 3975 D.getDeclSpec().isFriendSpecified())); 3976 else 3977 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 3978 3979 SourceLocation TemplateKWLoc; 3980 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 3981 /*EnteringContext=*/true, 3982 /*AllowDestructorName=*/true, 3983 AllowConstructorName, 3984 ParsedType(), 3985 TemplateKWLoc, 3986 D.getName()) || 3987 // Once we're past the identifier, if the scope was bad, mark the 3988 // whole declarator bad. 3989 D.getCXXScopeSpec().isInvalid()) { 3990 D.SetIdentifier(0, Tok.getLocation()); 3991 D.setInvalidType(true); 3992 } else { 3993 // Parsed the unqualified-id; update range information and move along. 3994 if (D.getSourceRange().getBegin().isInvalid()) 3995 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 3996 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 3997 } 3998 goto PastIdentifier; 3999 } 4000 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 4001 assert(!getLang().CPlusPlus && 4002 "There's a C++-specific check for tok::identifier above"); 4003 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 4004 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 4005 ConsumeToken(); 4006 goto PastIdentifier; 4007 } 4008 4009 if (Tok.is(tok::l_paren)) { 4010 // direct-declarator: '(' declarator ')' 4011 // direct-declarator: '(' attributes declarator ')' 4012 // Example: 'char (*X)' or 'int (*XX)(void)' 4013 ParseParenDeclarator(D); 4014 4015 // If the declarator was parenthesized, we entered the declarator 4016 // scope when parsing the parenthesized declarator, then exited 4017 // the scope already. Re-enter the scope, if we need to. 4018 if (D.getCXXScopeSpec().isSet()) { 4019 // If there was an error parsing parenthesized declarator, declarator 4020 // scope may have been enterred before. Don't do it again. 4021 if (!D.isInvalidType() && 4022 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 4023 // Change the declaration context for name lookup, until this function 4024 // is exited (and the declarator has been parsed). 4025 DeclScopeObj.EnterDeclaratorScope(); 4026 } 4027 } else if (D.mayOmitIdentifier()) { 4028 // This could be something simple like "int" (in which case the declarator 4029 // portion is empty), if an abstract-declarator is allowed. 4030 D.SetIdentifier(0, Tok.getLocation()); 4031 } else { 4032 if (D.getContext() == Declarator::MemberContext) 4033 Diag(Tok, diag::err_expected_member_name_or_semi) 4034 << D.getDeclSpec().getSourceRange(); 4035 else if (getLang().CPlusPlus) 4036 Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus; 4037 else 4038 Diag(Tok, diag::err_expected_ident_lparen); 4039 D.SetIdentifier(0, Tok.getLocation()); 4040 D.setInvalidType(true); 4041 } 4042 4043 PastIdentifier: 4044 assert(D.isPastIdentifier() && 4045 "Haven't past the location of the identifier yet?"); 4046 4047 // Don't parse attributes unless we have an identifier. 4048 if (D.getIdentifier()) 4049 MaybeParseCXX0XAttributes(D); 4050 4051 while (1) { 4052 if (Tok.is(tok::l_paren)) { 4053 // Enter function-declaration scope, limiting any declarators to the 4054 // function prototype scope, including parameter declarators. 4055 ParseScope PrototypeScope(this, 4056 Scope::FunctionPrototypeScope|Scope::DeclScope); 4057 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 4058 // In such a case, check if we actually have a function declarator; if it 4059 // is not, the declarator has been fully parsed. 4060 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 4061 // When not in file scope, warn for ambiguous function declarators, just 4062 // in case the author intended it as a variable definition. 4063 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 4064 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 4065 break; 4066 } 4067 ParsedAttributes attrs(AttrFactory); 4068 BalancedDelimiterTracker T(*this, tok::l_paren); 4069 T.consumeOpen(); 4070 ParseFunctionDeclarator(D, attrs, T); 4071 PrototypeScope.Exit(); 4072 } else if (Tok.is(tok::l_square)) { 4073 ParseBracketDeclarator(D); 4074 } else { 4075 break; 4076 } 4077 } 4078} 4079 4080/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 4081/// only called before the identifier, so these are most likely just grouping 4082/// parens for precedence. If we find that these are actually function 4083/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 4084/// 4085/// direct-declarator: 4086/// '(' declarator ')' 4087/// [GNU] '(' attributes declarator ')' 4088/// direct-declarator '(' parameter-type-list ')' 4089/// direct-declarator '(' identifier-list[opt] ')' 4090/// [GNU] direct-declarator '(' parameter-forward-declarations 4091/// parameter-type-list[opt] ')' 4092/// 4093void Parser::ParseParenDeclarator(Declarator &D) { 4094 BalancedDelimiterTracker T(*this, tok::l_paren); 4095 T.consumeOpen(); 4096 4097 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 4098 4099 // Eat any attributes before we look at whether this is a grouping or function 4100 // declarator paren. If this is a grouping paren, the attribute applies to 4101 // the type being built up, for example: 4102 // int (__attribute__(()) *x)(long y) 4103 // If this ends up not being a grouping paren, the attribute applies to the 4104 // first argument, for example: 4105 // int (__attribute__(()) int x) 4106 // In either case, we need to eat any attributes to be able to determine what 4107 // sort of paren this is. 4108 // 4109 ParsedAttributes attrs(AttrFactory); 4110 bool RequiresArg = false; 4111 if (Tok.is(tok::kw___attribute)) { 4112 ParseGNUAttributes(attrs); 4113 4114 // We require that the argument list (if this is a non-grouping paren) be 4115 // present even if the attribute list was empty. 4116 RequiresArg = true; 4117 } 4118 // Eat any Microsoft extensions. 4119 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 4120 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) || 4121 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) || 4122 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) { 4123 ParseMicrosoftTypeAttributes(attrs); 4124 } 4125 // Eat any Borland extensions. 4126 if (Tok.is(tok::kw___pascal)) 4127 ParseBorlandTypeAttributes(attrs); 4128 4129 // If we haven't past the identifier yet (or where the identifier would be 4130 // stored, if this is an abstract declarator), then this is probably just 4131 // grouping parens. However, if this could be an abstract-declarator, then 4132 // this could also be the start of function arguments (consider 'void()'). 4133 bool isGrouping; 4134 4135 if (!D.mayOmitIdentifier()) { 4136 // If this can't be an abstract-declarator, this *must* be a grouping 4137 // paren, because we haven't seen the identifier yet. 4138 isGrouping = true; 4139 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 4140 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...) 4141 isDeclarationSpecifier()) { // 'int(int)' is a function. 4142 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 4143 // considered to be a type, not a K&R identifier-list. 4144 isGrouping = false; 4145 } else { 4146 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 4147 isGrouping = true; 4148 } 4149 4150 // If this is a grouping paren, handle: 4151 // direct-declarator: '(' declarator ')' 4152 // direct-declarator: '(' attributes declarator ')' 4153 if (isGrouping) { 4154 bool hadGroupingParens = D.hasGroupingParens(); 4155 D.setGroupingParens(true); 4156 4157 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 4158 // Match the ')'. 4159 T.consumeClose(); 4160 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(), 4161 T.getCloseLocation()), 4162 attrs, T.getCloseLocation()); 4163 4164 D.setGroupingParens(hadGroupingParens); 4165 return; 4166 } 4167 4168 // Okay, if this wasn't a grouping paren, it must be the start of a function 4169 // argument list. Recognize that this declarator will never have an 4170 // identifier (and remember where it would have been), then call into 4171 // ParseFunctionDeclarator to handle of argument list. 4172 D.SetIdentifier(0, Tok.getLocation()); 4173 4174 // Enter function-declaration scope, limiting any declarators to the 4175 // function prototype scope, including parameter declarators. 4176 ParseScope PrototypeScope(this, 4177 Scope::FunctionPrototypeScope|Scope::DeclScope); 4178 ParseFunctionDeclarator(D, attrs, T, RequiresArg); 4179 PrototypeScope.Exit(); 4180} 4181 4182/// ParseFunctionDeclarator - We are after the identifier and have parsed the 4183/// declarator D up to a paren, which indicates that we are parsing function 4184/// arguments. 4185/// 4186/// If attrs is non-null, then the caller parsed those arguments immediately 4187/// after the open paren - they should be considered to be the first argument of 4188/// a parameter. If RequiresArg is true, then the first argument of the 4189/// function is required to be present and required to not be an identifier 4190/// list. 4191/// 4192/// For C++, after the parameter-list, it also parses cv-qualifier-seq[opt], 4193/// (C++0x) ref-qualifier[opt], exception-specification[opt], and 4194/// (C++0x) trailing-return-type[opt]. 4195/// 4196/// [C++0x] exception-specification: 4197/// dynamic-exception-specification 4198/// noexcept-specification 4199/// 4200void Parser::ParseFunctionDeclarator(Declarator &D, 4201 ParsedAttributes &attrs, 4202 BalancedDelimiterTracker &Tracker, 4203 bool RequiresArg) { 4204 assert(getCurScope()->isFunctionPrototypeScope() && 4205 "Should call from a Function scope"); 4206 // lparen is already consumed! 4207 assert(D.isPastIdentifier() && "Should not call before identifier!"); 4208 4209 // This should be true when the function has typed arguments. 4210 // Otherwise, it is treated as a K&R-style function. 4211 bool HasProto = false; 4212 // Build up an array of information about the parsed arguments. 4213 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 4214 // Remember where we see an ellipsis, if any. 4215 SourceLocation EllipsisLoc; 4216 4217 DeclSpec DS(AttrFactory); 4218 bool RefQualifierIsLValueRef = true; 4219 SourceLocation RefQualifierLoc; 4220 SourceLocation ConstQualifierLoc; 4221 SourceLocation VolatileQualifierLoc; 4222 ExceptionSpecificationType ESpecType = EST_None; 4223 SourceRange ESpecRange; 4224 SmallVector<ParsedType, 2> DynamicExceptions; 4225 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4226 ExprResult NoexceptExpr; 4227 ParsedType TrailingReturnType; 4228 4229 SourceLocation EndLoc; 4230 if (isFunctionDeclaratorIdentifierList()) { 4231 if (RequiresArg) 4232 Diag(Tok, diag::err_argument_required_after_attribute); 4233 4234 ParseFunctionDeclaratorIdentifierList(D, ParamInfo); 4235 4236 Tracker.consumeClose(); 4237 EndLoc = Tracker.getCloseLocation(); 4238 } else { 4239 if (Tok.isNot(tok::r_paren)) 4240 ParseParameterDeclarationClause(D, attrs, ParamInfo, EllipsisLoc); 4241 else if (RequiresArg) 4242 Diag(Tok, diag::err_argument_required_after_attribute); 4243 4244 HasProto = ParamInfo.size() || getLang().CPlusPlus; 4245 4246 // If we have the closing ')', eat it. 4247 Tracker.consumeClose(); 4248 EndLoc = Tracker.getCloseLocation(); 4249 4250 if (getLang().CPlusPlus) { 4251 MaybeParseCXX0XAttributes(attrs); 4252 4253 // Parse cv-qualifier-seq[opt]. 4254 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 4255 if (!DS.getSourceRange().getEnd().isInvalid()) { 4256 EndLoc = DS.getSourceRange().getEnd(); 4257 ConstQualifierLoc = DS.getConstSpecLoc(); 4258 VolatileQualifierLoc = DS.getVolatileSpecLoc(); 4259 } 4260 4261 // Parse ref-qualifier[opt]. 4262 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 4263 Diag(Tok, getLang().CPlusPlus0x ? 4264 diag::warn_cxx98_compat_ref_qualifier : 4265 diag::ext_ref_qualifier); 4266 4267 RefQualifierIsLValueRef = Tok.is(tok::amp); 4268 RefQualifierLoc = ConsumeToken(); 4269 EndLoc = RefQualifierLoc; 4270 } 4271 4272 // Parse exception-specification[opt]. 4273 ESpecType = MaybeParseExceptionSpecification(ESpecRange, 4274 DynamicExceptions, 4275 DynamicExceptionRanges, 4276 NoexceptExpr); 4277 if (ESpecType != EST_None) 4278 EndLoc = ESpecRange.getEnd(); 4279 4280 // Parse trailing-return-type[opt]. 4281 if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) { 4282 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); 4283 SourceRange Range; 4284 TrailingReturnType = ParseTrailingReturnType(Range).get(); 4285 if (Range.getEnd().isValid()) 4286 EndLoc = Range.getEnd(); 4287 } 4288 } 4289 } 4290 4291 // Remember that we parsed a function type, and remember the attributes. 4292 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto, 4293 /*isVariadic=*/EllipsisLoc.isValid(), 4294 EllipsisLoc, 4295 ParamInfo.data(), ParamInfo.size(), 4296 DS.getTypeQualifiers(), 4297 RefQualifierIsLValueRef, 4298 RefQualifierLoc, ConstQualifierLoc, 4299 VolatileQualifierLoc, 4300 /*MutableLoc=*/SourceLocation(), 4301 ESpecType, ESpecRange.getBegin(), 4302 DynamicExceptions.data(), 4303 DynamicExceptionRanges.data(), 4304 DynamicExceptions.size(), 4305 NoexceptExpr.isUsable() ? 4306 NoexceptExpr.get() : 0, 4307 Tracker.getOpenLocation(), 4308 EndLoc, D, 4309 TrailingReturnType), 4310 attrs, EndLoc); 4311} 4312 4313/// isFunctionDeclaratorIdentifierList - This parameter list may have an 4314/// identifier list form for a K&R-style function: void foo(a,b,c) 4315/// 4316/// Note that identifier-lists are only allowed for normal declarators, not for 4317/// abstract-declarators. 4318bool Parser::isFunctionDeclaratorIdentifierList() { 4319 return !getLang().CPlusPlus 4320 && Tok.is(tok::identifier) 4321 && !TryAltiVecVectorToken() 4322 // K&R identifier lists can't have typedefs as identifiers, per C99 4323 // 6.7.5.3p11. 4324 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) 4325 // Identifier lists follow a really simple grammar: the identifiers can 4326 // be followed *only* by a ", identifier" or ")". However, K&R 4327 // identifier lists are really rare in the brave new modern world, and 4328 // it is very common for someone to typo a type in a non-K&R style 4329 // list. If we are presented with something like: "void foo(intptr x, 4330 // float y)", we don't want to start parsing the function declarator as 4331 // though it is a K&R style declarator just because intptr is an 4332 // invalid type. 4333 // 4334 // To handle this, we check to see if the token after the first 4335 // identifier is a "," or ")". Only then do we parse it as an 4336 // identifier list. 4337 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)); 4338} 4339 4340/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 4341/// we found a K&R-style identifier list instead of a typed parameter list. 4342/// 4343/// After returning, ParamInfo will hold the parsed parameters. 4344/// 4345/// identifier-list: [C99 6.7.5] 4346/// identifier 4347/// identifier-list ',' identifier 4348/// 4349void Parser::ParseFunctionDeclaratorIdentifierList( 4350 Declarator &D, 4351 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) { 4352 // If there was no identifier specified for the declarator, either we are in 4353 // an abstract-declarator, or we are in a parameter declarator which was found 4354 // to be abstract. In abstract-declarators, identifier lists are not valid: 4355 // diagnose this. 4356 if (!D.getIdentifier()) 4357 Diag(Tok, diag::ext_ident_list_in_param); 4358 4359 // Maintain an efficient lookup of params we have seen so far. 4360 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 4361 4362 while (1) { 4363 // If this isn't an identifier, report the error and skip until ')'. 4364 if (Tok.isNot(tok::identifier)) { 4365 Diag(Tok, diag::err_expected_ident); 4366 SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true); 4367 // Forget we parsed anything. 4368 ParamInfo.clear(); 4369 return; 4370 } 4371 4372 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 4373 4374 // Reject 'typedef int y; int test(x, y)', but continue parsing. 4375 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 4376 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 4377 4378 // Verify that the argument identifier has not already been mentioned. 4379 if (!ParamsSoFar.insert(ParmII)) { 4380 Diag(Tok, diag::err_param_redefinition) << ParmII; 4381 } else { 4382 // Remember this identifier in ParamInfo. 4383 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 4384 Tok.getLocation(), 4385 0)); 4386 } 4387 4388 // Eat the identifier. 4389 ConsumeToken(); 4390 4391 // The list continues if we see a comma. 4392 if (Tok.isNot(tok::comma)) 4393 break; 4394 ConsumeToken(); 4395 } 4396} 4397 4398/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list 4399/// after the opening parenthesis. This function will not parse a K&R-style 4400/// identifier list. 4401/// 4402/// D is the declarator being parsed. If attrs is non-null, then the caller 4403/// parsed those arguments immediately after the open paren - they should be 4404/// considered to be the first argument of a parameter. 4405/// 4406/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will 4407/// be the location of the ellipsis, if any was parsed. 4408/// 4409/// parameter-type-list: [C99 6.7.5] 4410/// parameter-list 4411/// parameter-list ',' '...' 4412/// [C++] parameter-list '...' 4413/// 4414/// parameter-list: [C99 6.7.5] 4415/// parameter-declaration 4416/// parameter-list ',' parameter-declaration 4417/// 4418/// parameter-declaration: [C99 6.7.5] 4419/// declaration-specifiers declarator 4420/// [C++] declaration-specifiers declarator '=' assignment-expression 4421/// [GNU] declaration-specifiers declarator attributes 4422/// declaration-specifiers abstract-declarator[opt] 4423/// [C++] declaration-specifiers abstract-declarator[opt] 4424/// '=' assignment-expression 4425/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 4426/// 4427void Parser::ParseParameterDeclarationClause( 4428 Declarator &D, 4429 ParsedAttributes &attrs, 4430 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo, 4431 SourceLocation &EllipsisLoc) { 4432 4433 while (1) { 4434 if (Tok.is(tok::ellipsis)) { 4435 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 4436 break; 4437 } 4438 4439 // Parse the declaration-specifiers. 4440 // Just use the ParsingDeclaration "scope" of the declarator. 4441 DeclSpec DS(AttrFactory); 4442 4443 // Skip any Microsoft attributes before a param. 4444 if (getLang().MicrosoftExt && Tok.is(tok::l_square)) 4445 ParseMicrosoftAttributes(DS.getAttributes()); 4446 4447 SourceLocation DSStart = Tok.getLocation(); 4448 4449 // If the caller parsed attributes for the first argument, add them now. 4450 // Take them so that we only apply the attributes to the first parameter. 4451 // FIXME: If we saw an ellipsis first, this code is not reached. Are the 4452 // attributes lost? Should they even be allowed? 4453 // FIXME: If we can leave the attributes in the token stream somehow, we can 4454 // get rid of a parameter (attrs) and this statement. It might be too much 4455 // hassle. 4456 DS.takeAttributesFrom(attrs); 4457 4458 ParseDeclarationSpecifiers(DS); 4459 4460 // Parse the declarator. This is "PrototypeContext", because we must 4461 // accept either 'declarator' or 'abstract-declarator' here. 4462 Declarator ParmDecl(DS, Declarator::PrototypeContext); 4463 ParseDeclarator(ParmDecl); 4464 4465 // Parse GNU attributes, if present. 4466 MaybeParseGNUAttributes(ParmDecl); 4467 4468 // Remember this parsed parameter in ParamInfo. 4469 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 4470 4471 // DefArgToks is used when the parsing of default arguments needs 4472 // to be delayed. 4473 CachedTokens *DefArgToks = 0; 4474 4475 // If no parameter was specified, verify that *something* was specified, 4476 // otherwise we have a missing type and identifier. 4477 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 4478 ParmDecl.getNumTypeObjects() == 0) { 4479 // Completely missing, emit error. 4480 Diag(DSStart, diag::err_missing_param); 4481 } else { 4482 // Otherwise, we have something. Add it and let semantic analysis try 4483 // to grok it and add the result to the ParamInfo we are building. 4484 4485 // Inform the actions module about the parameter declarator, so it gets 4486 // added to the current scope. 4487 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 4488 4489 // Parse the default argument, if any. We parse the default 4490 // arguments in all dialects; the semantic analysis in 4491 // ActOnParamDefaultArgument will reject the default argument in 4492 // C. 4493 if (Tok.is(tok::equal)) { 4494 SourceLocation EqualLoc = Tok.getLocation(); 4495 4496 // Parse the default argument 4497 if (D.getContext() == Declarator::MemberContext) { 4498 // If we're inside a class definition, cache the tokens 4499 // corresponding to the default argument. We'll actually parse 4500 // them when we see the end of the class definition. 4501 // FIXME: Templates will require something similar. 4502 // FIXME: Can we use a smart pointer for Toks? 4503 DefArgToks = new CachedTokens; 4504 4505 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 4506 /*StopAtSemi=*/true, 4507 /*ConsumeFinalToken=*/false)) { 4508 delete DefArgToks; 4509 DefArgToks = 0; 4510 Actions.ActOnParamDefaultArgumentError(Param); 4511 } else { 4512 // Mark the end of the default argument so that we know when to 4513 // stop when we parse it later on. 4514 Token DefArgEnd; 4515 DefArgEnd.startToken(); 4516 DefArgEnd.setKind(tok::cxx_defaultarg_end); 4517 DefArgEnd.setLocation(Tok.getLocation()); 4518 DefArgToks->push_back(DefArgEnd); 4519 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 4520 (*DefArgToks)[1].getLocation()); 4521 } 4522 } else { 4523 // Consume the '='. 4524 ConsumeToken(); 4525 4526 // The argument isn't actually potentially evaluated unless it is 4527 // used. 4528 EnterExpressionEvaluationContext Eval(Actions, 4529 Sema::PotentiallyEvaluatedIfUsed, 4530 Param); 4531 4532 ExprResult DefArgResult(ParseAssignmentExpression()); 4533 if (DefArgResult.isInvalid()) { 4534 Actions.ActOnParamDefaultArgumentError(Param); 4535 SkipUntil(tok::comma, tok::r_paren, true, true); 4536 } else { 4537 // Inform the actions module about the default argument 4538 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 4539 DefArgResult.take()); 4540 } 4541 } 4542 } 4543 4544 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 4545 ParmDecl.getIdentifierLoc(), Param, 4546 DefArgToks)); 4547 } 4548 4549 // If the next token is a comma, consume it and keep reading arguments. 4550 if (Tok.isNot(tok::comma)) { 4551 if (Tok.is(tok::ellipsis)) { 4552 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 4553 4554 if (!getLang().CPlusPlus) { 4555 // We have ellipsis without a preceding ',', which is ill-formed 4556 // in C. Complain and provide the fix. 4557 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 4558 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 4559 } 4560 } 4561 4562 break; 4563 } 4564 4565 // Consume the comma. 4566 ConsumeToken(); 4567 } 4568 4569} 4570 4571/// [C90] direct-declarator '[' constant-expression[opt] ']' 4572/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 4573/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 4574/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 4575/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 4576void Parser::ParseBracketDeclarator(Declarator &D) { 4577 BalancedDelimiterTracker T(*this, tok::l_square); 4578 T.consumeOpen(); 4579 4580 // C array syntax has many features, but by-far the most common is [] and [4]. 4581 // This code does a fast path to handle some of the most obvious cases. 4582 if (Tok.getKind() == tok::r_square) { 4583 T.consumeClose(); 4584 ParsedAttributes attrs(AttrFactory); 4585 MaybeParseCXX0XAttributes(attrs); 4586 4587 // Remember that we parsed the empty array type. 4588 ExprResult NumElements; 4589 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, 4590 T.getOpenLocation(), 4591 T.getCloseLocation()), 4592 attrs, T.getCloseLocation()); 4593 return; 4594 } else if (Tok.getKind() == tok::numeric_constant && 4595 GetLookAheadToken(1).is(tok::r_square)) { 4596 // [4] is very common. Parse the numeric constant expression. 4597 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok)); 4598 ConsumeToken(); 4599 4600 T.consumeClose(); 4601 ParsedAttributes attrs(AttrFactory); 4602 MaybeParseCXX0XAttributes(attrs); 4603 4604 // Remember that we parsed a array type, and remember its features. 4605 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, 4606 ExprRes.release(), 4607 T.getOpenLocation(), 4608 T.getCloseLocation()), 4609 attrs, T.getCloseLocation()); 4610 return; 4611 } 4612 4613 // If valid, this location is the position where we read the 'static' keyword. 4614 SourceLocation StaticLoc; 4615 if (Tok.is(tok::kw_static)) 4616 StaticLoc = ConsumeToken(); 4617 4618 // If there is a type-qualifier-list, read it now. 4619 // Type qualifiers in an array subscript are a C99 feature. 4620 DeclSpec DS(AttrFactory); 4621 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 4622 4623 // If we haven't already read 'static', check to see if there is one after the 4624 // type-qualifier-list. 4625 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 4626 StaticLoc = ConsumeToken(); 4627 4628 // Handle "direct-declarator [ type-qual-list[opt] * ]". 4629 bool isStar = false; 4630 ExprResult NumElements; 4631 4632 // Handle the case where we have '[*]' as the array size. However, a leading 4633 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 4634 // the the token after the star is a ']'. Since stars in arrays are 4635 // infrequent, use of lookahead is not costly here. 4636 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 4637 ConsumeToken(); // Eat the '*'. 4638 4639 if (StaticLoc.isValid()) { 4640 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 4641 StaticLoc = SourceLocation(); // Drop the static. 4642 } 4643 isStar = true; 4644 } else if (Tok.isNot(tok::r_square)) { 4645 // Note, in C89, this production uses the constant-expr production instead 4646 // of assignment-expr. The only difference is that assignment-expr allows 4647 // things like '=' and '*='. Sema rejects these in C89 mode because they 4648 // are not i-c-e's, so we don't need to distinguish between the two here. 4649 4650 // Parse the constant-expression or assignment-expression now (depending 4651 // on dialect). 4652 if (getLang().CPlusPlus) { 4653 NumElements = ParseConstantExpression(); 4654 } else { 4655 EnterExpressionEvaluationContext Unevaluated(Actions, 4656 Sema::ConstantEvaluated); 4657 NumElements = ParseAssignmentExpression(); 4658 } 4659 } 4660 4661 // If there was an error parsing the assignment-expression, recover. 4662 if (NumElements.isInvalid()) { 4663 D.setInvalidType(true); 4664 // If the expression was invalid, skip it. 4665 SkipUntil(tok::r_square); 4666 return; 4667 } 4668 4669 T.consumeClose(); 4670 4671 ParsedAttributes attrs(AttrFactory); 4672 MaybeParseCXX0XAttributes(attrs); 4673 4674 // Remember that we parsed a array type, and remember its features. 4675 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 4676 StaticLoc.isValid(), isStar, 4677 NumElements.release(), 4678 T.getOpenLocation(), 4679 T.getCloseLocation()), 4680 attrs, T.getCloseLocation()); 4681} 4682 4683/// [GNU] typeof-specifier: 4684/// typeof ( expressions ) 4685/// typeof ( type-name ) 4686/// [GNU/C++] typeof unary-expression 4687/// 4688void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 4689 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 4690 Token OpTok = Tok; 4691 SourceLocation StartLoc = ConsumeToken(); 4692 4693 const bool hasParens = Tok.is(tok::l_paren); 4694 4695 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 4696 4697 bool isCastExpr; 4698 ParsedType CastTy; 4699 SourceRange CastRange; 4700 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, 4701 CastTy, CastRange); 4702 if (hasParens) 4703 DS.setTypeofParensRange(CastRange); 4704 4705 if (CastRange.getEnd().isInvalid()) 4706 // FIXME: Not accurate, the range gets one token more than it should. 4707 DS.SetRangeEnd(Tok.getLocation()); 4708 else 4709 DS.SetRangeEnd(CastRange.getEnd()); 4710 4711 if (isCastExpr) { 4712 if (!CastTy) { 4713 DS.SetTypeSpecError(); 4714 return; 4715 } 4716 4717 const char *PrevSpec = 0; 4718 unsigned DiagID; 4719 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 4720 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 4721 DiagID, CastTy)) 4722 Diag(StartLoc, DiagID) << PrevSpec; 4723 return; 4724 } 4725 4726 // If we get here, the operand to the typeof was an expresion. 4727 if (Operand.isInvalid()) { 4728 DS.SetTypeSpecError(); 4729 return; 4730 } 4731 4732 // We might need to transform the operand if it is potentially evaluated. 4733 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); 4734 if (Operand.isInvalid()) { 4735 DS.SetTypeSpecError(); 4736 return; 4737 } 4738 4739 const char *PrevSpec = 0; 4740 unsigned DiagID; 4741 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 4742 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 4743 DiagID, Operand.get())) 4744 Diag(StartLoc, DiagID) << PrevSpec; 4745} 4746 4747/// [C11] atomic-specifier: 4748/// _Atomic ( type-name ) 4749/// 4750void Parser::ParseAtomicSpecifier(DeclSpec &DS) { 4751 assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier"); 4752 4753 SourceLocation StartLoc = ConsumeToken(); 4754 BalancedDelimiterTracker T(*this, tok::l_paren); 4755 if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) { 4756 SkipUntil(tok::r_paren); 4757 return; 4758 } 4759 4760 TypeResult Result = ParseTypeName(); 4761 if (Result.isInvalid()) { 4762 SkipUntil(tok::r_paren); 4763 return; 4764 } 4765 4766 // Match the ')' 4767 T.consumeClose(); 4768 4769 if (T.getCloseLocation().isInvalid()) 4770 return; 4771 4772 DS.setTypeofParensRange(T.getRange()); 4773 DS.SetRangeEnd(T.getCloseLocation()); 4774 4775 const char *PrevSpec = 0; 4776 unsigned DiagID; 4777 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, 4778 DiagID, Result.release())) 4779 Diag(StartLoc, DiagID) << PrevSpec; 4780} 4781 4782 4783/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 4784/// from TryAltiVecVectorToken. 4785bool Parser::TryAltiVecVectorTokenOutOfLine() { 4786 Token Next = NextToken(); 4787 switch (Next.getKind()) { 4788 default: return false; 4789 case tok::kw_short: 4790 case tok::kw_long: 4791 case tok::kw_signed: 4792 case tok::kw_unsigned: 4793 case tok::kw_void: 4794 case tok::kw_char: 4795 case tok::kw_int: 4796 case tok::kw_float: 4797 case tok::kw_double: 4798 case tok::kw_bool: 4799 case tok::kw___pixel: 4800 Tok.setKind(tok::kw___vector); 4801 return true; 4802 case tok::identifier: 4803 if (Next.getIdentifierInfo() == Ident_pixel) { 4804 Tok.setKind(tok::kw___vector); 4805 return true; 4806 } 4807 return false; 4808 } 4809} 4810 4811bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 4812 const char *&PrevSpec, unsigned &DiagID, 4813 bool &isInvalid) { 4814 if (Tok.getIdentifierInfo() == Ident_vector) { 4815 Token Next = NextToken(); 4816 switch (Next.getKind()) { 4817 case tok::kw_short: 4818 case tok::kw_long: 4819 case tok::kw_signed: 4820 case tok::kw_unsigned: 4821 case tok::kw_void: 4822 case tok::kw_char: 4823 case tok::kw_int: 4824 case tok::kw_float: 4825 case tok::kw_double: 4826 case tok::kw_bool: 4827 case tok::kw___pixel: 4828 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 4829 return true; 4830 case tok::identifier: 4831 if (Next.getIdentifierInfo() == Ident_pixel) { 4832 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 4833 return true; 4834 } 4835 break; 4836 default: 4837 break; 4838 } 4839 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 4840 DS.isTypeAltiVecVector()) { 4841 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 4842 return true; 4843 } 4844 return false; 4845} 4846