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