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