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