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