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