ParseDecl.cpp revision c9f351700721150a985f21844fbfec55b04e861d
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 we don't have a comma, it is either the end of the list (a ';') or an 1383 // error, bail out. 1384 while (Tok.is(tok::comma)) { 1385 SourceLocation CommaLoc = ConsumeToken(); 1386 1387 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) { 1388 // This comma was followed by a line-break and something which can't be 1389 // the start of a declarator. The comma was probably a typo for a 1390 // semicolon. 1391 Diag(CommaLoc, diag::err_expected_semi_declaration) 1392 << FixItHint::CreateReplacement(CommaLoc, ";"); 1393 ExpectSemi = false; 1394 break; 1395 } 1396 1397 // Parse the next declarator. 1398 D.clear(); 1399 D.setCommaLoc(CommaLoc); 1400 1401 // Accept attributes in an init-declarator. In the first declarator in a 1402 // declaration, these would be part of the declspec. In subsequent 1403 // declarators, they become part of the declarator itself, so that they 1404 // don't apply to declarators after *this* one. Examples: 1405 // short __attribute__((common)) var; -> declspec 1406 // short var __attribute__((common)); -> declarator 1407 // short x, __attribute__((common)) var; -> declarator 1408 MaybeParseGNUAttributes(D); 1409 1410 ParseDeclarator(D); 1411 if (!D.isInvalidType()) { 1412 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 1413 D.complete(ThisDecl); 1414 if (ThisDecl) 1415 DeclsInGroup.push_back(ThisDecl); 1416 } 1417 } 1418 1419 if (DeclEnd) 1420 *DeclEnd = Tok.getLocation(); 1421 1422 if (ExpectSemi && 1423 ExpectAndConsumeSemi(Context == Declarator::FileContext 1424 ? diag::err_invalid_token_after_toplevel_declarator 1425 : diag::err_expected_semi_declaration)) { 1426 // Okay, there was no semicolon and one was expected. If we see a 1427 // declaration specifier, just assume it was missing and continue parsing. 1428 // Otherwise things are very confused and we skip to recover. 1429 if (!isDeclarationSpecifier()) { 1430 SkipUntil(tok::r_brace, true, true); 1431 if (Tok.is(tok::semi)) 1432 ConsumeToken(); 1433 } 1434 } 1435 1436 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, 1437 DeclsInGroup.data(), 1438 DeclsInGroup.size()); 1439} 1440 1441/// Parse an optional simple-asm-expr and attributes, and attach them to a 1442/// declarator. Returns true on an error. 1443bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) { 1444 // If a simple-asm-expr is present, parse it. 1445 if (Tok.is(tok::kw_asm)) { 1446 SourceLocation Loc; 1447 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1448 if (AsmLabel.isInvalid()) { 1449 SkipUntil(tok::semi, true, true); 1450 return true; 1451 } 1452 1453 D.setAsmLabel(AsmLabel.release()); 1454 D.SetRangeEnd(Loc); 1455 } 1456 1457 MaybeParseGNUAttributes(D); 1458 return false; 1459} 1460 1461/// \brief Parse 'declaration' after parsing 'declaration-specifiers 1462/// declarator'. This method parses the remainder of the declaration 1463/// (including any attributes or initializer, among other things) and 1464/// finalizes the declaration. 1465/// 1466/// init-declarator: [C99 6.7] 1467/// declarator 1468/// declarator '=' initializer 1469/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 1470/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 1471/// [C++] declarator initializer[opt] 1472/// 1473/// [C++] initializer: 1474/// [C++] '=' initializer-clause 1475/// [C++] '(' expression-list ')' 1476/// [C++0x] '=' 'default' [TODO] 1477/// [C++0x] '=' 'delete' 1478/// [C++0x] braced-init-list 1479/// 1480/// According to the standard grammar, =default and =delete are function 1481/// definitions, but that definitely doesn't fit with the parser here. 1482/// 1483Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D, 1484 const ParsedTemplateInfo &TemplateInfo) { 1485 if (ParseAsmAttributesAfterDeclarator(D)) 1486 return 0; 1487 1488 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); 1489} 1490 1491Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D, 1492 const ParsedTemplateInfo &TemplateInfo) { 1493 // Inform the current actions module that we just parsed this declarator. 1494 Decl *ThisDecl = 0; 1495 switch (TemplateInfo.Kind) { 1496 case ParsedTemplateInfo::NonTemplate: 1497 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 1498 break; 1499 1500 case ParsedTemplateInfo::Template: 1501 case ParsedTemplateInfo::ExplicitSpecialization: 1502 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 1503 MultiTemplateParamsArg(Actions, 1504 TemplateInfo.TemplateParams->data(), 1505 TemplateInfo.TemplateParams->size()), 1506 D); 1507 break; 1508 1509 case ParsedTemplateInfo::ExplicitInstantiation: { 1510 DeclResult ThisRes 1511 = Actions.ActOnExplicitInstantiation(getCurScope(), 1512 TemplateInfo.ExternLoc, 1513 TemplateInfo.TemplateLoc, 1514 D); 1515 if (ThisRes.isInvalid()) { 1516 SkipUntil(tok::semi, true, true); 1517 return 0; 1518 } 1519 1520 ThisDecl = ThisRes.get(); 1521 break; 1522 } 1523 } 1524 1525 bool TypeContainsAuto = 1526 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 1527 1528 // Parse declarator '=' initializer. 1529 // If a '==' or '+=' is found, suggest a fixit to '='. 1530 if (isTokenEqualOrEqualTypo()) { 1531 ConsumeToken(); 1532 if (Tok.is(tok::kw_delete)) { 1533 if (D.isFunctionDeclarator()) 1534 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 1535 << 1 /* delete */; 1536 else 1537 Diag(ConsumeToken(), diag::err_deleted_non_function); 1538 } else if (Tok.is(tok::kw_default)) { 1539 if (D.isFunctionDeclarator()) 1540 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 1541 << 0 /* default */; 1542 else 1543 Diag(ConsumeToken(), diag::err_default_special_members); 1544 } else { 1545 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1546 EnterScope(0); 1547 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1548 } 1549 1550 if (Tok.is(tok::code_completion)) { 1551 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 1552 cutOffParsing(); 1553 return 0; 1554 } 1555 1556 ExprResult Init(ParseInitializer()); 1557 1558 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1559 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1560 ExitScope(); 1561 } 1562 1563 if (Init.isInvalid()) { 1564 SkipUntil(tok::comma, true, true); 1565 Actions.ActOnInitializerError(ThisDecl); 1566 } else 1567 Actions.AddInitializerToDecl(ThisDecl, Init.take(), 1568 /*DirectInit=*/false, TypeContainsAuto); 1569 } 1570 } else if (Tok.is(tok::l_paren)) { 1571 // Parse C++ direct initializer: '(' expression-list ')' 1572 BalancedDelimiterTracker T(*this, tok::l_paren); 1573 T.consumeOpen(); 1574 1575 ExprVector Exprs(Actions); 1576 CommaLocsTy CommaLocs; 1577 1578 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1579 EnterScope(0); 1580 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1581 } 1582 1583 if (ParseExpressionList(Exprs, CommaLocs)) { 1584 SkipUntil(tok::r_paren); 1585 1586 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1587 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1588 ExitScope(); 1589 } 1590 } else { 1591 // Match the ')'. 1592 T.consumeClose(); 1593 1594 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 1595 "Unexpected number of commas!"); 1596 1597 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1598 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1599 ExitScope(); 1600 } 1601 1602 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(), 1603 T.getCloseLocation(), 1604 move_arg(Exprs)); 1605 Actions.AddInitializerToDecl(ThisDecl, Initializer.take(), 1606 /*DirectInit=*/true, TypeContainsAuto); 1607 } 1608 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 1609 // Parse C++0x braced-init-list. 1610 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 1611 1612 if (D.getCXXScopeSpec().isSet()) { 1613 EnterScope(0); 1614 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1615 } 1616 1617 ExprResult Init(ParseBraceInitializer()); 1618 1619 if (D.getCXXScopeSpec().isSet()) { 1620 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1621 ExitScope(); 1622 } 1623 1624 if (Init.isInvalid()) { 1625 Actions.ActOnInitializerError(ThisDecl); 1626 } else 1627 Actions.AddInitializerToDecl(ThisDecl, Init.take(), 1628 /*DirectInit=*/true, TypeContainsAuto); 1629 1630 } else { 1631 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); 1632 } 1633 1634 Actions.FinalizeDeclaration(ThisDecl); 1635 1636 return ThisDecl; 1637} 1638 1639/// ParseSpecifierQualifierList 1640/// specifier-qualifier-list: 1641/// type-specifier specifier-qualifier-list[opt] 1642/// type-qualifier specifier-qualifier-list[opt] 1643/// [GNU] attributes specifier-qualifier-list[opt] 1644/// 1645void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS, 1646 DeclSpecContext DSC) { 1647 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 1648 /// parse declaration-specifiers and complain about extra stuff. 1649 /// TODO: diagnose attribute-specifiers and alignment-specifiers. 1650 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC); 1651 1652 // Validate declspec for type-name. 1653 unsigned Specs = DS.getParsedSpecifiers(); 1654 if ((DSC == DSC_type_specifier || DSC == DSC_trailing) && 1655 !DS.hasTypeSpecifier()) { 1656 Diag(Tok, diag::err_expected_type); 1657 DS.SetTypeSpecError(); 1658 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && 1659 !DS.hasAttributes()) { 1660 Diag(Tok, diag::err_typename_requires_specqual); 1661 if (!DS.hasTypeSpecifier()) 1662 DS.SetTypeSpecError(); 1663 } 1664 1665 // Issue diagnostic and remove storage class if present. 1666 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 1667 if (DS.getStorageClassSpecLoc().isValid()) 1668 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 1669 else 1670 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); 1671 DS.ClearStorageClassSpecs(); 1672 } 1673 1674 // Issue diagnostic and remove function specfier if present. 1675 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 1676 if (DS.isInlineSpecified()) 1677 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 1678 if (DS.isVirtualSpecified()) 1679 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 1680 if (DS.isExplicitSpecified()) 1681 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 1682 DS.ClearFunctionSpecs(); 1683 } 1684 1685 // Issue diagnostic and remove constexpr specfier if present. 1686 if (DS.isConstexprSpecified()) { 1687 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr); 1688 DS.ClearConstexprSpec(); 1689 } 1690} 1691 1692/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 1693/// specified token is valid after the identifier in a declarator which 1694/// immediately follows the declspec. For example, these things are valid: 1695/// 1696/// int x [ 4]; // direct-declarator 1697/// int x ( int y); // direct-declarator 1698/// int(int x ) // direct-declarator 1699/// int x ; // simple-declaration 1700/// int x = 17; // init-declarator-list 1701/// int x , y; // init-declarator-list 1702/// int x __asm__ ("foo"); // init-declarator-list 1703/// int x : 4; // struct-declarator 1704/// int x { 5}; // C++'0x unified initializers 1705/// 1706/// This is not, because 'x' does not immediately follow the declspec (though 1707/// ')' happens to be valid anyway). 1708/// int (x) 1709/// 1710static bool isValidAfterIdentifierInDeclarator(const Token &T) { 1711 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) || 1712 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) || 1713 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon); 1714} 1715 1716 1717/// ParseImplicitInt - This method is called when we have an non-typename 1718/// identifier in a declspec (which normally terminates the decl spec) when 1719/// the declspec has no type specifier. In this case, the declspec is either 1720/// malformed or is "implicit int" (in K&R and C89). 1721/// 1722/// This method handles diagnosing this prettily and returns false if the 1723/// declspec is done being processed. If it recovers and thinks there may be 1724/// other pieces of declspec after it, it returns true. 1725/// 1726bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 1727 const ParsedTemplateInfo &TemplateInfo, 1728 AccessSpecifier AS, DeclSpecContext DSC) { 1729 assert(Tok.is(tok::identifier) && "should have identifier"); 1730 1731 SourceLocation Loc = Tok.getLocation(); 1732 // If we see an identifier that is not a type name, we normally would 1733 // parse it as the identifer being declared. However, when a typename 1734 // is typo'd or the definition is not included, this will incorrectly 1735 // parse the typename as the identifier name and fall over misparsing 1736 // later parts of the diagnostic. 1737 // 1738 // As such, we try to do some look-ahead in cases where this would 1739 // otherwise be an "implicit-int" case to see if this is invalid. For 1740 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 1741 // an identifier with implicit int, we'd get a parse error because the 1742 // next token is obviously invalid for a type. Parse these as a case 1743 // with an invalid type specifier. 1744 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 1745 1746 // Since we know that this either implicit int (which is rare) or an 1747 // error, do lookahead to try to do better recovery. This never applies 1748 // within a type specifier. Outside of C++, we allow this even if the 1749 // language doesn't "officially" support implicit int -- we support 1750 // implicit int as an extension in C99 and C11. Allegedly, MS also 1751 // supports implicit int in C++ mode. 1752 if (DSC != DSC_type_specifier && DSC != DSC_trailing && 1753 (!getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt) && 1754 isValidAfterIdentifierInDeclarator(NextToken())) { 1755 // If this token is valid for implicit int, e.g. "static x = 4", then 1756 // we just avoid eating the identifier, so it will be parsed as the 1757 // identifier in the declarator. 1758 return false; 1759 } 1760 1761 if (getLangOpts().CPlusPlus && 1762 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 1763 // Don't require a type specifier if we have the 'auto' storage class 1764 // specifier in C++98 -- we'll promote it to a type specifier. 1765 return false; 1766 } 1767 1768 // Otherwise, if we don't consume this token, we are going to emit an 1769 // error anyway. Try to recover from various common problems. Check 1770 // to see if this was a reference to a tag name without a tag specified. 1771 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 1772 // 1773 // C++ doesn't need this, and isTagName doesn't take SS. 1774 if (SS == 0) { 1775 const char *TagName = 0, *FixitTagName = 0; 1776 tok::TokenKind TagKind = tok::unknown; 1777 1778 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 1779 default: break; 1780 case DeclSpec::TST_enum: 1781 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break; 1782 case DeclSpec::TST_union: 1783 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break; 1784 case DeclSpec::TST_struct: 1785 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break; 1786 case DeclSpec::TST_class: 1787 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break; 1788 } 1789 1790 if (TagName) { 1791 IdentifierInfo *TokenName = Tok.getIdentifierInfo(); 1792 LookupResult R(Actions, TokenName, SourceLocation(), 1793 Sema::LookupOrdinaryName); 1794 1795 Diag(Loc, diag::err_use_of_tag_name_without_tag) 1796 << TokenName << TagName << getLangOpts().CPlusPlus 1797 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName); 1798 1799 if (Actions.LookupParsedName(R, getCurScope(), SS)) { 1800 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); 1801 I != IEnd; ++I) 1802 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 1803 << TokenName << TagName; 1804 } 1805 1806 // Parse this as a tag as if the missing tag were present. 1807 if (TagKind == tok::kw_enum) 1808 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal); 1809 else 1810 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS, 1811 /*EnteringContext*/ false, DSC_normal); 1812 return true; 1813 } 1814 } 1815 1816 // Determine whether this identifier could plausibly be the name of something 1817 // being declared (with a missing type). 1818 if (DSC != DSC_type_specifier && DSC != DSC_trailing && 1819 (!SS || DSC == DSC_top_level || DSC == DSC_class)) { 1820 // Look ahead to the next token to try to figure out what this declaration 1821 // was supposed to be. 1822 switch (NextToken().getKind()) { 1823 case tok::comma: 1824 case tok::equal: 1825 case tok::kw_asm: 1826 case tok::l_brace: 1827 case tok::l_square: 1828 case tok::semi: 1829 // This looks like a variable declaration. The type is probably missing. 1830 // We're done parsing decl-specifiers. 1831 return false; 1832 1833 case tok::l_paren: { 1834 // static x(4); // 'x' is not a type 1835 // x(int n); // 'x' is not a type 1836 // x (*p)[]; // 'x' is a type 1837 // 1838 // Since we're in an error case (or the rare 'implicit int in C++' MS 1839 // extension), we can afford to perform a tentative parse to determine 1840 // which case we're in. 1841 TentativeParsingAction PA(*this); 1842 ConsumeToken(); 1843 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false); 1844 PA.Revert(); 1845 if (TPR == TPResult::False()) 1846 return false; 1847 // The identifier is followed by a parenthesized declarator. 1848 // It's supposed to be a type. 1849 break; 1850 } 1851 1852 default: 1853 // This is probably supposed to be a type. This includes cases like: 1854 // int f(itn); 1855 // struct S { unsinged : 4; }; 1856 break; 1857 } 1858 } 1859 1860 // This is almost certainly an invalid type name. Let the action emit a 1861 // diagnostic and attempt to recover. 1862 ParsedType T; 1863 IdentifierInfo *II = Tok.getIdentifierInfo(); 1864 if (Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T)) { 1865 // The action emitted a diagnostic, so we don't have to. 1866 if (T) { 1867 // The action has suggested that the type T could be used. Set that as 1868 // the type in the declaration specifiers, consume the would-be type 1869 // name token, and we're done. 1870 const char *PrevSpec; 1871 unsigned DiagID; 1872 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T); 1873 DS.SetRangeEnd(Tok.getLocation()); 1874 ConsumeToken(); 1875 // There may be other declaration specifiers after this. 1876 return true; 1877 } else if (II != Tok.getIdentifierInfo()) { 1878 // If no type was suggested, the correction is to a keyword 1879 Tok.setKind(II->getTokenID()); 1880 // There may be other declaration specifiers after this. 1881 return true; 1882 } 1883 1884 // Fall through; the action had no suggestion for us. 1885 } else { 1886 // The action did not emit a diagnostic, so emit one now. 1887 SourceRange R; 1888 if (SS) R = SS->getRange(); 1889 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R; 1890 } 1891 1892 // Mark this as an error. 1893 DS.SetTypeSpecError(); 1894 DS.SetRangeEnd(Tok.getLocation()); 1895 ConsumeToken(); 1896 1897 // TODO: Could inject an invalid typedef decl in an enclosing scope to 1898 // avoid rippling error messages on subsequent uses of the same type, 1899 // could be useful if #include was forgotten. 1900 return false; 1901} 1902 1903/// \brief Determine the declaration specifier context from the declarator 1904/// context. 1905/// 1906/// \param Context the declarator context, which is one of the 1907/// Declarator::TheContext enumerator values. 1908Parser::DeclSpecContext 1909Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { 1910 if (Context == Declarator::MemberContext) 1911 return DSC_class; 1912 if (Context == Declarator::FileContext) 1913 return DSC_top_level; 1914 if (Context == Declarator::TrailingReturnContext) 1915 return DSC_trailing; 1916 return DSC_normal; 1917} 1918 1919/// ParseAlignArgument - Parse the argument to an alignment-specifier. 1920/// 1921/// FIXME: Simply returns an alignof() expression if the argument is a 1922/// type. Ideally, the type should be propagated directly into Sema. 1923/// 1924/// [C11] type-id 1925/// [C11] constant-expression 1926/// [C++0x] type-id ...[opt] 1927/// [C++0x] assignment-expression ...[opt] 1928ExprResult Parser::ParseAlignArgument(SourceLocation Start, 1929 SourceLocation &EllipsisLoc) { 1930 ExprResult ER; 1931 if (isTypeIdInParens()) { 1932 SourceLocation TypeLoc = Tok.getLocation(); 1933 ParsedType Ty = ParseTypeName().get(); 1934 SourceRange TypeRange(Start, Tok.getLocation()); 1935 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true, 1936 Ty.getAsOpaquePtr(), TypeRange); 1937 } else 1938 ER = ParseConstantExpression(); 1939 1940 if (getLangOpts().CPlusPlus0x && Tok.is(tok::ellipsis)) 1941 EllipsisLoc = ConsumeToken(); 1942 1943 return ER; 1944} 1945 1946/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the 1947/// attribute to Attrs. 1948/// 1949/// alignment-specifier: 1950/// [C11] '_Alignas' '(' type-id ')' 1951/// [C11] '_Alignas' '(' constant-expression ')' 1952/// [C++0x] 'alignas' '(' type-id ...[opt] ')' 1953/// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')' 1954void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs, 1955 SourceLocation *endLoc) { 1956 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) && 1957 "Not an alignment-specifier!"); 1958 1959 SourceLocation KWLoc = Tok.getLocation(); 1960 ConsumeToken(); 1961 1962 BalancedDelimiterTracker T(*this, tok::l_paren); 1963 if (T.expectAndConsume(diag::err_expected_lparen)) 1964 return; 1965 1966 SourceLocation EllipsisLoc; 1967 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc); 1968 if (ArgExpr.isInvalid()) { 1969 SkipUntil(tok::r_paren); 1970 return; 1971 } 1972 1973 T.consumeClose(); 1974 if (endLoc) 1975 *endLoc = T.getCloseLocation(); 1976 1977 // FIXME: Handle pack-expansions here. 1978 if (EllipsisLoc.isValid()) { 1979 Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported); 1980 return; 1981 } 1982 1983 ExprVector ArgExprs(Actions); 1984 ArgExprs.push_back(ArgExpr.release()); 1985 // FIXME: This should not be GNU, but we since the attribute used is 1986 // based on the spelling, and there is no true spelling for 1987 // C++11 attributes, this isn't accepted. 1988 Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc, 1989 0, T.getOpenLocation(), ArgExprs.take(), 1, 1990 AttributeList::AS_GNU); 1991} 1992 1993/// ParseDeclarationSpecifiers 1994/// declaration-specifiers: [C99 6.7] 1995/// storage-class-specifier declaration-specifiers[opt] 1996/// type-specifier declaration-specifiers[opt] 1997/// [C99] function-specifier declaration-specifiers[opt] 1998/// [C11] alignment-specifier declaration-specifiers[opt] 1999/// [GNU] attributes declaration-specifiers[opt] 2000/// [Clang] '__module_private__' declaration-specifiers[opt] 2001/// 2002/// storage-class-specifier: [C99 6.7.1] 2003/// 'typedef' 2004/// 'extern' 2005/// 'static' 2006/// 'auto' 2007/// 'register' 2008/// [C++] 'mutable' 2009/// [GNU] '__thread' 2010/// function-specifier: [C99 6.7.4] 2011/// [C99] 'inline' 2012/// [C++] 'virtual' 2013/// [C++] 'explicit' 2014/// [OpenCL] '__kernel' 2015/// 'friend': [C++ dcl.friend] 2016/// 'constexpr': [C++0x dcl.constexpr] 2017 2018/// 2019void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 2020 const ParsedTemplateInfo &TemplateInfo, 2021 AccessSpecifier AS, 2022 DeclSpecContext DSContext, 2023 LateParsedAttrList *LateAttrs) { 2024 if (DS.getSourceRange().isInvalid()) { 2025 DS.SetRangeStart(Tok.getLocation()); 2026 DS.SetRangeEnd(Tok.getLocation()); 2027 } 2028 2029 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); 2030 bool AttrsLastTime = false; 2031 ParsedAttributesWithRange attrs(AttrFactory); 2032 while (1) { 2033 bool isInvalid = false; 2034 const char *PrevSpec = 0; 2035 unsigned DiagID = 0; 2036 2037 SourceLocation Loc = Tok.getLocation(); 2038 2039 switch (Tok.getKind()) { 2040 default: 2041 DoneWithDeclSpec: 2042 if (!AttrsLastTime) 2043 ProhibitAttributes(attrs); 2044 else 2045 DS.takeAttributesFrom(attrs); 2046 2047 // If this is not a declaration specifier token, we're done reading decl 2048 // specifiers. First verify that DeclSpec's are consistent. 2049 DS.Finish(Diags, PP); 2050 return; 2051 2052 case tok::l_square: 2053 case tok::kw_alignas: 2054 if (!isCXX11AttributeSpecifier()) 2055 goto DoneWithDeclSpec; 2056 2057 ProhibitAttributes(attrs); 2058 // FIXME: It would be good to recover by accepting the attributes, 2059 // but attempting to do that now would cause serious 2060 // madness in terms of diagnostics. 2061 attrs.clear(); 2062 attrs.Range = SourceRange(); 2063 2064 ParseCXX11Attributes(attrs); 2065 AttrsLastTime = true; 2066 continue; 2067 2068 case tok::code_completion: { 2069 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 2070 if (DS.hasTypeSpecifier()) { 2071 bool AllowNonIdentifiers 2072 = (getCurScope()->getFlags() & (Scope::ControlScope | 2073 Scope::BlockScope | 2074 Scope::TemplateParamScope | 2075 Scope::FunctionPrototypeScope | 2076 Scope::AtCatchScope)) == 0; 2077 bool AllowNestedNameSpecifiers 2078 = DSContext == DSC_top_level || 2079 (DSContext == DSC_class && DS.isFriendSpecified()); 2080 2081 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 2082 AllowNonIdentifiers, 2083 AllowNestedNameSpecifiers); 2084 return cutOffParsing(); 2085 } 2086 2087 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) 2088 CCC = Sema::PCC_LocalDeclarationSpecifiers; 2089 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 2090 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate 2091 : Sema::PCC_Template; 2092 else if (DSContext == DSC_class) 2093 CCC = Sema::PCC_Class; 2094 else if (CurParsedObjCImpl) 2095 CCC = Sema::PCC_ObjCImplementation; 2096 2097 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 2098 return cutOffParsing(); 2099 } 2100 2101 case tok::coloncolon: // ::foo::bar 2102 // C++ scope specifier. Annotate and loop, or bail out on error. 2103 if (TryAnnotateCXXScopeToken(true)) { 2104 if (!DS.hasTypeSpecifier()) 2105 DS.SetTypeSpecError(); 2106 goto DoneWithDeclSpec; 2107 } 2108 if (Tok.is(tok::coloncolon)) // ::new or ::delete 2109 goto DoneWithDeclSpec; 2110 continue; 2111 2112 case tok::annot_cxxscope: { 2113 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector()) 2114 goto DoneWithDeclSpec; 2115 2116 CXXScopeSpec SS; 2117 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 2118 Tok.getAnnotationRange(), 2119 SS); 2120 2121 // We are looking for a qualified typename. 2122 Token Next = NextToken(); 2123 if (Next.is(tok::annot_template_id) && 2124 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 2125 ->Kind == TNK_Type_template) { 2126 // We have a qualified template-id, e.g., N::A<int> 2127 2128 // C++ [class.qual]p2: 2129 // In a lookup in which the constructor is an acceptable lookup 2130 // result and the nested-name-specifier nominates a class C: 2131 // 2132 // - if the name specified after the 2133 // nested-name-specifier, when looked up in C, is the 2134 // injected-class-name of C (Clause 9), or 2135 // 2136 // - if the name specified after the nested-name-specifier 2137 // is the same as the identifier or the 2138 // simple-template-id's template-name in the last 2139 // component of the nested-name-specifier, 2140 // 2141 // the name is instead considered to name the constructor of 2142 // class C. 2143 // 2144 // Thus, if the template-name is actually the constructor 2145 // name, then the code is ill-formed; this interpretation is 2146 // reinforced by the NAD status of core issue 635. 2147 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 2148 if ((DSContext == DSC_top_level || 2149 (DSContext == DSC_class && DS.isFriendSpecified())) && 2150 TemplateId->Name && 2151 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 2152 if (isConstructorDeclarator()) { 2153 // The user meant this to be an out-of-line constructor 2154 // definition, but template arguments are not allowed 2155 // there. Just allow this as a constructor; we'll 2156 // complain about it later. 2157 goto DoneWithDeclSpec; 2158 } 2159 2160 // The user meant this to name a type, but it actually names 2161 // a constructor with some extraneous template 2162 // arguments. Complain, then parse it as a type as the user 2163 // intended. 2164 Diag(TemplateId->TemplateNameLoc, 2165 diag::err_out_of_line_template_id_names_constructor) 2166 << TemplateId->Name; 2167 } 2168 2169 DS.getTypeSpecScope() = SS; 2170 ConsumeToken(); // The C++ scope. 2171 assert(Tok.is(tok::annot_template_id) && 2172 "ParseOptionalCXXScopeSpecifier not working"); 2173 AnnotateTemplateIdTokenAsType(); 2174 continue; 2175 } 2176 2177 if (Next.is(tok::annot_typename)) { 2178 DS.getTypeSpecScope() = SS; 2179 ConsumeToken(); // The C++ scope. 2180 if (Tok.getAnnotationValue()) { 2181 ParsedType T = getTypeAnnotation(Tok); 2182 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 2183 Tok.getAnnotationEndLoc(), 2184 PrevSpec, DiagID, T); 2185 } 2186 else 2187 DS.SetTypeSpecError(); 2188 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 2189 ConsumeToken(); // The typename 2190 } 2191 2192 if (Next.isNot(tok::identifier)) 2193 goto DoneWithDeclSpec; 2194 2195 // If we're in a context where the identifier could be a class name, 2196 // check whether this is a constructor declaration. 2197 if ((DSContext == DSC_top_level || 2198 (DSContext == DSC_class && DS.isFriendSpecified())) && 2199 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 2200 &SS)) { 2201 if (isConstructorDeclarator()) 2202 goto DoneWithDeclSpec; 2203 2204 // As noted in C++ [class.qual]p2 (cited above), when the name 2205 // of the class is qualified in a context where it could name 2206 // a constructor, its a constructor name. However, we've 2207 // looked at the declarator, and the user probably meant this 2208 // to be a type. Complain that it isn't supposed to be treated 2209 // as a type, then proceed to parse it as a type. 2210 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 2211 << Next.getIdentifierInfo(); 2212 } 2213 2214 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 2215 Next.getLocation(), 2216 getCurScope(), &SS, 2217 false, false, ParsedType(), 2218 /*IsCtorOrDtorName=*/false, 2219 /*NonTrivialSourceInfo=*/true); 2220 2221 // If the referenced identifier is not a type, then this declspec is 2222 // erroneous: We already checked about that it has no type specifier, and 2223 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 2224 // typename. 2225 if (TypeRep == 0) { 2226 ConsumeToken(); // Eat the scope spec so the identifier is current. 2227 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext)) continue; 2228 goto DoneWithDeclSpec; 2229 } 2230 2231 DS.getTypeSpecScope() = SS; 2232 ConsumeToken(); // The C++ scope. 2233 2234 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 2235 DiagID, TypeRep); 2236 if (isInvalid) 2237 break; 2238 2239 DS.SetRangeEnd(Tok.getLocation()); 2240 ConsumeToken(); // The typename. 2241 2242 continue; 2243 } 2244 2245 case tok::annot_typename: { 2246 if (Tok.getAnnotationValue()) { 2247 ParsedType T = getTypeAnnotation(Tok); 2248 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 2249 DiagID, T); 2250 } else 2251 DS.SetTypeSpecError(); 2252 2253 if (isInvalid) 2254 break; 2255 2256 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 2257 ConsumeToken(); // The typename 2258 2259 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 2260 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 2261 // Objective-C interface. 2262 if (Tok.is(tok::less) && getLangOpts().ObjC1) 2263 ParseObjCProtocolQualifiers(DS); 2264 2265 continue; 2266 } 2267 2268 case tok::kw___is_signed: 2269 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang 2270 // typically treats it as a trait. If we see __is_signed as it appears 2271 // in libstdc++, e.g., 2272 // 2273 // static const bool __is_signed; 2274 // 2275 // then treat __is_signed as an identifier rather than as a keyword. 2276 if (DS.getTypeSpecType() == TST_bool && 2277 DS.getTypeQualifiers() == DeclSpec::TQ_const && 2278 DS.getStorageClassSpec() == DeclSpec::SCS_static) { 2279 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 2280 Tok.setKind(tok::identifier); 2281 } 2282 2283 // We're done with the declaration-specifiers. 2284 goto DoneWithDeclSpec; 2285 2286 // typedef-name 2287 case tok::kw_decltype: 2288 case tok::identifier: { 2289 // In C++, check to see if this is a scope specifier like foo::bar::, if 2290 // so handle it as such. This is important for ctor parsing. 2291 if (getLangOpts().CPlusPlus) { 2292 if (TryAnnotateCXXScopeToken(true)) { 2293 if (!DS.hasTypeSpecifier()) 2294 DS.SetTypeSpecError(); 2295 goto DoneWithDeclSpec; 2296 } 2297 if (!Tok.is(tok::identifier)) 2298 continue; 2299 } 2300 2301 // This identifier can only be a typedef name if we haven't already seen 2302 // a type-specifier. Without this check we misparse: 2303 // typedef int X; struct Y { short X; }; as 'short int'. 2304 if (DS.hasTypeSpecifier()) 2305 goto DoneWithDeclSpec; 2306 2307 // Check for need to substitute AltiVec keyword tokens. 2308 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 2309 break; 2310 2311 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not 2312 // allow the use of a typedef name as a type specifier. 2313 if (DS.isTypeAltiVecVector()) 2314 goto DoneWithDeclSpec; 2315 2316 ParsedType TypeRep = 2317 Actions.getTypeName(*Tok.getIdentifierInfo(), 2318 Tok.getLocation(), getCurScope()); 2319 2320 // If this is not a typedef name, don't parse it as part of the declspec, 2321 // it must be an implicit int or an error. 2322 if (!TypeRep) { 2323 if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext)) continue; 2324 goto DoneWithDeclSpec; 2325 } 2326 2327 // If we're in a context where the identifier could be a class name, 2328 // check whether this is a constructor declaration. 2329 if (getLangOpts().CPlusPlus && DSContext == DSC_class && 2330 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 2331 isConstructorDeclarator()) 2332 goto DoneWithDeclSpec; 2333 2334 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 2335 DiagID, TypeRep); 2336 if (isInvalid) 2337 break; 2338 2339 DS.SetRangeEnd(Tok.getLocation()); 2340 ConsumeToken(); // The identifier 2341 2342 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 2343 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 2344 // Objective-C interface. 2345 if (Tok.is(tok::less) && getLangOpts().ObjC1) 2346 ParseObjCProtocolQualifiers(DS); 2347 2348 // Need to support trailing type qualifiers (e.g. "id<p> const"). 2349 // If a type specifier follows, it will be diagnosed elsewhere. 2350 continue; 2351 } 2352 2353 // type-name 2354 case tok::annot_template_id: { 2355 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2356 if (TemplateId->Kind != TNK_Type_template) { 2357 // This template-id does not refer to a type name, so we're 2358 // done with the type-specifiers. 2359 goto DoneWithDeclSpec; 2360 } 2361 2362 // If we're in a context where the template-id could be a 2363 // constructor name or specialization, check whether this is a 2364 // constructor declaration. 2365 if (getLangOpts().CPlusPlus && DSContext == DSC_class && 2366 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 2367 isConstructorDeclarator()) 2368 goto DoneWithDeclSpec; 2369 2370 // Turn the template-id annotation token into a type annotation 2371 // token, then try again to parse it as a type-specifier. 2372 AnnotateTemplateIdTokenAsType(); 2373 continue; 2374 } 2375 2376 // GNU attributes support. 2377 case tok::kw___attribute: 2378 ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs); 2379 continue; 2380 2381 // Microsoft declspec support. 2382 case tok::kw___declspec: 2383 ParseMicrosoftDeclSpec(DS.getAttributes()); 2384 continue; 2385 2386 // Microsoft single token adornments. 2387 case tok::kw___forceinline: { 2388 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 2389 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 2390 SourceLocation AttrNameLoc = ConsumeToken(); 2391 // FIXME: This does not work correctly if it is set to be a declspec 2392 // attribute, and a GNU attribute is simply incorrect. 2393 DS.getAttributes().addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 2394 SourceLocation(), 0, 0, AttributeList::AS_GNU); 2395 continue; 2396 } 2397 2398 case tok::kw___ptr64: 2399 case tok::kw___ptr32: 2400 case tok::kw___w64: 2401 case tok::kw___cdecl: 2402 case tok::kw___stdcall: 2403 case tok::kw___fastcall: 2404 case tok::kw___thiscall: 2405 case tok::kw___unaligned: 2406 ParseMicrosoftTypeAttributes(DS.getAttributes()); 2407 continue; 2408 2409 // Borland single token adornments. 2410 case tok::kw___pascal: 2411 ParseBorlandTypeAttributes(DS.getAttributes()); 2412 continue; 2413 2414 // OpenCL single token adornments. 2415 case tok::kw___kernel: 2416 ParseOpenCLAttributes(DS.getAttributes()); 2417 continue; 2418 2419 // storage-class-specifier 2420 case tok::kw_typedef: 2421 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc, 2422 PrevSpec, DiagID); 2423 break; 2424 case tok::kw_extern: 2425 if (DS.isThreadSpecified()) 2426 Diag(Tok, diag::ext_thread_before) << "extern"; 2427 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc, 2428 PrevSpec, DiagID); 2429 break; 2430 case tok::kw___private_extern__: 2431 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern, 2432 Loc, PrevSpec, DiagID); 2433 break; 2434 case tok::kw_static: 2435 if (DS.isThreadSpecified()) 2436 Diag(Tok, diag::ext_thread_before) << "static"; 2437 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc, 2438 PrevSpec, DiagID); 2439 break; 2440 case tok::kw_auto: 2441 if (getLangOpts().CPlusPlus0x) { 2442 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 2443 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 2444 PrevSpec, DiagID); 2445 if (!isInvalid) 2446 Diag(Tok, diag::ext_auto_storage_class) 2447 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 2448 } else 2449 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 2450 DiagID); 2451 } else 2452 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 2453 PrevSpec, DiagID); 2454 break; 2455 case tok::kw_register: 2456 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc, 2457 PrevSpec, DiagID); 2458 break; 2459 case tok::kw_mutable: 2460 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc, 2461 PrevSpec, DiagID); 2462 break; 2463 case tok::kw___thread: 2464 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); 2465 break; 2466 2467 // function-specifier 2468 case tok::kw_inline: 2469 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 2470 break; 2471 case tok::kw_virtual: 2472 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID); 2473 break; 2474 case tok::kw_explicit: 2475 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID); 2476 break; 2477 2478 // alignment-specifier 2479 case tok::kw__Alignas: 2480 if (!getLangOpts().C11) 2481 Diag(Tok, diag::ext_c11_alignas); 2482 ParseAlignmentSpecifier(DS.getAttributes()); 2483 continue; 2484 2485 // friend 2486 case tok::kw_friend: 2487 if (DSContext == DSC_class) 2488 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 2489 else { 2490 PrevSpec = ""; // not actually used by the diagnostic 2491 DiagID = diag::err_friend_invalid_in_context; 2492 isInvalid = true; 2493 } 2494 break; 2495 2496 // Modules 2497 case tok::kw___module_private__: 2498 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID); 2499 break; 2500 2501 // constexpr 2502 case tok::kw_constexpr: 2503 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 2504 break; 2505 2506 // type-specifier 2507 case tok::kw_short: 2508 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 2509 DiagID); 2510 break; 2511 case tok::kw_long: 2512 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 2513 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 2514 DiagID); 2515 else 2516 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 2517 DiagID); 2518 break; 2519 case tok::kw___int64: 2520 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 2521 DiagID); 2522 break; 2523 case tok::kw_signed: 2524 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 2525 DiagID); 2526 break; 2527 case tok::kw_unsigned: 2528 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 2529 DiagID); 2530 break; 2531 case tok::kw__Complex: 2532 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 2533 DiagID); 2534 break; 2535 case tok::kw__Imaginary: 2536 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 2537 DiagID); 2538 break; 2539 case tok::kw_void: 2540 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 2541 DiagID); 2542 break; 2543 case tok::kw_char: 2544 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 2545 DiagID); 2546 break; 2547 case tok::kw_int: 2548 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 2549 DiagID); 2550 break; 2551 case tok::kw___int128: 2552 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, 2553 DiagID); 2554 break; 2555 case tok::kw_half: 2556 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, 2557 DiagID); 2558 break; 2559 case tok::kw_float: 2560 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 2561 DiagID); 2562 break; 2563 case tok::kw_double: 2564 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 2565 DiagID); 2566 break; 2567 case tok::kw_wchar_t: 2568 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 2569 DiagID); 2570 break; 2571 case tok::kw_char16_t: 2572 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 2573 DiagID); 2574 break; 2575 case tok::kw_char32_t: 2576 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 2577 DiagID); 2578 break; 2579 case tok::kw_bool: 2580 case tok::kw__Bool: 2581 if (Tok.is(tok::kw_bool) && 2582 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 2583 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 2584 PrevSpec = ""; // Not used by the diagnostic. 2585 DiagID = diag::err_bool_redeclaration; 2586 // For better error recovery. 2587 Tok.setKind(tok::identifier); 2588 isInvalid = true; 2589 } else { 2590 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 2591 DiagID); 2592 } 2593 break; 2594 case tok::kw__Decimal32: 2595 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 2596 DiagID); 2597 break; 2598 case tok::kw__Decimal64: 2599 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 2600 DiagID); 2601 break; 2602 case tok::kw__Decimal128: 2603 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 2604 DiagID); 2605 break; 2606 case tok::kw___vector: 2607 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 2608 break; 2609 case tok::kw___pixel: 2610 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 2611 break; 2612 case tok::kw___unknown_anytype: 2613 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 2614 PrevSpec, DiagID); 2615 break; 2616 2617 // class-specifier: 2618 case tok::kw_class: 2619 case tok::kw_struct: 2620 case tok::kw_union: { 2621 tok::TokenKind Kind = Tok.getKind(); 2622 ConsumeToken(); 2623 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, 2624 EnteringContext, DSContext); 2625 continue; 2626 } 2627 2628 // enum-specifier: 2629 case tok::kw_enum: 2630 ConsumeToken(); 2631 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext); 2632 continue; 2633 2634 // cv-qualifier: 2635 case tok::kw_const: 2636 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 2637 getLangOpts()); 2638 break; 2639 case tok::kw_volatile: 2640 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 2641 getLangOpts()); 2642 break; 2643 case tok::kw_restrict: 2644 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 2645 getLangOpts()); 2646 break; 2647 2648 // C++ typename-specifier: 2649 case tok::kw_typename: 2650 if (TryAnnotateTypeOrScopeToken()) { 2651 DS.SetTypeSpecError(); 2652 goto DoneWithDeclSpec; 2653 } 2654 if (!Tok.is(tok::kw_typename)) 2655 continue; 2656 break; 2657 2658 // GNU typeof support. 2659 case tok::kw_typeof: 2660 ParseTypeofSpecifier(DS); 2661 continue; 2662 2663 case tok::annot_decltype: 2664 ParseDecltypeSpecifier(DS); 2665 continue; 2666 2667 case tok::kw___underlying_type: 2668 ParseUnderlyingTypeSpecifier(DS); 2669 continue; 2670 2671 case tok::kw__Atomic: 2672 ParseAtomicSpecifier(DS); 2673 continue; 2674 2675 // OpenCL qualifiers: 2676 case tok::kw_private: 2677 if (!getLangOpts().OpenCL) 2678 goto DoneWithDeclSpec; 2679 case tok::kw___private: 2680 case tok::kw___global: 2681 case tok::kw___local: 2682 case tok::kw___constant: 2683 case tok::kw___read_only: 2684 case tok::kw___write_only: 2685 case tok::kw___read_write: 2686 ParseOpenCLQualifiers(DS); 2687 break; 2688 2689 case tok::less: 2690 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 2691 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 2692 // but we support it. 2693 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1) 2694 goto DoneWithDeclSpec; 2695 2696 if (!ParseObjCProtocolQualifiers(DS)) 2697 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 2698 << FixItHint::CreateInsertion(Loc, "id") 2699 << SourceRange(Loc, DS.getSourceRange().getEnd()); 2700 2701 // Need to support trailing type qualifiers (e.g. "id<p> const"). 2702 // If a type specifier follows, it will be diagnosed elsewhere. 2703 continue; 2704 } 2705 // If the specifier wasn't legal, issue a diagnostic. 2706 if (isInvalid) { 2707 assert(PrevSpec && "Method did not return previous specifier!"); 2708 assert(DiagID); 2709 2710 if (DiagID == diag::ext_duplicate_declspec) 2711 Diag(Tok, DiagID) 2712 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 2713 else 2714 Diag(Tok, DiagID) << PrevSpec; 2715 } 2716 2717 DS.SetRangeEnd(Tok.getLocation()); 2718 if (DiagID != diag::err_bool_redeclaration) 2719 ConsumeToken(); 2720 2721 AttrsLastTime = false; 2722 } 2723} 2724 2725/// ParseStructDeclaration - Parse a struct declaration without the terminating 2726/// semicolon. 2727/// 2728/// struct-declaration: 2729/// specifier-qualifier-list struct-declarator-list 2730/// [GNU] __extension__ struct-declaration 2731/// [GNU] specifier-qualifier-list 2732/// struct-declarator-list: 2733/// struct-declarator 2734/// struct-declarator-list ',' struct-declarator 2735/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 2736/// struct-declarator: 2737/// declarator 2738/// [GNU] declarator attributes[opt] 2739/// declarator[opt] ':' constant-expression 2740/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 2741/// 2742void Parser:: 2743ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) { 2744 2745 if (Tok.is(tok::kw___extension__)) { 2746 // __extension__ silences extension warnings in the subexpression. 2747 ExtensionRAIIObject O(Diags); // Use RAII to do this. 2748 ConsumeToken(); 2749 return ParseStructDeclaration(DS, Fields); 2750 } 2751 2752 // Parse the common specifier-qualifiers-list piece. 2753 ParseSpecifierQualifierList(DS); 2754 2755 // If there are no declarators, this is a free-standing declaration 2756 // specifier. Let the actions module cope with it. 2757 if (Tok.is(tok::semi)) { 2758 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS); 2759 return; 2760 } 2761 2762 // Read struct-declarators until we find the semicolon. 2763 bool FirstDeclarator = true; 2764 SourceLocation CommaLoc; 2765 while (1) { 2766 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 2767 FieldDeclarator DeclaratorInfo(DS); 2768 DeclaratorInfo.D.setCommaLoc(CommaLoc); 2769 2770 // Attributes are only allowed here on successive declarators. 2771 if (!FirstDeclarator) 2772 MaybeParseGNUAttributes(DeclaratorInfo.D); 2773 2774 /// struct-declarator: declarator 2775 /// struct-declarator: declarator[opt] ':' constant-expression 2776 if (Tok.isNot(tok::colon)) { 2777 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 2778 ColonProtectionRAIIObject X(*this); 2779 ParseDeclarator(DeclaratorInfo.D); 2780 } 2781 2782 if (Tok.is(tok::colon)) { 2783 ConsumeToken(); 2784 ExprResult Res(ParseConstantExpression()); 2785 if (Res.isInvalid()) 2786 SkipUntil(tok::semi, true, true); 2787 else 2788 DeclaratorInfo.BitfieldSize = Res.release(); 2789 } 2790 2791 // If attributes exist after the declarator, parse them. 2792 MaybeParseGNUAttributes(DeclaratorInfo.D); 2793 2794 // We're done with this declarator; invoke the callback. 2795 Decl *D = Fields.invoke(DeclaratorInfo); 2796 PD.complete(D); 2797 2798 // If we don't have a comma, it is either the end of the list (a ';') 2799 // or an error, bail out. 2800 if (Tok.isNot(tok::comma)) 2801 return; 2802 2803 // Consume the comma. 2804 CommaLoc = ConsumeToken(); 2805 2806 FirstDeclarator = false; 2807 } 2808} 2809 2810/// ParseStructUnionBody 2811/// struct-contents: 2812/// struct-declaration-list 2813/// [EXT] empty 2814/// [GNU] "struct-declaration-list" without terminatoring ';' 2815/// struct-declaration-list: 2816/// struct-declaration 2817/// struct-declaration-list struct-declaration 2818/// [OBC] '@' 'defs' '(' class-name ')' 2819/// 2820void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 2821 unsigned TagType, Decl *TagDecl) { 2822 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 2823 "parsing struct/union body"); 2824 2825 BalancedDelimiterTracker T(*this, tok::l_brace); 2826 if (T.consumeOpen()) 2827 return; 2828 2829 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 2830 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 2831 2832 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 2833 // C++. 2834 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) { 2835 Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union); 2836 Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union); 2837 } 2838 2839 SmallVector<Decl *, 32> FieldDecls; 2840 2841 // While we still have something to read, read the declarations in the struct. 2842 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 2843 // Each iteration of this loop reads one struct-declaration. 2844 2845 // Check for extraneous top-level semicolon. 2846 if (Tok.is(tok::semi)) { 2847 ConsumeExtraSemi(InsideStruct, 2848 DeclSpec::getSpecifierName((DeclSpec::TST)TagType)); 2849 continue; 2850 } 2851 2852 // Parse all the comma separated declarators. 2853 DeclSpec DS(AttrFactory); 2854 2855 if (!Tok.is(tok::at)) { 2856 struct CFieldCallback : FieldCallback { 2857 Parser &P; 2858 Decl *TagDecl; 2859 SmallVectorImpl<Decl *> &FieldDecls; 2860 2861 CFieldCallback(Parser &P, Decl *TagDecl, 2862 SmallVectorImpl<Decl *> &FieldDecls) : 2863 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 2864 2865 virtual Decl *invoke(FieldDeclarator &FD) { 2866 // Install the declarator into the current TagDecl. 2867 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl, 2868 FD.D.getDeclSpec().getSourceRange().getBegin(), 2869 FD.D, FD.BitfieldSize); 2870 FieldDecls.push_back(Field); 2871 return Field; 2872 } 2873 } Callback(*this, TagDecl, FieldDecls); 2874 2875 ParseStructDeclaration(DS, Callback); 2876 } else { // Handle @defs 2877 ConsumeToken(); 2878 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 2879 Diag(Tok, diag::err_unexpected_at); 2880 SkipUntil(tok::semi, true); 2881 continue; 2882 } 2883 ConsumeToken(); 2884 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 2885 if (!Tok.is(tok::identifier)) { 2886 Diag(Tok, diag::err_expected_ident); 2887 SkipUntil(tok::semi, true); 2888 continue; 2889 } 2890 SmallVector<Decl *, 16> Fields; 2891 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 2892 Tok.getIdentifierInfo(), Fields); 2893 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 2894 ConsumeToken(); 2895 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 2896 } 2897 2898 if (Tok.is(tok::semi)) { 2899 ConsumeToken(); 2900 } else if (Tok.is(tok::r_brace)) { 2901 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 2902 break; 2903 } else { 2904 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 2905 // Skip to end of block or statement to avoid ext-warning on extra ';'. 2906 SkipUntil(tok::r_brace, true, true); 2907 // If we stopped at a ';', eat it. 2908 if (Tok.is(tok::semi)) ConsumeToken(); 2909 } 2910 } 2911 2912 T.consumeClose(); 2913 2914 ParsedAttributes attrs(AttrFactory); 2915 // If attributes exist after struct contents, parse them. 2916 MaybeParseGNUAttributes(attrs); 2917 2918 Actions.ActOnFields(getCurScope(), 2919 RecordLoc, TagDecl, FieldDecls, 2920 T.getOpenLocation(), T.getCloseLocation(), 2921 attrs.getList()); 2922 StructScope.Exit(); 2923 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 2924 T.getCloseLocation()); 2925} 2926 2927/// ParseEnumSpecifier 2928/// enum-specifier: [C99 6.7.2.2] 2929/// 'enum' identifier[opt] '{' enumerator-list '}' 2930///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 2931/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 2932/// '}' attributes[opt] 2933/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] 2934/// '}' 2935/// 'enum' identifier 2936/// [GNU] 'enum' attributes[opt] identifier 2937/// 2938/// [C++11] enum-head '{' enumerator-list[opt] '}' 2939/// [C++11] enum-head '{' enumerator-list ',' '}' 2940/// 2941/// enum-head: [C++11] 2942/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] 2943/// enum-key attribute-specifier-seq[opt] nested-name-specifier 2944/// identifier enum-base[opt] 2945/// 2946/// enum-key: [C++11] 2947/// 'enum' 2948/// 'enum' 'class' 2949/// 'enum' 'struct' 2950/// 2951/// enum-base: [C++11] 2952/// ':' type-specifier-seq 2953/// 2954/// [C++] elaborated-type-specifier: 2955/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 2956/// 2957void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 2958 const ParsedTemplateInfo &TemplateInfo, 2959 AccessSpecifier AS, DeclSpecContext DSC) { 2960 // Parse the tag portion of this. 2961 if (Tok.is(tok::code_completion)) { 2962 // Code completion for an enum name. 2963 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 2964 return cutOffParsing(); 2965 } 2966 2967 // If attributes exist after tag, parse them. 2968 ParsedAttributesWithRange attrs(AttrFactory); 2969 MaybeParseGNUAttributes(attrs); 2970 MaybeParseCXX0XAttributes(attrs); 2971 2972 // If declspecs exist after tag, parse them. 2973 while (Tok.is(tok::kw___declspec)) 2974 ParseMicrosoftDeclSpec(attrs); 2975 2976 SourceLocation ScopedEnumKWLoc; 2977 bool IsScopedUsingClassTag = false; 2978 2979 // In C++11, recognize 'enum class' and 'enum struct'. 2980 if (getLangOpts().CPlusPlus0x && 2981 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) { 2982 Diag(Tok, diag::warn_cxx98_compat_scoped_enum); 2983 IsScopedUsingClassTag = Tok.is(tok::kw_class); 2984 ScopedEnumKWLoc = ConsumeToken(); 2985 2986 // Attributes are not allowed between these keywords. Diagnose, 2987 // but then just treat them like they appeared in the right place. 2988 ProhibitAttributes(attrs); 2989 2990 // They are allowed afterwards, though. 2991 MaybeParseGNUAttributes(attrs); 2992 MaybeParseCXX0XAttributes(attrs); 2993 while (Tok.is(tok::kw___declspec)) 2994 ParseMicrosoftDeclSpec(attrs); 2995 } 2996 2997 // C++11 [temp.explicit]p12: 2998 // The usual access controls do not apply to names used to specify 2999 // explicit instantiations. 3000 // We extend this to also cover explicit specializations. Note that 3001 // we don't suppress if this turns out to be an elaborated type 3002 // specifier. 3003 bool shouldDelayDiagsInTag = 3004 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 3005 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 3006 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 3007 3008 // Enum definitions should not be parsed in a trailing-return-type. 3009 bool AllowDeclaration = DSC != DSC_trailing; 3010 3011 bool AllowFixedUnderlyingType = AllowDeclaration && 3012 (getLangOpts().CPlusPlus0x || getLangOpts().MicrosoftExt || 3013 getLangOpts().ObjC2); 3014 3015 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3016 if (getLangOpts().CPlusPlus) { 3017 // "enum foo : bar;" is not a potential typo for "enum foo::bar;" 3018 // if a fixed underlying type is allowed. 3019 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); 3020 3021 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 3022 /*EnteringContext=*/false)) 3023 return; 3024 3025 if (SS.isSet() && Tok.isNot(tok::identifier)) { 3026 Diag(Tok, diag::err_expected_ident); 3027 if (Tok.isNot(tok::l_brace)) { 3028 // Has no name and is not a definition. 3029 // Skip the rest of this declarator, up until the comma or semicolon. 3030 SkipUntil(tok::comma, true); 3031 return; 3032 } 3033 } 3034 } 3035 3036 // Must have either 'enum name' or 'enum {...}'. 3037 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 3038 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) { 3039 Diag(Tok, diag::err_expected_ident_lbrace); 3040 3041 // Skip the rest of this declarator, up until the comma or semicolon. 3042 SkipUntil(tok::comma, true); 3043 return; 3044 } 3045 3046 // If an identifier is present, consume and remember it. 3047 IdentifierInfo *Name = 0; 3048 SourceLocation NameLoc; 3049 if (Tok.is(tok::identifier)) { 3050 Name = Tok.getIdentifierInfo(); 3051 NameLoc = ConsumeToken(); 3052 } 3053 3054 if (!Name && ScopedEnumKWLoc.isValid()) { 3055 // C++0x 7.2p2: The optional identifier shall not be omitted in the 3056 // declaration of a scoped enumeration. 3057 Diag(Tok, diag::err_scoped_enum_missing_identifier); 3058 ScopedEnumKWLoc = SourceLocation(); 3059 IsScopedUsingClassTag = false; 3060 } 3061 3062 // Okay, end the suppression area. We'll decide whether to emit the 3063 // diagnostics in a second. 3064 if (shouldDelayDiagsInTag) 3065 diagsFromTag.done(); 3066 3067 TypeResult BaseType; 3068 3069 // Parse the fixed underlying type. 3070 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 3071 bool PossibleBitfield = false; 3072 if (getCurScope()->getFlags() & Scope::ClassScope) { 3073 // If we're in class scope, this can either be an enum declaration with 3074 // an underlying type, or a declaration of a bitfield member. We try to 3075 // use a simple disambiguation scheme first to catch the common cases 3076 // (integer literal, sizeof); if it's still ambiguous, we then consider 3077 // anything that's a simple-type-specifier followed by '(' as an 3078 // expression. This suffices because function types are not valid 3079 // underlying types anyway. 3080 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 3081 // If the next token starts an expression, we know we're parsing a 3082 // bit-field. This is the common case. 3083 if (TPR == TPResult::True()) 3084 PossibleBitfield = true; 3085 // If the next token starts a type-specifier-seq, it may be either a 3086 // a fixed underlying type or the start of a function-style cast in C++; 3087 // lookahead one more token to see if it's obvious that we have a 3088 // fixed underlying type. 3089 else if (TPR == TPResult::False() && 3090 GetLookAheadToken(2).getKind() == tok::semi) { 3091 // Consume the ':'. 3092 ConsumeToken(); 3093 } else { 3094 // We have the start of a type-specifier-seq, so we have to perform 3095 // tentative parsing to determine whether we have an expression or a 3096 // type. 3097 TentativeParsingAction TPA(*this); 3098 3099 // Consume the ':'. 3100 ConsumeToken(); 3101 3102 // If we see a type specifier followed by an open-brace, we have an 3103 // ambiguity between an underlying type and a C++11 braced 3104 // function-style cast. Resolve this by always treating it as an 3105 // underlying type. 3106 // FIXME: The standard is not entirely clear on how to disambiguate in 3107 // this case. 3108 if ((getLangOpts().CPlusPlus && 3109 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) || 3110 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) { 3111 // We'll parse this as a bitfield later. 3112 PossibleBitfield = true; 3113 TPA.Revert(); 3114 } else { 3115 // We have a type-specifier-seq. 3116 TPA.Commit(); 3117 } 3118 } 3119 } else { 3120 // Consume the ':'. 3121 ConsumeToken(); 3122 } 3123 3124 if (!PossibleBitfield) { 3125 SourceRange Range; 3126 BaseType = ParseTypeName(&Range); 3127 3128 if (!getLangOpts().CPlusPlus0x && !getLangOpts().ObjC2) 3129 Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type) 3130 << Range; 3131 if (getLangOpts().CPlusPlus0x) 3132 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); 3133 } 3134 } 3135 3136 // There are four options here. If we have 'friend enum foo;' then this is a 3137 // friend declaration, and cannot have an accompanying definition. If we have 3138 // 'enum foo;', then this is a forward declaration. If we have 3139 // 'enum foo {...' then this is a definition. Otherwise we have something 3140 // like 'enum foo xyz', a reference. 3141 // 3142 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 3143 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 3144 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 3145 // 3146 Sema::TagUseKind TUK; 3147 if (!AllowDeclaration) { 3148 TUK = Sema::TUK_Reference; 3149 } else if (Tok.is(tok::l_brace)) { 3150 if (DS.isFriendSpecified()) { 3151 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 3152 << SourceRange(DS.getFriendSpecLoc()); 3153 ConsumeBrace(); 3154 SkipUntil(tok::r_brace); 3155 TUK = Sema::TUK_Friend; 3156 } else { 3157 TUK = Sema::TUK_Definition; 3158 } 3159 } else if (DSC != DSC_type_specifier && 3160 (Tok.is(tok::semi) || 3161 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier()))) { 3162 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 3163 if (Tok.isNot(tok::semi)) { 3164 // A semicolon was missing after this declaration. Diagnose and recover. 3165 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 3166 "enum"); 3167 PP.EnterToken(Tok); 3168 Tok.setKind(tok::semi); 3169 } 3170 } else { 3171 TUK = Sema::TUK_Reference; 3172 } 3173 3174 // If this is an elaborated type specifier, and we delayed 3175 // diagnostics before, just merge them into the current pool. 3176 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) { 3177 diagsFromTag.redelay(); 3178 } 3179 3180 MultiTemplateParamsArg TParams; 3181 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 3182 TUK != Sema::TUK_Reference) { 3183 if (!getLangOpts().CPlusPlus0x || !SS.isSet()) { 3184 // Skip the rest of this declarator, up until the comma or semicolon. 3185 Diag(Tok, diag::err_enum_template); 3186 SkipUntil(tok::comma, true); 3187 return; 3188 } 3189 3190 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 3191 // Enumerations can't be explicitly instantiated. 3192 DS.SetTypeSpecError(); 3193 Diag(StartLoc, diag::err_explicit_instantiation_enum); 3194 return; 3195 } 3196 3197 assert(TemplateInfo.TemplateParams && "no template parameters"); 3198 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(), 3199 TemplateInfo.TemplateParams->size()); 3200 } 3201 3202 if (TUK == Sema::TUK_Reference) 3203 ProhibitAttributes(attrs); 3204 3205 if (!Name && TUK != Sema::TUK_Definition) { 3206 Diag(Tok, diag::err_enumerator_unnamed_no_def); 3207 3208 // Skip the rest of this declarator, up until the comma or semicolon. 3209 SkipUntil(tok::comma, true); 3210 return; 3211 } 3212 3213 bool Owned = false; 3214 bool IsDependent = false; 3215 const char *PrevSpec = 0; 3216 unsigned DiagID; 3217 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 3218 StartLoc, SS, Name, NameLoc, attrs.getList(), 3219 AS, DS.getModulePrivateSpecLoc(), TParams, 3220 Owned, IsDependent, ScopedEnumKWLoc, 3221 IsScopedUsingClassTag, BaseType); 3222 3223 if (IsDependent) { 3224 // This enum has a dependent nested-name-specifier. Handle it as a 3225 // dependent tag. 3226 if (!Name) { 3227 DS.SetTypeSpecError(); 3228 Diag(Tok, diag::err_expected_type_name_after_typename); 3229 return; 3230 } 3231 3232 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum, 3233 TUK, SS, Name, StartLoc, 3234 NameLoc); 3235 if (Type.isInvalid()) { 3236 DS.SetTypeSpecError(); 3237 return; 3238 } 3239 3240 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 3241 NameLoc.isValid() ? NameLoc : StartLoc, 3242 PrevSpec, DiagID, Type.get())) 3243 Diag(StartLoc, DiagID) << PrevSpec; 3244 3245 return; 3246 } 3247 3248 if (!TagDecl) { 3249 // The action failed to produce an enumeration tag. If this is a 3250 // definition, consume the entire definition. 3251 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 3252 ConsumeBrace(); 3253 SkipUntil(tok::r_brace); 3254 } 3255 3256 DS.SetTypeSpecError(); 3257 return; 3258 } 3259 3260 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) 3261 ParseEnumBody(StartLoc, TagDecl); 3262 3263 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 3264 NameLoc.isValid() ? NameLoc : StartLoc, 3265 PrevSpec, DiagID, TagDecl, Owned)) 3266 Diag(StartLoc, DiagID) << PrevSpec; 3267} 3268 3269/// ParseEnumBody - Parse a {} enclosed enumerator-list. 3270/// enumerator-list: 3271/// enumerator 3272/// enumerator-list ',' enumerator 3273/// enumerator: 3274/// enumeration-constant 3275/// enumeration-constant '=' constant-expression 3276/// enumeration-constant: 3277/// identifier 3278/// 3279void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 3280 // Enter the scope of the enum body and start the definition. 3281 ParseScope EnumScope(this, Scope::DeclScope); 3282 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 3283 3284 BalancedDelimiterTracker T(*this, tok::l_brace); 3285 T.consumeOpen(); 3286 3287 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 3288 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) 3289 Diag(Tok, diag::error_empty_enum); 3290 3291 SmallVector<Decl *, 32> EnumConstantDecls; 3292 3293 Decl *LastEnumConstDecl = 0; 3294 3295 // Parse the enumerator-list. 3296 while (Tok.is(tok::identifier)) { 3297 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 3298 SourceLocation IdentLoc = ConsumeToken(); 3299 3300 // If attributes exist after the enumerator, parse them. 3301 ParsedAttributesWithRange attrs(AttrFactory); 3302 MaybeParseGNUAttributes(attrs); 3303 MaybeParseCXX0XAttributes(attrs); 3304 ProhibitAttributes(attrs); 3305 3306 SourceLocation EqualLoc; 3307 ExprResult AssignedVal; 3308 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 3309 3310 if (Tok.is(tok::equal)) { 3311 EqualLoc = ConsumeToken(); 3312 AssignedVal = ParseConstantExpression(); 3313 if (AssignedVal.isInvalid()) 3314 SkipUntil(tok::comma, tok::r_brace, true, true); 3315 } 3316 3317 // Install the enumerator constant into EnumDecl. 3318 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 3319 LastEnumConstDecl, 3320 IdentLoc, Ident, 3321 attrs.getList(), EqualLoc, 3322 AssignedVal.release()); 3323 PD.complete(EnumConstDecl); 3324 3325 EnumConstantDecls.push_back(EnumConstDecl); 3326 LastEnumConstDecl = EnumConstDecl; 3327 3328 if (Tok.is(tok::identifier)) { 3329 // We're missing a comma between enumerators. 3330 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 3331 Diag(Loc, diag::err_enumerator_list_missing_comma) 3332 << FixItHint::CreateInsertion(Loc, ", "); 3333 continue; 3334 } 3335 3336 if (Tok.isNot(tok::comma)) 3337 break; 3338 SourceLocation CommaLoc = ConsumeToken(); 3339 3340 if (Tok.isNot(tok::identifier)) { 3341 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus0x) 3342 Diag(CommaLoc, diag::ext_enumerator_list_comma) 3343 << getLangOpts().CPlusPlus 3344 << FixItHint::CreateRemoval(CommaLoc); 3345 else if (getLangOpts().CPlusPlus0x) 3346 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) 3347 << FixItHint::CreateRemoval(CommaLoc); 3348 } 3349 } 3350 3351 // Eat the }. 3352 T.consumeClose(); 3353 3354 // If attributes exist after the identifier list, parse them. 3355 ParsedAttributes attrs(AttrFactory); 3356 MaybeParseGNUAttributes(attrs); 3357 3358 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(), 3359 EnumDecl, EnumConstantDecls.data(), 3360 EnumConstantDecls.size(), getCurScope(), 3361 attrs.getList()); 3362 3363 EnumScope.Exit(); 3364 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, 3365 T.getCloseLocation()); 3366 3367 // The next token must be valid after an enum definition. If not, a ';' 3368 // was probably forgotten. 3369 if (!isValidAfterTypeSpecifier()) { 3370 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum"); 3371 // Push this token back into the preprocessor and change our current token 3372 // to ';' so that the rest of the code recovers as though there were an 3373 // ';' after the definition. 3374 PP.EnterToken(Tok); 3375 Tok.setKind(tok::semi); 3376 } 3377} 3378 3379/// isTypeSpecifierQualifier - Return true if the current token could be the 3380/// start of a type-qualifier-list. 3381bool Parser::isTypeQualifier() const { 3382 switch (Tok.getKind()) { 3383 default: return false; 3384 3385 // type-qualifier only in OpenCL 3386 case tok::kw_private: 3387 return getLangOpts().OpenCL; 3388 3389 // type-qualifier 3390 case tok::kw_const: 3391 case tok::kw_volatile: 3392 case tok::kw_restrict: 3393 case tok::kw___private: 3394 case tok::kw___local: 3395 case tok::kw___global: 3396 case tok::kw___constant: 3397 case tok::kw___read_only: 3398 case tok::kw___read_write: 3399 case tok::kw___write_only: 3400 return true; 3401 } 3402} 3403 3404/// isKnownToBeTypeSpecifier - Return true if we know that the specified token 3405/// is definitely a type-specifier. Return false if it isn't part of a type 3406/// specifier or if we're not sure. 3407bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 3408 switch (Tok.getKind()) { 3409 default: return false; 3410 // type-specifiers 3411 case tok::kw_short: 3412 case tok::kw_long: 3413 case tok::kw___int64: 3414 case tok::kw___int128: 3415 case tok::kw_signed: 3416 case tok::kw_unsigned: 3417 case tok::kw__Complex: 3418 case tok::kw__Imaginary: 3419 case tok::kw_void: 3420 case tok::kw_char: 3421 case tok::kw_wchar_t: 3422 case tok::kw_char16_t: 3423 case tok::kw_char32_t: 3424 case tok::kw_int: 3425 case tok::kw_half: 3426 case tok::kw_float: 3427 case tok::kw_double: 3428 case tok::kw_bool: 3429 case tok::kw__Bool: 3430 case tok::kw__Decimal32: 3431 case tok::kw__Decimal64: 3432 case tok::kw__Decimal128: 3433 case tok::kw___vector: 3434 3435 // struct-or-union-specifier (C99) or class-specifier (C++) 3436 case tok::kw_class: 3437 case tok::kw_struct: 3438 case tok::kw_union: 3439 // enum-specifier 3440 case tok::kw_enum: 3441 3442 // typedef-name 3443 case tok::annot_typename: 3444 return true; 3445 } 3446} 3447 3448/// isTypeSpecifierQualifier - Return true if the current token could be the 3449/// start of a specifier-qualifier-list. 3450bool Parser::isTypeSpecifierQualifier() { 3451 switch (Tok.getKind()) { 3452 default: return false; 3453 3454 case tok::identifier: // foo::bar 3455 if (TryAltiVecVectorToken()) 3456 return true; 3457 // Fall through. 3458 case tok::kw_typename: // typename T::type 3459 // Annotate typenames and C++ scope specifiers. If we get one, just 3460 // recurse to handle whatever we get. 3461 if (TryAnnotateTypeOrScopeToken()) 3462 return true; 3463 if (Tok.is(tok::identifier)) 3464 return false; 3465 return isTypeSpecifierQualifier(); 3466 3467 case tok::coloncolon: // ::foo::bar 3468 if (NextToken().is(tok::kw_new) || // ::new 3469 NextToken().is(tok::kw_delete)) // ::delete 3470 return false; 3471 3472 if (TryAnnotateTypeOrScopeToken()) 3473 return true; 3474 return isTypeSpecifierQualifier(); 3475 3476 // GNU attributes support. 3477 case tok::kw___attribute: 3478 // GNU typeof support. 3479 case tok::kw_typeof: 3480 3481 // type-specifiers 3482 case tok::kw_short: 3483 case tok::kw_long: 3484 case tok::kw___int64: 3485 case tok::kw___int128: 3486 case tok::kw_signed: 3487 case tok::kw_unsigned: 3488 case tok::kw__Complex: 3489 case tok::kw__Imaginary: 3490 case tok::kw_void: 3491 case tok::kw_char: 3492 case tok::kw_wchar_t: 3493 case tok::kw_char16_t: 3494 case tok::kw_char32_t: 3495 case tok::kw_int: 3496 case tok::kw_half: 3497 case tok::kw_float: 3498 case tok::kw_double: 3499 case tok::kw_bool: 3500 case tok::kw__Bool: 3501 case tok::kw__Decimal32: 3502 case tok::kw__Decimal64: 3503 case tok::kw__Decimal128: 3504 case tok::kw___vector: 3505 3506 // struct-or-union-specifier (C99) or class-specifier (C++) 3507 case tok::kw_class: 3508 case tok::kw_struct: 3509 case tok::kw_union: 3510 // enum-specifier 3511 case tok::kw_enum: 3512 3513 // type-qualifier 3514 case tok::kw_const: 3515 case tok::kw_volatile: 3516 case tok::kw_restrict: 3517 3518 // typedef-name 3519 case tok::annot_typename: 3520 return true; 3521 3522 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 3523 case tok::less: 3524 return getLangOpts().ObjC1; 3525 3526 case tok::kw___cdecl: 3527 case tok::kw___stdcall: 3528 case tok::kw___fastcall: 3529 case tok::kw___thiscall: 3530 case tok::kw___w64: 3531 case tok::kw___ptr64: 3532 case tok::kw___ptr32: 3533 case tok::kw___pascal: 3534 case tok::kw___unaligned: 3535 3536 case tok::kw___private: 3537 case tok::kw___local: 3538 case tok::kw___global: 3539 case tok::kw___constant: 3540 case tok::kw___read_only: 3541 case tok::kw___read_write: 3542 case tok::kw___write_only: 3543 3544 return true; 3545 3546 case tok::kw_private: 3547 return getLangOpts().OpenCL; 3548 3549 // C11 _Atomic() 3550 case tok::kw__Atomic: 3551 return true; 3552 } 3553} 3554 3555/// isDeclarationSpecifier() - Return true if the current token is part of a 3556/// declaration specifier. 3557/// 3558/// \param DisambiguatingWithExpression True to indicate that the purpose of 3559/// this check is to disambiguate between an expression and a declaration. 3560bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 3561 switch (Tok.getKind()) { 3562 default: return false; 3563 3564 case tok::kw_private: 3565 return getLangOpts().OpenCL; 3566 3567 case tok::identifier: // foo::bar 3568 // Unfortunate hack to support "Class.factoryMethod" notation. 3569 if (getLangOpts().ObjC1 && NextToken().is(tok::period)) 3570 return false; 3571 if (TryAltiVecVectorToken()) 3572 return true; 3573 // Fall through. 3574 case tok::kw_decltype: // decltype(T())::type 3575 case tok::kw_typename: // typename T::type 3576 // Annotate typenames and C++ scope specifiers. If we get one, just 3577 // recurse to handle whatever we get. 3578 if (TryAnnotateTypeOrScopeToken()) 3579 return true; 3580 if (Tok.is(tok::identifier)) 3581 return false; 3582 3583 // If we're in Objective-C and we have an Objective-C class type followed 3584 // by an identifier and then either ':' or ']', in a place where an 3585 // expression is permitted, then this is probably a class message send 3586 // missing the initial '['. In this case, we won't consider this to be 3587 // the start of a declaration. 3588 if (DisambiguatingWithExpression && 3589 isStartOfObjCClassMessageMissingOpenBracket()) 3590 return false; 3591 3592 return isDeclarationSpecifier(); 3593 3594 case tok::coloncolon: // ::foo::bar 3595 if (NextToken().is(tok::kw_new) || // ::new 3596 NextToken().is(tok::kw_delete)) // ::delete 3597 return false; 3598 3599 // Annotate typenames and C++ scope specifiers. If we get one, just 3600 // recurse to handle whatever we get. 3601 if (TryAnnotateTypeOrScopeToken()) 3602 return true; 3603 return isDeclarationSpecifier(); 3604 3605 // storage-class-specifier 3606 case tok::kw_typedef: 3607 case tok::kw_extern: 3608 case tok::kw___private_extern__: 3609 case tok::kw_static: 3610 case tok::kw_auto: 3611 case tok::kw_register: 3612 case tok::kw___thread: 3613 3614 // Modules 3615 case tok::kw___module_private__: 3616 3617 // type-specifiers 3618 case tok::kw_short: 3619 case tok::kw_long: 3620 case tok::kw___int64: 3621 case tok::kw___int128: 3622 case tok::kw_signed: 3623 case tok::kw_unsigned: 3624 case tok::kw__Complex: 3625 case tok::kw__Imaginary: 3626 case tok::kw_void: 3627 case tok::kw_char: 3628 case tok::kw_wchar_t: 3629 case tok::kw_char16_t: 3630 case tok::kw_char32_t: 3631 3632 case tok::kw_int: 3633 case tok::kw_half: 3634 case tok::kw_float: 3635 case tok::kw_double: 3636 case tok::kw_bool: 3637 case tok::kw__Bool: 3638 case tok::kw__Decimal32: 3639 case tok::kw__Decimal64: 3640 case tok::kw__Decimal128: 3641 case tok::kw___vector: 3642 3643 // struct-or-union-specifier (C99) or class-specifier (C++) 3644 case tok::kw_class: 3645 case tok::kw_struct: 3646 case tok::kw_union: 3647 // enum-specifier 3648 case tok::kw_enum: 3649 3650 // type-qualifier 3651 case tok::kw_const: 3652 case tok::kw_volatile: 3653 case tok::kw_restrict: 3654 3655 // function-specifier 3656 case tok::kw_inline: 3657 case tok::kw_virtual: 3658 case tok::kw_explicit: 3659 3660 // static_assert-declaration 3661 case tok::kw__Static_assert: 3662 3663 // GNU typeof support. 3664 case tok::kw_typeof: 3665 3666 // GNU attributes. 3667 case tok::kw___attribute: 3668 return true; 3669 3670 // C++0x decltype. 3671 case tok::annot_decltype: 3672 return true; 3673 3674 // C11 _Atomic() 3675 case tok::kw__Atomic: 3676 return true; 3677 3678 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 3679 case tok::less: 3680 return getLangOpts().ObjC1; 3681 3682 // typedef-name 3683 case tok::annot_typename: 3684 return !DisambiguatingWithExpression || 3685 !isStartOfObjCClassMessageMissingOpenBracket(); 3686 3687 case tok::kw___declspec: 3688 case tok::kw___cdecl: 3689 case tok::kw___stdcall: 3690 case tok::kw___fastcall: 3691 case tok::kw___thiscall: 3692 case tok::kw___w64: 3693 case tok::kw___ptr64: 3694 case tok::kw___ptr32: 3695 case tok::kw___forceinline: 3696 case tok::kw___pascal: 3697 case tok::kw___unaligned: 3698 3699 case tok::kw___private: 3700 case tok::kw___local: 3701 case tok::kw___global: 3702 case tok::kw___constant: 3703 case tok::kw___read_only: 3704 case tok::kw___read_write: 3705 case tok::kw___write_only: 3706 3707 return true; 3708 } 3709} 3710 3711bool Parser::isConstructorDeclarator() { 3712 TentativeParsingAction TPA(*this); 3713 3714 // Parse the C++ scope specifier. 3715 CXXScopeSpec SS; 3716 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 3717 /*EnteringContext=*/true)) { 3718 TPA.Revert(); 3719 return false; 3720 } 3721 3722 // Parse the constructor name. 3723 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 3724 // We already know that we have a constructor name; just consume 3725 // the token. 3726 ConsumeToken(); 3727 } else { 3728 TPA.Revert(); 3729 return false; 3730 } 3731 3732 // Current class name must be followed by a left parenthesis. 3733 if (Tok.isNot(tok::l_paren)) { 3734 TPA.Revert(); 3735 return false; 3736 } 3737 ConsumeParen(); 3738 3739 // A right parenthesis, or ellipsis followed by a right parenthesis signals 3740 // that we have a constructor. 3741 if (Tok.is(tok::r_paren) || 3742 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { 3743 TPA.Revert(); 3744 return true; 3745 } 3746 3747 // If we need to, enter the specified scope. 3748 DeclaratorScopeObj DeclScopeObj(*this, SS); 3749 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 3750 DeclScopeObj.EnterDeclaratorScope(); 3751 3752 // Optionally skip Microsoft attributes. 3753 ParsedAttributes Attrs(AttrFactory); 3754 MaybeParseMicrosoftAttributes(Attrs); 3755 3756 // Check whether the next token(s) are part of a declaration 3757 // specifier, in which case we have the start of a parameter and, 3758 // therefore, we know that this is a constructor. 3759 bool IsConstructor = false; 3760 if (isDeclarationSpecifier()) 3761 IsConstructor = true; 3762 else if (Tok.is(tok::identifier) || 3763 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { 3764 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. 3765 // This might be a parenthesized member name, but is more likely to 3766 // be a constructor declaration with an invalid argument type. Keep 3767 // looking. 3768 if (Tok.is(tok::annot_cxxscope)) 3769 ConsumeToken(); 3770 ConsumeToken(); 3771 3772 // If this is not a constructor, we must be parsing a declarator, 3773 // which must have one of the following syntactic forms (see the 3774 // grammar extract at the start of ParseDirectDeclarator): 3775 switch (Tok.getKind()) { 3776 case tok::l_paren: 3777 // C(X ( int)); 3778 case tok::l_square: 3779 // C(X [ 5]); 3780 // C(X [ [attribute]]); 3781 case tok::coloncolon: 3782 // C(X :: Y); 3783 // C(X :: *p); 3784 case tok::r_paren: 3785 // C(X ) 3786 // Assume this isn't a constructor, rather than assuming it's a 3787 // constructor with an unnamed parameter of an ill-formed type. 3788 break; 3789 3790 default: 3791 IsConstructor = true; 3792 break; 3793 } 3794 } 3795 3796 TPA.Revert(); 3797 return IsConstructor; 3798} 3799 3800/// ParseTypeQualifierListOpt 3801/// type-qualifier-list: [C99 6.7.5] 3802/// type-qualifier 3803/// [vendor] attributes 3804/// [ only if VendorAttributesAllowed=true ] 3805/// type-qualifier-list type-qualifier 3806/// [vendor] type-qualifier-list attributes 3807/// [ only if VendorAttributesAllowed=true ] 3808/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 3809/// [ only if CXX0XAttributesAllowed=true ] 3810/// Note: vendor can be GNU, MS, etc. 3811/// 3812void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, 3813 bool VendorAttributesAllowed, 3814 bool CXX11AttributesAllowed) { 3815 if (getLangOpts().CPlusPlus0x && CXX11AttributesAllowed && 3816 isCXX11AttributeSpecifier()) { 3817 ParsedAttributesWithRange attrs(AttrFactory); 3818 ParseCXX11Attributes(attrs); 3819 DS.takeAttributesFrom(attrs); 3820 } 3821 3822 SourceLocation EndLoc; 3823 3824 while (1) { 3825 bool isInvalid = false; 3826 const char *PrevSpec = 0; 3827 unsigned DiagID = 0; 3828 SourceLocation Loc = Tok.getLocation(); 3829 3830 switch (Tok.getKind()) { 3831 case tok::code_completion: 3832 Actions.CodeCompleteTypeQualifiers(DS); 3833 return cutOffParsing(); 3834 3835 case tok::kw_const: 3836 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 3837 getLangOpts()); 3838 break; 3839 case tok::kw_volatile: 3840 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 3841 getLangOpts()); 3842 break; 3843 case tok::kw_restrict: 3844 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 3845 getLangOpts()); 3846 break; 3847 3848 // OpenCL qualifiers: 3849 case tok::kw_private: 3850 if (!getLangOpts().OpenCL) 3851 goto DoneWithTypeQuals; 3852 case tok::kw___private: 3853 case tok::kw___global: 3854 case tok::kw___local: 3855 case tok::kw___constant: 3856 case tok::kw___read_only: 3857 case tok::kw___write_only: 3858 case tok::kw___read_write: 3859 ParseOpenCLQualifiers(DS); 3860 break; 3861 3862 case tok::kw___w64: 3863 case tok::kw___ptr64: 3864 case tok::kw___ptr32: 3865 case tok::kw___cdecl: 3866 case tok::kw___stdcall: 3867 case tok::kw___fastcall: 3868 case tok::kw___thiscall: 3869 case tok::kw___unaligned: 3870 if (VendorAttributesAllowed) { 3871 ParseMicrosoftTypeAttributes(DS.getAttributes()); 3872 continue; 3873 } 3874 goto DoneWithTypeQuals; 3875 case tok::kw___pascal: 3876 if (VendorAttributesAllowed) { 3877 ParseBorlandTypeAttributes(DS.getAttributes()); 3878 continue; 3879 } 3880 goto DoneWithTypeQuals; 3881 case tok::kw___attribute: 3882 if (VendorAttributesAllowed) { 3883 ParseGNUAttributes(DS.getAttributes()); 3884 continue; // do *not* consume the next token! 3885 } 3886 // otherwise, FALL THROUGH! 3887 default: 3888 DoneWithTypeQuals: 3889 // If this is not a type-qualifier token, we're done reading type 3890 // qualifiers. First verify that DeclSpec's are consistent. 3891 DS.Finish(Diags, PP); 3892 if (EndLoc.isValid()) 3893 DS.SetRangeEnd(EndLoc); 3894 return; 3895 } 3896 3897 // If the specifier combination wasn't legal, issue a diagnostic. 3898 if (isInvalid) { 3899 assert(PrevSpec && "Method did not return previous specifier!"); 3900 Diag(Tok, DiagID) << PrevSpec; 3901 } 3902 EndLoc = ConsumeToken(); 3903 } 3904} 3905 3906 3907/// ParseDeclarator - Parse and verify a newly-initialized declarator. 3908/// 3909void Parser::ParseDeclarator(Declarator &D) { 3910 /// This implements the 'declarator' production in the C grammar, then checks 3911 /// for well-formedness and issues diagnostics. 3912 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 3913} 3914 3915static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) { 3916 if (Kind == tok::star || Kind == tok::caret) 3917 return true; 3918 3919 // We parse rvalue refs in C++03, because otherwise the errors are scary. 3920 if (!Lang.CPlusPlus) 3921 return false; 3922 3923 return Kind == tok::amp || Kind == tok::ampamp; 3924} 3925 3926/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 3927/// is parsed by the function passed to it. Pass null, and the direct-declarator 3928/// isn't parsed at all, making this function effectively parse the C++ 3929/// ptr-operator production. 3930/// 3931/// If the grammar of this construct is extended, matching changes must also be 3932/// made to TryParseDeclarator and MightBeDeclarator, and possibly to 3933/// isConstructorDeclarator. 3934/// 3935/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 3936/// [C] pointer[opt] direct-declarator 3937/// [C++] direct-declarator 3938/// [C++] ptr-operator declarator 3939/// 3940/// pointer: [C99 6.7.5] 3941/// '*' type-qualifier-list[opt] 3942/// '*' type-qualifier-list[opt] pointer 3943/// 3944/// ptr-operator: 3945/// '*' cv-qualifier-seq[opt] 3946/// '&' 3947/// [C++0x] '&&' 3948/// [GNU] '&' restrict[opt] attributes[opt] 3949/// [GNU?] '&&' restrict[opt] attributes[opt] 3950/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 3951void Parser::ParseDeclaratorInternal(Declarator &D, 3952 DirectDeclParseFunction DirectDeclParser) { 3953 if (Diags.hasAllExtensionsSilenced()) 3954 D.setExtension(); 3955 3956 // C++ member pointers start with a '::' or a nested-name. 3957 // Member pointers get special handling, since there's no place for the 3958 // scope spec in the generic path below. 3959 if (getLangOpts().CPlusPlus && 3960 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 3961 Tok.is(tok::annot_cxxscope))) { 3962 bool EnteringContext = D.getContext() == Declarator::FileContext || 3963 D.getContext() == Declarator::MemberContext; 3964 CXXScopeSpec SS; 3965 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext); 3966 3967 if (SS.isNotEmpty()) { 3968 if (Tok.isNot(tok::star)) { 3969 // The scope spec really belongs to the direct-declarator. 3970 D.getCXXScopeSpec() = SS; 3971 if (DirectDeclParser) 3972 (this->*DirectDeclParser)(D); 3973 return; 3974 } 3975 3976 SourceLocation Loc = ConsumeToken(); 3977 D.SetRangeEnd(Loc); 3978 DeclSpec DS(AttrFactory); 3979 ParseTypeQualifierListOpt(DS); 3980 D.ExtendWithDeclSpec(DS); 3981 3982 // Recurse to parse whatever is left. 3983 ParseDeclaratorInternal(D, DirectDeclParser); 3984 3985 // Sema will have to catch (syntactically invalid) pointers into global 3986 // scope. It has to catch pointers into namespace scope anyway. 3987 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 3988 Loc), 3989 DS.getAttributes(), 3990 /* Don't replace range end. */SourceLocation()); 3991 return; 3992 } 3993 } 3994 3995 tok::TokenKind Kind = Tok.getKind(); 3996 // Not a pointer, C++ reference, or block. 3997 if (!isPtrOperatorToken(Kind, getLangOpts())) { 3998 if (DirectDeclParser) 3999 (this->*DirectDeclParser)(D); 4000 return; 4001 } 4002 4003 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 4004 // '&&' -> rvalue reference 4005 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 4006 D.SetRangeEnd(Loc); 4007 4008 if (Kind == tok::star || Kind == tok::caret) { 4009 // Is a pointer. 4010 DeclSpec DS(AttrFactory); 4011 4012 // FIXME: GNU attributes are not allowed here in a new-type-id. 4013 ParseTypeQualifierListOpt(DS); 4014 D.ExtendWithDeclSpec(DS); 4015 4016 // Recursively parse the declarator. 4017 ParseDeclaratorInternal(D, DirectDeclParser); 4018 if (Kind == tok::star) 4019 // Remember that we parsed a pointer type, and remember the type-quals. 4020 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 4021 DS.getConstSpecLoc(), 4022 DS.getVolatileSpecLoc(), 4023 DS.getRestrictSpecLoc()), 4024 DS.getAttributes(), 4025 SourceLocation()); 4026 else 4027 // Remember that we parsed a Block type, and remember the type-quals. 4028 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 4029 Loc), 4030 DS.getAttributes(), 4031 SourceLocation()); 4032 } else { 4033 // Is a reference 4034 DeclSpec DS(AttrFactory); 4035 4036 // Complain about rvalue references in C++03, but then go on and build 4037 // the declarator. 4038 if (Kind == tok::ampamp) 4039 Diag(Loc, getLangOpts().CPlusPlus0x ? 4040 diag::warn_cxx98_compat_rvalue_reference : 4041 diag::ext_rvalue_reference); 4042 4043 // GNU-style and C++11 attributes are allowed here, as is restrict. 4044 ParseTypeQualifierListOpt(DS); 4045 D.ExtendWithDeclSpec(DS); 4046 4047 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 4048 // cv-qualifiers are introduced through the use of a typedef or of a 4049 // template type argument, in which case the cv-qualifiers are ignored. 4050 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 4051 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4052 Diag(DS.getConstSpecLoc(), 4053 diag::err_invalid_reference_qualifier_application) << "const"; 4054 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4055 Diag(DS.getVolatileSpecLoc(), 4056 diag::err_invalid_reference_qualifier_application) << "volatile"; 4057 } 4058 4059 // Recursively parse the declarator. 4060 ParseDeclaratorInternal(D, DirectDeclParser); 4061 4062 if (D.getNumTypeObjects() > 0) { 4063 // C++ [dcl.ref]p4: There shall be no references to references. 4064 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 4065 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 4066 if (const IdentifierInfo *II = D.getIdentifier()) 4067 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 4068 << II; 4069 else 4070 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 4071 << "type name"; 4072 4073 // Once we've complained about the reference-to-reference, we 4074 // can go ahead and build the (technically ill-formed) 4075 // declarator: reference collapsing will take care of it. 4076 } 4077 } 4078 4079 // Remember that we parsed a reference type. It doesn't have type-quals. 4080 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 4081 Kind == tok::amp), 4082 DS.getAttributes(), 4083 SourceLocation()); 4084 } 4085} 4086 4087static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D, 4088 SourceLocation EllipsisLoc) { 4089 if (EllipsisLoc.isValid()) { 4090 FixItHint Insertion; 4091 if (!D.getEllipsisLoc().isValid()) { 4092 Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "..."); 4093 D.setEllipsisLoc(EllipsisLoc); 4094 } 4095 P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration) 4096 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName(); 4097 } 4098} 4099 4100/// ParseDirectDeclarator 4101/// direct-declarator: [C99 6.7.5] 4102/// [C99] identifier 4103/// '(' declarator ')' 4104/// [GNU] '(' attributes declarator ')' 4105/// [C90] direct-declarator '[' constant-expression[opt] ']' 4106/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 4107/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 4108/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 4109/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 4110/// [C++11] direct-declarator '[' constant-expression[opt] ']' 4111/// attribute-specifier-seq[opt] 4112/// direct-declarator '(' parameter-type-list ')' 4113/// direct-declarator '(' identifier-list[opt] ')' 4114/// [GNU] direct-declarator '(' parameter-forward-declarations 4115/// parameter-type-list[opt] ')' 4116/// [C++] direct-declarator '(' parameter-declaration-clause ')' 4117/// cv-qualifier-seq[opt] exception-specification[opt] 4118/// [C++11] direct-declarator '(' parameter-declaration-clause ')' 4119/// attribute-specifier-seq[opt] cv-qualifier-seq[opt] 4120/// ref-qualifier[opt] exception-specification[opt] 4121/// [C++] declarator-id 4122/// [C++11] declarator-id attribute-specifier-seq[opt] 4123/// 4124/// declarator-id: [C++ 8] 4125/// '...'[opt] id-expression 4126/// '::'[opt] nested-name-specifier[opt] type-name 4127/// 4128/// id-expression: [C++ 5.1] 4129/// unqualified-id 4130/// qualified-id 4131/// 4132/// unqualified-id: [C++ 5.1] 4133/// identifier 4134/// operator-function-id 4135/// conversion-function-id 4136/// '~' class-name 4137/// template-id 4138/// 4139/// Note, any additional constructs added here may need corresponding changes 4140/// in isConstructorDeclarator. 4141void Parser::ParseDirectDeclarator(Declarator &D) { 4142 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 4143 4144 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) { 4145 // ParseDeclaratorInternal might already have parsed the scope. 4146 if (D.getCXXScopeSpec().isEmpty()) { 4147 bool EnteringContext = D.getContext() == Declarator::FileContext || 4148 D.getContext() == Declarator::MemberContext; 4149 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), 4150 EnteringContext); 4151 } 4152 4153 if (D.getCXXScopeSpec().isValid()) { 4154 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 4155 // Change the declaration context for name lookup, until this function 4156 // is exited (and the declarator has been parsed). 4157 DeclScopeObj.EnterDeclaratorScope(); 4158 } 4159 4160 // C++0x [dcl.fct]p14: 4161 // There is a syntactic ambiguity when an ellipsis occurs at the end 4162 // of a parameter-declaration-clause without a preceding comma. In 4163 // this case, the ellipsis is parsed as part of the 4164 // abstract-declarator if the type of the parameter names a template 4165 // parameter pack that has not been expanded; otherwise, it is parsed 4166 // as part of the parameter-declaration-clause. 4167 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() && 4168 !((D.getContext() == Declarator::PrototypeContext || 4169 D.getContext() == Declarator::BlockLiteralContext) && 4170 NextToken().is(tok::r_paren) && 4171 !Actions.containsUnexpandedParameterPacks(D))) { 4172 SourceLocation EllipsisLoc = ConsumeToken(); 4173 if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) { 4174 // The ellipsis was put in the wrong place. Recover, and explain to 4175 // the user what they should have done. 4176 ParseDeclarator(D); 4177 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc); 4178 return; 4179 } else 4180 D.setEllipsisLoc(EllipsisLoc); 4181 4182 // The ellipsis can't be followed by a parenthesized declarator. We 4183 // check for that in ParseParenDeclarator, after we have disambiguated 4184 // the l_paren token. 4185 } 4186 4187 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 4188 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 4189 // We found something that indicates the start of an unqualified-id. 4190 // Parse that unqualified-id. 4191 bool AllowConstructorName; 4192 if (D.getDeclSpec().hasTypeSpecifier()) 4193 AllowConstructorName = false; 4194 else if (D.getCXXScopeSpec().isSet()) 4195 AllowConstructorName = 4196 (D.getContext() == Declarator::FileContext || 4197 (D.getContext() == Declarator::MemberContext && 4198 D.getDeclSpec().isFriendSpecified())); 4199 else 4200 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 4201 4202 SourceLocation TemplateKWLoc; 4203 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 4204 /*EnteringContext=*/true, 4205 /*AllowDestructorName=*/true, 4206 AllowConstructorName, 4207 ParsedType(), 4208 TemplateKWLoc, 4209 D.getName()) || 4210 // Once we're past the identifier, if the scope was bad, mark the 4211 // whole declarator bad. 4212 D.getCXXScopeSpec().isInvalid()) { 4213 D.SetIdentifier(0, Tok.getLocation()); 4214 D.setInvalidType(true); 4215 } else { 4216 // Parsed the unqualified-id; update range information and move along. 4217 if (D.getSourceRange().getBegin().isInvalid()) 4218 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 4219 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 4220 } 4221 goto PastIdentifier; 4222 } 4223 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 4224 assert(!getLangOpts().CPlusPlus && 4225 "There's a C++-specific check for tok::identifier above"); 4226 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 4227 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 4228 ConsumeToken(); 4229 goto PastIdentifier; 4230 } 4231 4232 if (Tok.is(tok::l_paren)) { 4233 // direct-declarator: '(' declarator ')' 4234 // direct-declarator: '(' attributes declarator ')' 4235 // Example: 'char (*X)' or 'int (*XX)(void)' 4236 ParseParenDeclarator(D); 4237 4238 // If the declarator was parenthesized, we entered the declarator 4239 // scope when parsing the parenthesized declarator, then exited 4240 // the scope already. Re-enter the scope, if we need to. 4241 if (D.getCXXScopeSpec().isSet()) { 4242 // If there was an error parsing parenthesized declarator, declarator 4243 // scope may have been entered before. Don't do it again. 4244 if (!D.isInvalidType() && 4245 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 4246 // Change the declaration context for name lookup, until this function 4247 // is exited (and the declarator has been parsed). 4248 DeclScopeObj.EnterDeclaratorScope(); 4249 } 4250 } else if (D.mayOmitIdentifier()) { 4251 // This could be something simple like "int" (in which case the declarator 4252 // portion is empty), if an abstract-declarator is allowed. 4253 D.SetIdentifier(0, Tok.getLocation()); 4254 } else { 4255 if (D.getContext() == Declarator::MemberContext) 4256 Diag(Tok, diag::err_expected_member_name_or_semi) 4257 << D.getDeclSpec().getSourceRange(); 4258 else if (getLangOpts().CPlusPlus) 4259 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; 4260 else 4261 Diag(Tok, diag::err_expected_ident_lparen); 4262 D.SetIdentifier(0, Tok.getLocation()); 4263 D.setInvalidType(true); 4264 } 4265 4266 PastIdentifier: 4267 assert(D.isPastIdentifier() && 4268 "Haven't past the location of the identifier yet?"); 4269 4270 // Don't parse attributes unless we have parsed an unparenthesized name. 4271 if (D.hasName() && !D.getNumTypeObjects()) 4272 MaybeParseCXX0XAttributes(D); 4273 4274 while (1) { 4275 if (Tok.is(tok::l_paren)) { 4276 // Enter function-declaration scope, limiting any declarators to the 4277 // function prototype scope, including parameter declarators. 4278 ParseScope PrototypeScope(this, 4279 Scope::FunctionPrototypeScope|Scope::DeclScope); 4280 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 4281 // In such a case, check if we actually have a function declarator; if it 4282 // is not, the declarator has been fully parsed. 4283 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 4284 // When not in file scope, warn for ambiguous function declarators, just 4285 // in case the author intended it as a variable definition. 4286 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 4287 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 4288 break; 4289 } 4290 ParsedAttributes attrs(AttrFactory); 4291 BalancedDelimiterTracker T(*this, tok::l_paren); 4292 T.consumeOpen(); 4293 ParseFunctionDeclarator(D, attrs, T); 4294 PrototypeScope.Exit(); 4295 } else if (Tok.is(tok::l_square)) { 4296 ParseBracketDeclarator(D); 4297 } else { 4298 break; 4299 } 4300 } 4301} 4302 4303/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 4304/// only called before the identifier, so these are most likely just grouping 4305/// parens for precedence. If we find that these are actually function 4306/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 4307/// 4308/// direct-declarator: 4309/// '(' declarator ')' 4310/// [GNU] '(' attributes declarator ')' 4311/// direct-declarator '(' parameter-type-list ')' 4312/// direct-declarator '(' identifier-list[opt] ')' 4313/// [GNU] direct-declarator '(' parameter-forward-declarations 4314/// parameter-type-list[opt] ')' 4315/// 4316void Parser::ParseParenDeclarator(Declarator &D) { 4317 BalancedDelimiterTracker T(*this, tok::l_paren); 4318 T.consumeOpen(); 4319 4320 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 4321 4322 // Eat any attributes before we look at whether this is a grouping or function 4323 // declarator paren. If this is a grouping paren, the attribute applies to 4324 // the type being built up, for example: 4325 // int (__attribute__(()) *x)(long y) 4326 // If this ends up not being a grouping paren, the attribute applies to the 4327 // first argument, for example: 4328 // int (__attribute__(()) int x) 4329 // In either case, we need to eat any attributes to be able to determine what 4330 // sort of paren this is. 4331 // 4332 ParsedAttributes attrs(AttrFactory); 4333 bool RequiresArg = false; 4334 if (Tok.is(tok::kw___attribute)) { 4335 ParseGNUAttributes(attrs); 4336 4337 // We require that the argument list (if this is a non-grouping paren) be 4338 // present even if the attribute list was empty. 4339 RequiresArg = true; 4340 } 4341 // Eat any Microsoft extensions. 4342 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 4343 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) || 4344 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) || 4345 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) { 4346 ParseMicrosoftTypeAttributes(attrs); 4347 } 4348 // Eat any Borland extensions. 4349 if (Tok.is(tok::kw___pascal)) 4350 ParseBorlandTypeAttributes(attrs); 4351 4352 // If we haven't past the identifier yet (or where the identifier would be 4353 // stored, if this is an abstract declarator), then this is probably just 4354 // grouping parens. However, if this could be an abstract-declarator, then 4355 // this could also be the start of function arguments (consider 'void()'). 4356 bool isGrouping; 4357 4358 if (!D.mayOmitIdentifier()) { 4359 // If this can't be an abstract-declarator, this *must* be a grouping 4360 // paren, because we haven't seen the identifier yet. 4361 isGrouping = true; 4362 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 4363 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) && 4364 NextToken().is(tok::r_paren)) || // C++ int(...) 4365 isDeclarationSpecifier() || // 'int(int)' is a function. 4366 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function. 4367 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 4368 // considered to be a type, not a K&R identifier-list. 4369 isGrouping = false; 4370 } else { 4371 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 4372 isGrouping = true; 4373 } 4374 4375 // If this is a grouping paren, handle: 4376 // direct-declarator: '(' declarator ')' 4377 // direct-declarator: '(' attributes declarator ')' 4378 if (isGrouping) { 4379 SourceLocation EllipsisLoc = D.getEllipsisLoc(); 4380 D.setEllipsisLoc(SourceLocation()); 4381 4382 bool hadGroupingParens = D.hasGroupingParens(); 4383 D.setGroupingParens(true); 4384 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 4385 // Match the ')'. 4386 T.consumeClose(); 4387 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(), 4388 T.getCloseLocation()), 4389 attrs, T.getCloseLocation()); 4390 4391 D.setGroupingParens(hadGroupingParens); 4392 4393 // An ellipsis cannot be placed outside parentheses. 4394 if (EllipsisLoc.isValid()) 4395 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc); 4396 4397 return; 4398 } 4399 4400 // Okay, if this wasn't a grouping paren, it must be the start of a function 4401 // argument list. Recognize that this declarator will never have an 4402 // identifier (and remember where it would have been), then call into 4403 // ParseFunctionDeclarator to handle of argument list. 4404 D.SetIdentifier(0, Tok.getLocation()); 4405 4406 // Enter function-declaration scope, limiting any declarators to the 4407 // function prototype scope, including parameter declarators. 4408 ParseScope PrototypeScope(this, 4409 Scope::FunctionPrototypeScope|Scope::DeclScope); 4410 ParseFunctionDeclarator(D, attrs, T, RequiresArg); 4411 PrototypeScope.Exit(); 4412} 4413 4414/// ParseFunctionDeclarator - We are after the identifier and have parsed the 4415/// declarator D up to a paren, which indicates that we are parsing function 4416/// arguments. 4417/// 4418/// If FirstArgAttrs is non-null, then the caller parsed those arguments 4419/// immediately after the open paren - they should be considered to be the 4420/// first argument of a parameter. 4421/// 4422/// If RequiresArg is true, then the first argument of the function is required 4423/// to be present and required to not be an identifier list. 4424/// 4425/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt], 4426/// (C++11) ref-qualifier[opt], exception-specification[opt], 4427/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt]. 4428/// 4429/// [C++11] exception-specification: 4430/// dynamic-exception-specification 4431/// noexcept-specification 4432/// 4433void Parser::ParseFunctionDeclarator(Declarator &D, 4434 ParsedAttributes &FirstArgAttrs, 4435 BalancedDelimiterTracker &Tracker, 4436 bool RequiresArg) { 4437 assert(getCurScope()->isFunctionPrototypeScope() && 4438 "Should call from a Function scope"); 4439 // lparen is already consumed! 4440 assert(D.isPastIdentifier() && "Should not call before identifier!"); 4441 4442 // This should be true when the function has typed arguments. 4443 // Otherwise, it is treated as a K&R-style function. 4444 bool HasProto = false; 4445 // Build up an array of information about the parsed arguments. 4446 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 4447 // Remember where we see an ellipsis, if any. 4448 SourceLocation EllipsisLoc; 4449 4450 DeclSpec DS(AttrFactory); 4451 bool RefQualifierIsLValueRef = true; 4452 SourceLocation RefQualifierLoc; 4453 SourceLocation ConstQualifierLoc; 4454 SourceLocation VolatileQualifierLoc; 4455 ExceptionSpecificationType ESpecType = EST_None; 4456 SourceRange ESpecRange; 4457 SmallVector<ParsedType, 2> DynamicExceptions; 4458 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4459 ExprResult NoexceptExpr; 4460 ParsedAttributes FnAttrs(AttrFactory); 4461 TypeResult TrailingReturnType; 4462 4463 Actions.ActOnStartFunctionDeclarator(); 4464 4465 SourceLocation EndLoc; 4466 if (isFunctionDeclaratorIdentifierList()) { 4467 if (RequiresArg) 4468 Diag(Tok, diag::err_argument_required_after_attribute); 4469 4470 ParseFunctionDeclaratorIdentifierList(D, ParamInfo); 4471 4472 Tracker.consumeClose(); 4473 EndLoc = Tracker.getCloseLocation(); 4474 } else { 4475 if (Tok.isNot(tok::r_paren)) 4476 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc); 4477 else if (RequiresArg) 4478 Diag(Tok, diag::err_argument_required_after_attribute); 4479 4480 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus; 4481 4482 // If we have the closing ')', eat it. 4483 Tracker.consumeClose(); 4484 EndLoc = Tracker.getCloseLocation(); 4485 4486 if (getLangOpts().CPlusPlus) { 4487 // FIXME: Accept these components in any order, and produce fixits to 4488 // correct the order if the user gets it wrong. Ideally we should deal 4489 // with the virt-specifier-seq and pure-specifier in the same way. 4490 4491 // Parse cv-qualifier-seq[opt]. 4492 ParseTypeQualifierListOpt(DS, false /*no attributes*/, false); 4493 if (!DS.getSourceRange().getEnd().isInvalid()) { 4494 EndLoc = DS.getSourceRange().getEnd(); 4495 ConstQualifierLoc = DS.getConstSpecLoc(); 4496 VolatileQualifierLoc = DS.getVolatileSpecLoc(); 4497 } 4498 4499 // Parse ref-qualifier[opt]. 4500 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 4501 Diag(Tok, getLangOpts().CPlusPlus0x ? 4502 diag::warn_cxx98_compat_ref_qualifier : 4503 diag::ext_ref_qualifier); 4504 4505 RefQualifierIsLValueRef = Tok.is(tok::amp); 4506 RefQualifierLoc = ConsumeToken(); 4507 EndLoc = RefQualifierLoc; 4508 } 4509 4510 // C++11 [expr.prim.general]p3: 4511 // If a declaration declares a member function or member function 4512 // template of a class X, the expression this is a prvalue of type 4513 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 4514 // and the end of the function-definition, member-declarator, or 4515 // declarator. 4516 bool IsCXX11MemberFunction = 4517 getLangOpts().CPlusPlus0x && 4518 (D.getContext() == Declarator::MemberContext || 4519 (D.getContext() == Declarator::FileContext && 4520 D.getCXXScopeSpec().isValid() && 4521 Actions.CurContext->isRecord())); 4522 Sema::CXXThisScopeRAII ThisScope(Actions, 4523 dyn_cast<CXXRecordDecl>(Actions.CurContext), 4524 DS.getTypeQualifiers(), 4525 IsCXX11MemberFunction); 4526 4527 // Parse exception-specification[opt]. 4528 ESpecType = tryParseExceptionSpecification(ESpecRange, 4529 DynamicExceptions, 4530 DynamicExceptionRanges, 4531 NoexceptExpr); 4532 if (ESpecType != EST_None) 4533 EndLoc = ESpecRange.getEnd(); 4534 4535 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes 4536 // after the exception-specification. 4537 MaybeParseCXX0XAttributes(FnAttrs); 4538 4539 // Parse trailing-return-type[opt]. 4540 if (getLangOpts().CPlusPlus0x && Tok.is(tok::arrow)) { 4541 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); 4542 SourceRange Range; 4543 TrailingReturnType = ParseTrailingReturnType(Range); 4544 if (Range.getEnd().isValid()) 4545 EndLoc = Range.getEnd(); 4546 } 4547 } 4548 } 4549 4550 // Remember that we parsed a function type, and remember the attributes. 4551 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto, 4552 /*isVariadic=*/EllipsisLoc.isValid(), 4553 EllipsisLoc, 4554 ParamInfo.data(), ParamInfo.size(), 4555 DS.getTypeQualifiers(), 4556 RefQualifierIsLValueRef, 4557 RefQualifierLoc, ConstQualifierLoc, 4558 VolatileQualifierLoc, 4559 /*MutableLoc=*/SourceLocation(), 4560 ESpecType, ESpecRange.getBegin(), 4561 DynamicExceptions.data(), 4562 DynamicExceptionRanges.data(), 4563 DynamicExceptions.size(), 4564 NoexceptExpr.isUsable() ? 4565 NoexceptExpr.get() : 0, 4566 Tracker.getOpenLocation(), 4567 EndLoc, D, 4568 TrailingReturnType), 4569 FnAttrs, EndLoc); 4570 4571 Actions.ActOnEndFunctionDeclarator(); 4572} 4573 4574/// isFunctionDeclaratorIdentifierList - This parameter list may have an 4575/// identifier list form for a K&R-style function: void foo(a,b,c) 4576/// 4577/// Note that identifier-lists are only allowed for normal declarators, not for 4578/// abstract-declarators. 4579bool Parser::isFunctionDeclaratorIdentifierList() { 4580 return !getLangOpts().CPlusPlus 4581 && Tok.is(tok::identifier) 4582 && !TryAltiVecVectorToken() 4583 // K&R identifier lists can't have typedefs as identifiers, per C99 4584 // 6.7.5.3p11. 4585 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) 4586 // Identifier lists follow a really simple grammar: the identifiers can 4587 // be followed *only* by a ", identifier" or ")". However, K&R 4588 // identifier lists are really rare in the brave new modern world, and 4589 // it is very common for someone to typo a type in a non-K&R style 4590 // list. If we are presented with something like: "void foo(intptr x, 4591 // float y)", we don't want to start parsing the function declarator as 4592 // though it is a K&R style declarator just because intptr is an 4593 // invalid type. 4594 // 4595 // To handle this, we check to see if the token after the first 4596 // identifier is a "," or ")". Only then do we parse it as an 4597 // identifier list. 4598 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)); 4599} 4600 4601/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 4602/// we found a K&R-style identifier list instead of a typed parameter list. 4603/// 4604/// After returning, ParamInfo will hold the parsed parameters. 4605/// 4606/// identifier-list: [C99 6.7.5] 4607/// identifier 4608/// identifier-list ',' identifier 4609/// 4610void Parser::ParseFunctionDeclaratorIdentifierList( 4611 Declarator &D, 4612 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) { 4613 // If there was no identifier specified for the declarator, either we are in 4614 // an abstract-declarator, or we are in a parameter declarator which was found 4615 // to be abstract. In abstract-declarators, identifier lists are not valid: 4616 // diagnose this. 4617 if (!D.getIdentifier()) 4618 Diag(Tok, diag::ext_ident_list_in_param); 4619 4620 // Maintain an efficient lookup of params we have seen so far. 4621 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 4622 4623 while (1) { 4624 // If this isn't an identifier, report the error and skip until ')'. 4625 if (Tok.isNot(tok::identifier)) { 4626 Diag(Tok, diag::err_expected_ident); 4627 SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true); 4628 // Forget we parsed anything. 4629 ParamInfo.clear(); 4630 return; 4631 } 4632 4633 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 4634 4635 // Reject 'typedef int y; int test(x, y)', but continue parsing. 4636 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 4637 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 4638 4639 // Verify that the argument identifier has not already been mentioned. 4640 if (!ParamsSoFar.insert(ParmII)) { 4641 Diag(Tok, diag::err_param_redefinition) << ParmII; 4642 } else { 4643 // Remember this identifier in ParamInfo. 4644 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 4645 Tok.getLocation(), 4646 0)); 4647 } 4648 4649 // Eat the identifier. 4650 ConsumeToken(); 4651 4652 // The list continues if we see a comma. 4653 if (Tok.isNot(tok::comma)) 4654 break; 4655 ConsumeToken(); 4656 } 4657} 4658 4659/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list 4660/// after the opening parenthesis. This function will not parse a K&R-style 4661/// identifier list. 4662/// 4663/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the 4664/// caller parsed those arguments immediately after the open paren - they should 4665/// be considered to be part of the first parameter. 4666/// 4667/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will 4668/// be the location of the ellipsis, if any was parsed. 4669/// 4670/// parameter-type-list: [C99 6.7.5] 4671/// parameter-list 4672/// parameter-list ',' '...' 4673/// [C++] parameter-list '...' 4674/// 4675/// parameter-list: [C99 6.7.5] 4676/// parameter-declaration 4677/// parameter-list ',' parameter-declaration 4678/// 4679/// parameter-declaration: [C99 6.7.5] 4680/// declaration-specifiers declarator 4681/// [C++] declaration-specifiers declarator '=' assignment-expression 4682/// [C++11] initializer-clause 4683/// [GNU] declaration-specifiers declarator attributes 4684/// declaration-specifiers abstract-declarator[opt] 4685/// [C++] declaration-specifiers abstract-declarator[opt] 4686/// '=' assignment-expression 4687/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 4688/// [C++11] attribute-specifier-seq parameter-declaration 4689/// 4690void Parser::ParseParameterDeclarationClause( 4691 Declarator &D, 4692 ParsedAttributes &FirstArgAttrs, 4693 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo, 4694 SourceLocation &EllipsisLoc) { 4695 4696 while (1) { 4697 if (Tok.is(tok::ellipsis)) { 4698 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq 4699 // before deciding this was a parameter-declaration-clause. 4700 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 4701 break; 4702 } 4703 4704 // Parse the declaration-specifiers. 4705 // Just use the ParsingDeclaration "scope" of the declarator. 4706 DeclSpec DS(AttrFactory); 4707 4708 // Parse any C++11 attributes. 4709 MaybeParseCXX0XAttributes(DS.getAttributes()); 4710 4711 // Skip any Microsoft attributes before a param. 4712 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) 4713 ParseMicrosoftAttributes(DS.getAttributes()); 4714 4715 SourceLocation DSStart = Tok.getLocation(); 4716 4717 // If the caller parsed attributes for the first argument, add them now. 4718 // Take them so that we only apply the attributes to the first parameter. 4719 // FIXME: If we can leave the attributes in the token stream somehow, we can 4720 // get rid of a parameter (FirstArgAttrs) and this statement. It might be 4721 // too much hassle. 4722 DS.takeAttributesFrom(FirstArgAttrs); 4723 4724 ParseDeclarationSpecifiers(DS); 4725 4726 // Parse the declarator. This is "PrototypeContext", because we must 4727 // accept either 'declarator' or 'abstract-declarator' here. 4728 Declarator ParmDecl(DS, Declarator::PrototypeContext); 4729 ParseDeclarator(ParmDecl); 4730 4731 // Parse GNU attributes, if present. 4732 MaybeParseGNUAttributes(ParmDecl); 4733 4734 // Remember this parsed parameter in ParamInfo. 4735 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 4736 4737 // DefArgToks is used when the parsing of default arguments needs 4738 // to be delayed. 4739 CachedTokens *DefArgToks = 0; 4740 4741 // If no parameter was specified, verify that *something* was specified, 4742 // otherwise we have a missing type and identifier. 4743 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 4744 ParmDecl.getNumTypeObjects() == 0) { 4745 // Completely missing, emit error. 4746 Diag(DSStart, diag::err_missing_param); 4747 } else { 4748 // Otherwise, we have something. Add it and let semantic analysis try 4749 // to grok it and add the result to the ParamInfo we are building. 4750 4751 // Inform the actions module about the parameter declarator, so it gets 4752 // added to the current scope. 4753 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 4754 4755 // Parse the default argument, if any. We parse the default 4756 // arguments in all dialects; the semantic analysis in 4757 // ActOnParamDefaultArgument will reject the default argument in 4758 // C. 4759 if (Tok.is(tok::equal)) { 4760 SourceLocation EqualLoc = Tok.getLocation(); 4761 4762 // Parse the default argument 4763 if (D.getContext() == Declarator::MemberContext) { 4764 // If we're inside a class definition, cache the tokens 4765 // corresponding to the default argument. We'll actually parse 4766 // them when we see the end of the class definition. 4767 // FIXME: Can we use a smart pointer for Toks? 4768 DefArgToks = new CachedTokens; 4769 4770 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 4771 /*StopAtSemi=*/true, 4772 /*ConsumeFinalToken=*/false)) { 4773 delete DefArgToks; 4774 DefArgToks = 0; 4775 Actions.ActOnParamDefaultArgumentError(Param); 4776 } else { 4777 // Mark the end of the default argument so that we know when to 4778 // stop when we parse it later on. 4779 Token DefArgEnd; 4780 DefArgEnd.startToken(); 4781 DefArgEnd.setKind(tok::cxx_defaultarg_end); 4782 DefArgEnd.setLocation(Tok.getLocation()); 4783 DefArgToks->push_back(DefArgEnd); 4784 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 4785 (*DefArgToks)[1].getLocation()); 4786 } 4787 } else { 4788 // Consume the '='. 4789 ConsumeToken(); 4790 4791 // The argument isn't actually potentially evaluated unless it is 4792 // used. 4793 EnterExpressionEvaluationContext Eval(Actions, 4794 Sema::PotentiallyEvaluatedIfUsed, 4795 Param); 4796 4797 ExprResult DefArgResult; 4798 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 4799 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 4800 DefArgResult = ParseBraceInitializer(); 4801 } else 4802 DefArgResult = ParseAssignmentExpression(); 4803 if (DefArgResult.isInvalid()) { 4804 Actions.ActOnParamDefaultArgumentError(Param); 4805 SkipUntil(tok::comma, tok::r_paren, true, true); 4806 } else { 4807 // Inform the actions module about the default argument 4808 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 4809 DefArgResult.take()); 4810 } 4811 } 4812 } 4813 4814 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 4815 ParmDecl.getIdentifierLoc(), Param, 4816 DefArgToks)); 4817 } 4818 4819 // If the next token is a comma, consume it and keep reading arguments. 4820 if (Tok.isNot(tok::comma)) { 4821 if (Tok.is(tok::ellipsis)) { 4822 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 4823 4824 if (!getLangOpts().CPlusPlus) { 4825 // We have ellipsis without a preceding ',', which is ill-formed 4826 // in C. Complain and provide the fix. 4827 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 4828 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 4829 } 4830 } 4831 4832 break; 4833 } 4834 4835 // Consume the comma. 4836 ConsumeToken(); 4837 } 4838 4839} 4840 4841/// [C90] direct-declarator '[' constant-expression[opt] ']' 4842/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 4843/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 4844/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 4845/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 4846/// [C++11] direct-declarator '[' constant-expression[opt] ']' 4847/// attribute-specifier-seq[opt] 4848void Parser::ParseBracketDeclarator(Declarator &D) { 4849 if (CheckProhibitedCXX11Attribute()) 4850 return; 4851 4852 BalancedDelimiterTracker T(*this, tok::l_square); 4853 T.consumeOpen(); 4854 4855 // C array syntax has many features, but by-far the most common is [] and [4]. 4856 // This code does a fast path to handle some of the most obvious cases. 4857 if (Tok.getKind() == tok::r_square) { 4858 T.consumeClose(); 4859 ParsedAttributes attrs(AttrFactory); 4860 MaybeParseCXX0XAttributes(attrs); 4861 4862 // Remember that we parsed the empty array type. 4863 ExprResult NumElements; 4864 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, 4865 T.getOpenLocation(), 4866 T.getCloseLocation()), 4867 attrs, T.getCloseLocation()); 4868 return; 4869 } else if (Tok.getKind() == tok::numeric_constant && 4870 GetLookAheadToken(1).is(tok::r_square)) { 4871 // [4] is very common. Parse the numeric constant expression. 4872 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope())); 4873 ConsumeToken(); 4874 4875 T.consumeClose(); 4876 ParsedAttributes attrs(AttrFactory); 4877 MaybeParseCXX0XAttributes(attrs); 4878 4879 // Remember that we parsed a array type, and remember its features. 4880 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, 4881 ExprRes.release(), 4882 T.getOpenLocation(), 4883 T.getCloseLocation()), 4884 attrs, T.getCloseLocation()); 4885 return; 4886 } 4887 4888 // If valid, this location is the position where we read the 'static' keyword. 4889 SourceLocation StaticLoc; 4890 if (Tok.is(tok::kw_static)) 4891 StaticLoc = ConsumeToken(); 4892 4893 // If there is a type-qualifier-list, read it now. 4894 // Type qualifiers in an array subscript are a C99 feature. 4895 DeclSpec DS(AttrFactory); 4896 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 4897 4898 // If we haven't already read 'static', check to see if there is one after the 4899 // type-qualifier-list. 4900 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 4901 StaticLoc = ConsumeToken(); 4902 4903 // Handle "direct-declarator [ type-qual-list[opt] * ]". 4904 bool isStar = false; 4905 ExprResult NumElements; 4906 4907 // Handle the case where we have '[*]' as the array size. However, a leading 4908 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 4909 // the the token after the star is a ']'. Since stars in arrays are 4910 // infrequent, use of lookahead is not costly here. 4911 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 4912 ConsumeToken(); // Eat the '*'. 4913 4914 if (StaticLoc.isValid()) { 4915 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 4916 StaticLoc = SourceLocation(); // Drop the static. 4917 } 4918 isStar = true; 4919 } else if (Tok.isNot(tok::r_square)) { 4920 // Note, in C89, this production uses the constant-expr production instead 4921 // of assignment-expr. The only difference is that assignment-expr allows 4922 // things like '=' and '*='. Sema rejects these in C89 mode because they 4923 // are not i-c-e's, so we don't need to distinguish between the two here. 4924 4925 // Parse the constant-expression or assignment-expression now (depending 4926 // on dialect). 4927 if (getLangOpts().CPlusPlus) { 4928 NumElements = ParseConstantExpression(); 4929 } else { 4930 EnterExpressionEvaluationContext Unevaluated(Actions, 4931 Sema::ConstantEvaluated); 4932 NumElements = ParseAssignmentExpression(); 4933 } 4934 } 4935 4936 // If there was an error parsing the assignment-expression, recover. 4937 if (NumElements.isInvalid()) { 4938 D.setInvalidType(true); 4939 // If the expression was invalid, skip it. 4940 SkipUntil(tok::r_square); 4941 return; 4942 } 4943 4944 T.consumeClose(); 4945 4946 ParsedAttributes attrs(AttrFactory); 4947 MaybeParseCXX0XAttributes(attrs); 4948 4949 // Remember that we parsed a array type, and remember its features. 4950 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 4951 StaticLoc.isValid(), isStar, 4952 NumElements.release(), 4953 T.getOpenLocation(), 4954 T.getCloseLocation()), 4955 attrs, T.getCloseLocation()); 4956} 4957 4958/// [GNU] typeof-specifier: 4959/// typeof ( expressions ) 4960/// typeof ( type-name ) 4961/// [GNU/C++] typeof unary-expression 4962/// 4963void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 4964 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 4965 Token OpTok = Tok; 4966 SourceLocation StartLoc = ConsumeToken(); 4967 4968 const bool hasParens = Tok.is(tok::l_paren); 4969 4970 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 4971 4972 bool isCastExpr; 4973 ParsedType CastTy; 4974 SourceRange CastRange; 4975 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, 4976 CastTy, CastRange); 4977 if (hasParens) 4978 DS.setTypeofParensRange(CastRange); 4979 4980 if (CastRange.getEnd().isInvalid()) 4981 // FIXME: Not accurate, the range gets one token more than it should. 4982 DS.SetRangeEnd(Tok.getLocation()); 4983 else 4984 DS.SetRangeEnd(CastRange.getEnd()); 4985 4986 if (isCastExpr) { 4987 if (!CastTy) { 4988 DS.SetTypeSpecError(); 4989 return; 4990 } 4991 4992 const char *PrevSpec = 0; 4993 unsigned DiagID; 4994 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 4995 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 4996 DiagID, CastTy)) 4997 Diag(StartLoc, DiagID) << PrevSpec; 4998 return; 4999 } 5000 5001 // If we get here, the operand to the typeof was an expresion. 5002 if (Operand.isInvalid()) { 5003 DS.SetTypeSpecError(); 5004 return; 5005 } 5006 5007 // We might need to transform the operand if it is potentially evaluated. 5008 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); 5009 if (Operand.isInvalid()) { 5010 DS.SetTypeSpecError(); 5011 return; 5012 } 5013 5014 const char *PrevSpec = 0; 5015 unsigned DiagID; 5016 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 5017 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 5018 DiagID, Operand.get())) 5019 Diag(StartLoc, DiagID) << PrevSpec; 5020} 5021 5022/// [C11] atomic-specifier: 5023/// _Atomic ( type-name ) 5024/// 5025void Parser::ParseAtomicSpecifier(DeclSpec &DS) { 5026 assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier"); 5027 5028 SourceLocation StartLoc = ConsumeToken(); 5029 BalancedDelimiterTracker T(*this, tok::l_paren); 5030 if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) { 5031 SkipUntil(tok::r_paren); 5032 return; 5033 } 5034 5035 TypeResult Result = ParseTypeName(); 5036 if (Result.isInvalid()) { 5037 SkipUntil(tok::r_paren); 5038 return; 5039 } 5040 5041 // Match the ')' 5042 T.consumeClose(); 5043 5044 if (T.getCloseLocation().isInvalid()) 5045 return; 5046 5047 DS.setTypeofParensRange(T.getRange()); 5048 DS.SetRangeEnd(T.getCloseLocation()); 5049 5050 const char *PrevSpec = 0; 5051 unsigned DiagID; 5052 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, 5053 DiagID, Result.release())) 5054 Diag(StartLoc, DiagID) << PrevSpec; 5055} 5056 5057 5058/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 5059/// from TryAltiVecVectorToken. 5060bool Parser::TryAltiVecVectorTokenOutOfLine() { 5061 Token Next = NextToken(); 5062 switch (Next.getKind()) { 5063 default: return false; 5064 case tok::kw_short: 5065 case tok::kw_long: 5066 case tok::kw_signed: 5067 case tok::kw_unsigned: 5068 case tok::kw_void: 5069 case tok::kw_char: 5070 case tok::kw_int: 5071 case tok::kw_float: 5072 case tok::kw_double: 5073 case tok::kw_bool: 5074 case tok::kw___pixel: 5075 Tok.setKind(tok::kw___vector); 5076 return true; 5077 case tok::identifier: 5078 if (Next.getIdentifierInfo() == Ident_pixel) { 5079 Tok.setKind(tok::kw___vector); 5080 return true; 5081 } 5082 return false; 5083 } 5084} 5085 5086bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 5087 const char *&PrevSpec, unsigned &DiagID, 5088 bool &isInvalid) { 5089 if (Tok.getIdentifierInfo() == Ident_vector) { 5090 Token Next = NextToken(); 5091 switch (Next.getKind()) { 5092 case tok::kw_short: 5093 case tok::kw_long: 5094 case tok::kw_signed: 5095 case tok::kw_unsigned: 5096 case tok::kw_void: 5097 case tok::kw_char: 5098 case tok::kw_int: 5099 case tok::kw_float: 5100 case tok::kw_double: 5101 case tok::kw_bool: 5102 case tok::kw___pixel: 5103 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 5104 return true; 5105 case tok::identifier: 5106 if (Next.getIdentifierInfo() == Ident_pixel) { 5107 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 5108 return true; 5109 } 5110 break; 5111 default: 5112 break; 5113 } 5114 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 5115 DS.isTypeAltiVecVector()) { 5116 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 5117 return true; 5118 } 5119 return false; 5120} 5121