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