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