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