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