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