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