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