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