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