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