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