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