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" 27 using 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++. 38 TypeResult 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. 70 static 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 114 void 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. 182 static 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. 190 void 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. 338 void 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. 361 bool 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. 384 void 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 545 void 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 599 void 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 Tok.is(tok::kw___sptr) || Tok.is(tok::kw___uptr)) { 606 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 607 SourceLocation AttrNameLoc = ConsumeToken(); 608 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 609 SourceLocation(), 0, 0, AttributeList::AS_Keyword); 610 } 611 } 612 613 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { 614 // Treat these like attributes 615 while (Tok.is(tok::kw___pascal)) { 616 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 617 SourceLocation AttrNameLoc = ConsumeToken(); 618 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 619 SourceLocation(), 0, 0, AttributeList::AS_Keyword); 620 } 621 } 622 623 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) { 624 // Treat these like attributes 625 while (Tok.is(tok::kw___kernel)) { 626 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 627 SourceLocation AttrNameLoc = ConsumeToken(); 628 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 629 SourceLocation(), 0, 0, AttributeList::AS_Keyword); 630 } 631 } 632 633 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) { 634 // FIXME: The mapping from attribute spelling to semantics should be 635 // performed in Sema, not here. 636 SourceLocation Loc = Tok.getLocation(); 637 switch(Tok.getKind()) { 638 // OpenCL qualifiers: 639 case tok::kw___private: 640 case tok::kw_private: 641 DS.getAttributes().addNewInteger( 642 Actions.getASTContext(), 643 PP.getIdentifierInfo("address_space"), Loc, 0); 644 break; 645 646 case tok::kw___global: 647 DS.getAttributes().addNewInteger( 648 Actions.getASTContext(), 649 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global); 650 break; 651 652 case tok::kw___local: 653 DS.getAttributes().addNewInteger( 654 Actions.getASTContext(), 655 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local); 656 break; 657 658 case tok::kw___constant: 659 DS.getAttributes().addNewInteger( 660 Actions.getASTContext(), 661 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant); 662 break; 663 664 case tok::kw___read_only: 665 DS.getAttributes().addNewInteger( 666 Actions.getASTContext(), 667 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only); 668 break; 669 670 case tok::kw___write_only: 671 DS.getAttributes().addNewInteger( 672 Actions.getASTContext(), 673 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only); 674 break; 675 676 case tok::kw___read_write: 677 DS.getAttributes().addNewInteger( 678 Actions.getASTContext(), 679 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write); 680 break; 681 default: break; 682 } 683 } 684 685 /// \brief Parse a version number. 686 /// 687 /// version: 688 /// simple-integer 689 /// simple-integer ',' simple-integer 690 /// simple-integer ',' simple-integer ',' simple-integer 691 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { 692 Range = Tok.getLocation(); 693 694 if (!Tok.is(tok::numeric_constant)) { 695 Diag(Tok, diag::err_expected_version); 696 SkipUntil(tok::comma, tok::r_paren, true, true, true); 697 return VersionTuple(); 698 } 699 700 // Parse the major (and possibly minor and subminor) versions, which 701 // are stored in the numeric constant. We utilize a quirk of the 702 // lexer, which is that it handles something like 1.2.3 as a single 703 // numeric constant, rather than two separate tokens. 704 SmallString<512> Buffer; 705 Buffer.resize(Tok.getLength()+1); 706 const char *ThisTokBegin = &Buffer[0]; 707 708 // Get the spelling of the token, which eliminates trigraphs, etc. 709 bool Invalid = false; 710 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 711 if (Invalid) 712 return VersionTuple(); 713 714 // Parse the major version. 715 unsigned AfterMajor = 0; 716 unsigned Major = 0; 717 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) { 718 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0'; 719 ++AfterMajor; 720 } 721 722 if (AfterMajor == 0) { 723 Diag(Tok, diag::err_expected_version); 724 SkipUntil(tok::comma, tok::r_paren, true, true, true); 725 return VersionTuple(); 726 } 727 728 if (AfterMajor == ActualLength) { 729 ConsumeToken(); 730 731 // We only had a single version component. 732 if (Major == 0) { 733 Diag(Tok, diag::err_zero_version); 734 return VersionTuple(); 735 } 736 737 return VersionTuple(Major); 738 } 739 740 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) { 741 Diag(Tok, diag::err_expected_version); 742 SkipUntil(tok::comma, tok::r_paren, true, true, true); 743 return VersionTuple(); 744 } 745 746 // Parse the minor version. 747 unsigned AfterMinor = AfterMajor + 1; 748 unsigned Minor = 0; 749 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) { 750 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0'; 751 ++AfterMinor; 752 } 753 754 if (AfterMinor == ActualLength) { 755 ConsumeToken(); 756 757 // We had major.minor. 758 if (Major == 0 && Minor == 0) { 759 Diag(Tok, diag::err_zero_version); 760 return VersionTuple(); 761 } 762 763 return VersionTuple(Major, Minor); 764 } 765 766 // If what follows is not a '.', we have a problem. 767 if (ThisTokBegin[AfterMinor] != '.') { 768 Diag(Tok, diag::err_expected_version); 769 SkipUntil(tok::comma, tok::r_paren, true, true, true); 770 return VersionTuple(); 771 } 772 773 // Parse the subminor version. 774 unsigned AfterSubminor = AfterMinor + 1; 775 unsigned Subminor = 0; 776 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) { 777 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0'; 778 ++AfterSubminor; 779 } 780 781 if (AfterSubminor != ActualLength) { 782 Diag(Tok, diag::err_expected_version); 783 SkipUntil(tok::comma, tok::r_paren, true, true, true); 784 return VersionTuple(); 785 } 786 ConsumeToken(); 787 return VersionTuple(Major, Minor, Subminor); 788 } 789 790 /// \brief Parse the contents of the "availability" attribute. 791 /// 792 /// availability-attribute: 793 /// 'availability' '(' platform ',' version-arg-list, opt-message')' 794 /// 795 /// platform: 796 /// identifier 797 /// 798 /// version-arg-list: 799 /// version-arg 800 /// version-arg ',' version-arg-list 801 /// 802 /// version-arg: 803 /// 'introduced' '=' version 804 /// 'deprecated' '=' version 805 /// 'obsoleted' = version 806 /// 'unavailable' 807 /// opt-message: 808 /// 'message' '=' <string> 809 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, 810 SourceLocation AvailabilityLoc, 811 ParsedAttributes &attrs, 812 SourceLocation *endLoc) { 813 SourceLocation PlatformLoc; 814 IdentifierInfo *Platform = 0; 815 816 enum { Introduced, Deprecated, Obsoleted, Unknown }; 817 AvailabilityChange Changes[Unknown]; 818 ExprResult MessageExpr; 819 820 // Opening '('. 821 BalancedDelimiterTracker T(*this, tok::l_paren); 822 if (T.consumeOpen()) { 823 Diag(Tok, diag::err_expected_lparen); 824 return; 825 } 826 827 // Parse the platform name, 828 if (Tok.isNot(tok::identifier)) { 829 Diag(Tok, diag::err_availability_expected_platform); 830 SkipUntil(tok::r_paren); 831 return; 832 } 833 Platform = Tok.getIdentifierInfo(); 834 PlatformLoc = ConsumeToken(); 835 836 // Parse the ',' following the platform name. 837 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren)) 838 return; 839 840 // If we haven't grabbed the pointers for the identifiers 841 // "introduced", "deprecated", and "obsoleted", do so now. 842 if (!Ident_introduced) { 843 Ident_introduced = PP.getIdentifierInfo("introduced"); 844 Ident_deprecated = PP.getIdentifierInfo("deprecated"); 845 Ident_obsoleted = PP.getIdentifierInfo("obsoleted"); 846 Ident_unavailable = PP.getIdentifierInfo("unavailable"); 847 Ident_message = PP.getIdentifierInfo("message"); 848 } 849 850 // Parse the set of introductions/deprecations/removals. 851 SourceLocation UnavailableLoc; 852 do { 853 if (Tok.isNot(tok::identifier)) { 854 Diag(Tok, diag::err_availability_expected_change); 855 SkipUntil(tok::r_paren); 856 return; 857 } 858 IdentifierInfo *Keyword = Tok.getIdentifierInfo(); 859 SourceLocation KeywordLoc = ConsumeToken(); 860 861 if (Keyword == Ident_unavailable) { 862 if (UnavailableLoc.isValid()) { 863 Diag(KeywordLoc, diag::err_availability_redundant) 864 << Keyword << SourceRange(UnavailableLoc); 865 } 866 UnavailableLoc = KeywordLoc; 867 868 if (Tok.isNot(tok::comma)) 869 break; 870 871 ConsumeToken(); 872 continue; 873 } 874 875 if (Tok.isNot(tok::equal)) { 876 Diag(Tok, diag::err_expected_equal_after) 877 << Keyword; 878 SkipUntil(tok::r_paren); 879 return; 880 } 881 ConsumeToken(); 882 if (Keyword == Ident_message) { 883 if (!isTokenStringLiteral()) { 884 Diag(Tok, diag::err_expected_string_literal) 885 << /*Source='availability attribute'*/2; 886 SkipUntil(tok::r_paren); 887 return; 888 } 889 MessageExpr = ParseStringLiteralExpression(); 890 break; 891 } 892 893 SourceRange VersionRange; 894 VersionTuple Version = ParseVersionTuple(VersionRange); 895 896 if (Version.empty()) { 897 SkipUntil(tok::r_paren); 898 return; 899 } 900 901 unsigned Index; 902 if (Keyword == Ident_introduced) 903 Index = Introduced; 904 else if (Keyword == Ident_deprecated) 905 Index = Deprecated; 906 else if (Keyword == Ident_obsoleted) 907 Index = Obsoleted; 908 else 909 Index = Unknown; 910 911 if (Index < Unknown) { 912 if (!Changes[Index].KeywordLoc.isInvalid()) { 913 Diag(KeywordLoc, diag::err_availability_redundant) 914 << Keyword 915 << SourceRange(Changes[Index].KeywordLoc, 916 Changes[Index].VersionRange.getEnd()); 917 } 918 919 Changes[Index].KeywordLoc = KeywordLoc; 920 Changes[Index].Version = Version; 921 Changes[Index].VersionRange = VersionRange; 922 } else { 923 Diag(KeywordLoc, diag::err_availability_unknown_change) 924 << Keyword << VersionRange; 925 } 926 927 if (Tok.isNot(tok::comma)) 928 break; 929 930 ConsumeToken(); 931 } while (true); 932 933 // Closing ')'. 934 if (T.consumeClose()) 935 return; 936 937 if (endLoc) 938 *endLoc = T.getCloseLocation(); 939 940 // The 'unavailable' availability cannot be combined with any other 941 // availability changes. Make sure that hasn't happened. 942 if (UnavailableLoc.isValid()) { 943 bool Complained = false; 944 for (unsigned Index = Introduced; Index != Unknown; ++Index) { 945 if (Changes[Index].KeywordLoc.isValid()) { 946 if (!Complained) { 947 Diag(UnavailableLoc, diag::warn_availability_and_unavailable) 948 << SourceRange(Changes[Index].KeywordLoc, 949 Changes[Index].VersionRange.getEnd()); 950 Complained = true; 951 } 952 953 // Clear out the availability. 954 Changes[Index] = AvailabilityChange(); 955 } 956 } 957 } 958 959 // Record this attribute 960 attrs.addNew(&Availability, 961 SourceRange(AvailabilityLoc, T.getCloseLocation()), 962 0, AvailabilityLoc, 963 Platform, PlatformLoc, 964 Changes[Introduced], 965 Changes[Deprecated], 966 Changes[Obsoleted], 967 UnavailableLoc, MessageExpr.take(), 968 AttributeList::AS_GNU); 969 } 970 971 972 // Late Parsed Attributes: 973 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods 974 975 void Parser::LateParsedDeclaration::ParseLexedAttributes() {} 976 977 void Parser::LateParsedClass::ParseLexedAttributes() { 978 Self->ParseLexedAttributes(*Class); 979 } 980 981 void Parser::LateParsedAttribute::ParseLexedAttributes() { 982 Self->ParseLexedAttribute(*this, true, false); 983 } 984 985 /// Wrapper class which calls ParseLexedAttribute, after setting up the 986 /// scope appropriately. 987 void Parser::ParseLexedAttributes(ParsingClass &Class) { 988 // Deal with templates 989 // FIXME: Test cases to make sure this does the right thing for templates. 990 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; 991 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, 992 HasTemplateScope); 993 if (HasTemplateScope) 994 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); 995 996 // Set or update the scope flags. 997 bool AlreadyHasClassScope = Class.TopLevelClass; 998 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; 999 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); 1000 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); 1001 1002 // Enter the scope of nested classes 1003 if (!AlreadyHasClassScope) 1004 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), 1005 Class.TagOrTemplate); 1006 if (!Class.LateParsedDeclarations.empty()) { 1007 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){ 1008 Class.LateParsedDeclarations[i]->ParseLexedAttributes(); 1009 } 1010 } 1011 1012 if (!AlreadyHasClassScope) 1013 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), 1014 Class.TagOrTemplate); 1015 } 1016 1017 1018 /// \brief Parse all attributes in LAs, and attach them to Decl D. 1019 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 1020 bool EnterScope, bool OnDefinition) { 1021 assert(LAs.parseSoon() && 1022 "Attribute list should be marked for immediate parsing."); 1023 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) { 1024 if (D) 1025 LAs[i]->addDecl(D); 1026 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition); 1027 delete LAs[i]; 1028 } 1029 LAs.clear(); 1030 } 1031 1032 1033 /// \brief Finish parsing an attribute for which parsing was delayed. 1034 /// This will be called at the end of parsing a class declaration 1035 /// for each LateParsedAttribute. We consume the saved tokens and 1036 /// create an attribute with the arguments filled in. We add this 1037 /// to the Attribute list for the decl. 1038 void Parser::ParseLexedAttribute(LateParsedAttribute &LA, 1039 bool EnterScope, bool OnDefinition) { 1040 // Save the current token position. 1041 SourceLocation OrigLoc = Tok.getLocation(); 1042 1043 // Append the current token at the end of the new token stream so that it 1044 // doesn't get lost. 1045 LA.Toks.push_back(Tok); 1046 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false); 1047 // Consume the previously pushed token. 1048 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1049 1050 if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) { 1051 // FIXME: Do not warn on C++11 attributes, once we start supporting 1052 // them here. 1053 Diag(Tok, diag::warn_attribute_on_function_definition) 1054 << LA.AttrName.getName(); 1055 } 1056 1057 ParsedAttributes Attrs(AttrFactory); 1058 SourceLocation endLoc; 1059 1060 if (LA.Decls.size() > 0) { 1061 Decl *D = LA.Decls[0]; 1062 NamedDecl *ND = dyn_cast<NamedDecl>(D); 1063 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); 1064 1065 // Allow 'this' within late-parsed attributes. 1066 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0, 1067 ND && 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 1120 bool 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). 1155 void 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 1191 void 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. 1263 bool 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. 1293 void 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 1308 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) { 1309 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) 1310 << attrs.Range; 1311 } 1312 1313 void 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 /// 1341 Parser::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. 1407 Parser::DeclGroupPtrTy 1408 Parser::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. 1436 bool 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. 1503 void 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. 1582 Parser::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. 1743 bool 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 /// 1783 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D, 1784 const ParsedTemplateInfo &TemplateInfo) { 1785 if (ParseAsmAttributesAfterDeclarator(D)) 1786 return 0; 1787 1788 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); 1789 } 1790 1791 Decl *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 /// 1945 void 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 /// 2011 static 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 /// 2027 bool 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. 2212 Parser::DeclSpecContext 2213 Parser::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] 2232 ExprResult 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] ')' 2258 void 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 /// 2315 void 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___sptr: 2715 case tok::kw___uptr: 2716 case tok::kw___ptr64: 2717 case tok::kw___ptr32: 2718 case tok::kw___w64: 2719 case tok::kw___cdecl: 2720 case tok::kw___stdcall: 2721 case tok::kw___fastcall: 2722 case tok::kw___thiscall: 2723 case tok::kw___unaligned: 2724 ParseMicrosoftTypeAttributes(DS.getAttributes()); 2725 continue; 2726 2727 // Borland single token adornments. 2728 case tok::kw___pascal: 2729 ParseBorlandTypeAttributes(DS.getAttributes()); 2730 continue; 2731 2732 // OpenCL single token adornments. 2733 case tok::kw___kernel: 2734 ParseOpenCLAttributes(DS.getAttributes()); 2735 continue; 2736 2737 // storage-class-specifier 2738 case tok::kw_typedef: 2739 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc, 2740 PrevSpec, DiagID); 2741 break; 2742 case tok::kw_extern: 2743 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) 2744 Diag(Tok, diag::ext_thread_before) << "extern"; 2745 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc, 2746 PrevSpec, DiagID); 2747 break; 2748 case tok::kw___private_extern__: 2749 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern, 2750 Loc, PrevSpec, DiagID); 2751 break; 2752 case tok::kw_static: 2753 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) 2754 Diag(Tok, diag::ext_thread_before) << "static"; 2755 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc, 2756 PrevSpec, DiagID); 2757 break; 2758 case tok::kw_auto: 2759 if (getLangOpts().CPlusPlus11) { 2760 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 2761 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 2762 PrevSpec, DiagID); 2763 if (!isInvalid) 2764 Diag(Tok, diag::ext_auto_storage_class) 2765 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 2766 } else 2767 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 2768 DiagID); 2769 } else 2770 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, 2771 PrevSpec, DiagID); 2772 break; 2773 case tok::kw_register: 2774 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc, 2775 PrevSpec, DiagID); 2776 break; 2777 case tok::kw_mutable: 2778 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc, 2779 PrevSpec, DiagID); 2780 break; 2781 case tok::kw___thread: 2782 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc, 2783 PrevSpec, DiagID); 2784 break; 2785 case tok::kw_thread_local: 2786 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc, 2787 PrevSpec, DiagID); 2788 break; 2789 case tok::kw__Thread_local: 2790 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local, 2791 Loc, PrevSpec, DiagID); 2792 break; 2793 2794 // function-specifier 2795 case tok::kw_inline: 2796 isInvalid = DS.setFunctionSpecInline(Loc); 2797 break; 2798 case tok::kw_virtual: 2799 isInvalid = DS.setFunctionSpecVirtual(Loc); 2800 break; 2801 case tok::kw_explicit: 2802 isInvalid = DS.setFunctionSpecExplicit(Loc); 2803 break; 2804 case tok::kw__Noreturn: 2805 if (!getLangOpts().C11) 2806 Diag(Loc, diag::ext_c11_noreturn); 2807 isInvalid = DS.setFunctionSpecNoreturn(Loc); 2808 break; 2809 2810 // alignment-specifier 2811 case tok::kw__Alignas: 2812 if (!getLangOpts().C11) 2813 Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); 2814 ParseAlignmentSpecifier(DS.getAttributes()); 2815 continue; 2816 2817 // friend 2818 case tok::kw_friend: 2819 if (DSContext == DSC_class) 2820 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 2821 else { 2822 PrevSpec = ""; // not actually used by the diagnostic 2823 DiagID = diag::err_friend_invalid_in_context; 2824 isInvalid = true; 2825 } 2826 break; 2827 2828 // Modules 2829 case tok::kw___module_private__: 2830 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID); 2831 break; 2832 2833 // constexpr 2834 case tok::kw_constexpr: 2835 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 2836 break; 2837 2838 // type-specifier 2839 case tok::kw_short: 2840 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 2841 DiagID); 2842 break; 2843 case tok::kw_long: 2844 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 2845 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 2846 DiagID); 2847 else 2848 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 2849 DiagID); 2850 break; 2851 case tok::kw___int64: 2852 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 2853 DiagID); 2854 break; 2855 case tok::kw_signed: 2856 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 2857 DiagID); 2858 break; 2859 case tok::kw_unsigned: 2860 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 2861 DiagID); 2862 break; 2863 case tok::kw__Complex: 2864 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 2865 DiagID); 2866 break; 2867 case tok::kw__Imaginary: 2868 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 2869 DiagID); 2870 break; 2871 case tok::kw_void: 2872 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 2873 DiagID); 2874 break; 2875 case tok::kw_char: 2876 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 2877 DiagID); 2878 break; 2879 case tok::kw_int: 2880 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 2881 DiagID); 2882 break; 2883 case tok::kw___int128: 2884 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, 2885 DiagID); 2886 break; 2887 case tok::kw_half: 2888 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, 2889 DiagID); 2890 break; 2891 case tok::kw_float: 2892 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 2893 DiagID); 2894 break; 2895 case tok::kw_double: 2896 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 2897 DiagID); 2898 break; 2899 case tok::kw_wchar_t: 2900 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 2901 DiagID); 2902 break; 2903 case tok::kw_char16_t: 2904 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 2905 DiagID); 2906 break; 2907 case tok::kw_char32_t: 2908 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 2909 DiagID); 2910 break; 2911 case tok::kw_bool: 2912 case tok::kw__Bool: 2913 if (Tok.is(tok::kw_bool) && 2914 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 2915 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 2916 PrevSpec = ""; // Not used by the diagnostic. 2917 DiagID = diag::err_bool_redeclaration; 2918 // For better error recovery. 2919 Tok.setKind(tok::identifier); 2920 isInvalid = true; 2921 } else { 2922 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 2923 DiagID); 2924 } 2925 break; 2926 case tok::kw__Decimal32: 2927 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 2928 DiagID); 2929 break; 2930 case tok::kw__Decimal64: 2931 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 2932 DiagID); 2933 break; 2934 case tok::kw__Decimal128: 2935 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 2936 DiagID); 2937 break; 2938 case tok::kw___vector: 2939 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 2940 break; 2941 case tok::kw___pixel: 2942 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 2943 break; 2944 case tok::kw_image1d_t: 2945 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_t, Loc, 2946 PrevSpec, DiagID); 2947 break; 2948 case tok::kw_image1d_array_t: 2949 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_array_t, Loc, 2950 PrevSpec, DiagID); 2951 break; 2952 case tok::kw_image1d_buffer_t: 2953 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_buffer_t, Loc, 2954 PrevSpec, DiagID); 2955 break; 2956 case tok::kw_image2d_t: 2957 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_t, Loc, 2958 PrevSpec, DiagID); 2959 break; 2960 case tok::kw_image2d_array_t: 2961 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_array_t, Loc, 2962 PrevSpec, DiagID); 2963 break; 2964 case tok::kw_image3d_t: 2965 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image3d_t, Loc, 2966 PrevSpec, DiagID); 2967 break; 2968 case tok::kw_sampler_t: 2969 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_sampler_t, Loc, 2970 PrevSpec, DiagID); 2971 break; 2972 case tok::kw_event_t: 2973 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_event_t, Loc, 2974 PrevSpec, DiagID); 2975 break; 2976 case tok::kw___unknown_anytype: 2977 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 2978 PrevSpec, DiagID); 2979 break; 2980 2981 // class-specifier: 2982 case tok::kw_class: 2983 case tok::kw_struct: 2984 case tok::kw___interface: 2985 case tok::kw_union: { 2986 tok::TokenKind Kind = Tok.getKind(); 2987 ConsumeToken(); 2988 2989 // These are attributes following class specifiers. 2990 // To produce better diagnostic, we parse them when 2991 // parsing class specifier. 2992 ParsedAttributesWithRange Attributes(AttrFactory); 2993 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, 2994 EnteringContext, DSContext, Attributes); 2995 2996 // If there are attributes following class specifier, 2997 // take them over and handle them here. 2998 if (!Attributes.empty()) { 2999 AttrsLastTime = true; 3000 attrs.takeAllFrom(Attributes); 3001 } 3002 continue; 3003 } 3004 3005 // enum-specifier: 3006 case tok::kw_enum: 3007 ConsumeToken(); 3008 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext); 3009 continue; 3010 3011 // cv-qualifier: 3012 case tok::kw_const: 3013 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 3014 getLangOpts()); 3015 break; 3016 case tok::kw_volatile: 3017 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 3018 getLangOpts()); 3019 break; 3020 case tok::kw_restrict: 3021 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 3022 getLangOpts()); 3023 break; 3024 3025 // C++ typename-specifier: 3026 case tok::kw_typename: 3027 if (TryAnnotateTypeOrScopeToken()) { 3028 DS.SetTypeSpecError(); 3029 goto DoneWithDeclSpec; 3030 } 3031 if (!Tok.is(tok::kw_typename)) 3032 continue; 3033 break; 3034 3035 // GNU typeof support. 3036 case tok::kw_typeof: 3037 ParseTypeofSpecifier(DS); 3038 continue; 3039 3040 case tok::annot_decltype: 3041 ParseDecltypeSpecifier(DS); 3042 continue; 3043 3044 case tok::kw___underlying_type: 3045 ParseUnderlyingTypeSpecifier(DS); 3046 continue; 3047 3048 case tok::kw__Atomic: 3049 // C11 6.7.2.4/4: 3050 // If the _Atomic keyword is immediately followed by a left parenthesis, 3051 // it is interpreted as a type specifier (with a type name), not as a 3052 // type qualifier. 3053 if (NextToken().is(tok::l_paren)) { 3054 ParseAtomicSpecifier(DS); 3055 continue; 3056 } 3057 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 3058 getLangOpts()); 3059 break; 3060 3061 // OpenCL qualifiers: 3062 case tok::kw_private: 3063 if (!getLangOpts().OpenCL) 3064 goto DoneWithDeclSpec; 3065 case tok::kw___private: 3066 case tok::kw___global: 3067 case tok::kw___local: 3068 case tok::kw___constant: 3069 case tok::kw___read_only: 3070 case tok::kw___write_only: 3071 case tok::kw___read_write: 3072 ParseOpenCLQualifiers(DS); 3073 break; 3074 3075 case tok::less: 3076 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 3077 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 3078 // but we support it. 3079 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1) 3080 goto DoneWithDeclSpec; 3081 3082 if (!ParseObjCProtocolQualifiers(DS)) 3083 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 3084 << FixItHint::CreateInsertion(Loc, "id") 3085 << SourceRange(Loc, DS.getSourceRange().getEnd()); 3086 3087 // Need to support trailing type qualifiers (e.g. "id<p> const"). 3088 // If a type specifier follows, it will be diagnosed elsewhere. 3089 continue; 3090 } 3091 // If the specifier wasn't legal, issue a diagnostic. 3092 if (isInvalid) { 3093 assert(PrevSpec && "Method did not return previous specifier!"); 3094 assert(DiagID); 3095 3096 if (DiagID == diag::ext_duplicate_declspec) 3097 Diag(Tok, DiagID) 3098 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 3099 else 3100 Diag(Tok, DiagID) << PrevSpec; 3101 } 3102 3103 DS.SetRangeEnd(Tok.getLocation()); 3104 if (DiagID != diag::err_bool_redeclaration) 3105 ConsumeToken(); 3106 3107 AttrsLastTime = false; 3108 } 3109 } 3110 3111 /// ParseStructDeclaration - Parse a struct declaration without the terminating 3112 /// semicolon. 3113 /// 3114 /// struct-declaration: 3115 /// specifier-qualifier-list struct-declarator-list 3116 /// [GNU] __extension__ struct-declaration 3117 /// [GNU] specifier-qualifier-list 3118 /// struct-declarator-list: 3119 /// struct-declarator 3120 /// struct-declarator-list ',' struct-declarator 3121 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 3122 /// struct-declarator: 3123 /// declarator 3124 /// [GNU] declarator attributes[opt] 3125 /// declarator[opt] ':' constant-expression 3126 /// [GNU] declarator[opt] ':' constant-expression attributes[opt] 3127 /// 3128 void Parser:: 3129 ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) { 3130 3131 if (Tok.is(tok::kw___extension__)) { 3132 // __extension__ silences extension warnings in the subexpression. 3133 ExtensionRAIIObject O(Diags); // Use RAII to do this. 3134 ConsumeToken(); 3135 return ParseStructDeclaration(DS, Fields); 3136 } 3137 3138 // Parse the common specifier-qualifiers-list piece. 3139 ParseSpecifierQualifierList(DS); 3140 3141 // If there are no declarators, this is a free-standing declaration 3142 // specifier. Let the actions module cope with it. 3143 if (Tok.is(tok::semi)) { 3144 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 3145 DS); 3146 DS.complete(TheDecl); 3147 return; 3148 } 3149 3150 // Read struct-declarators until we find the semicolon. 3151 bool FirstDeclarator = true; 3152 SourceLocation CommaLoc; 3153 while (1) { 3154 ParsingFieldDeclarator DeclaratorInfo(*this, DS); 3155 DeclaratorInfo.D.setCommaLoc(CommaLoc); 3156 3157 // Attributes are only allowed here on successive declarators. 3158 if (!FirstDeclarator) 3159 MaybeParseGNUAttributes(DeclaratorInfo.D); 3160 3161 /// struct-declarator: declarator 3162 /// struct-declarator: declarator[opt] ':' constant-expression 3163 if (Tok.isNot(tok::colon)) { 3164 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 3165 ColonProtectionRAIIObject X(*this); 3166 ParseDeclarator(DeclaratorInfo.D); 3167 } 3168 3169 if (Tok.is(tok::colon)) { 3170 ConsumeToken(); 3171 ExprResult Res(ParseConstantExpression()); 3172 if (Res.isInvalid()) 3173 SkipUntil(tok::semi, true, true); 3174 else 3175 DeclaratorInfo.BitfieldSize = Res.release(); 3176 } 3177 3178 // If attributes exist after the declarator, parse them. 3179 MaybeParseGNUAttributes(DeclaratorInfo.D); 3180 3181 // We're done with this declarator; invoke the callback. 3182 Fields.invoke(DeclaratorInfo); 3183 3184 // If we don't have a comma, it is either the end of the list (a ';') 3185 // or an error, bail out. 3186 if (Tok.isNot(tok::comma)) 3187 return; 3188 3189 // Consume the comma. 3190 CommaLoc = ConsumeToken(); 3191 3192 FirstDeclarator = false; 3193 } 3194 } 3195 3196 /// ParseStructUnionBody 3197 /// struct-contents: 3198 /// struct-declaration-list 3199 /// [EXT] empty 3200 /// [GNU] "struct-declaration-list" without terminatoring ';' 3201 /// struct-declaration-list: 3202 /// struct-declaration 3203 /// struct-declaration-list struct-declaration 3204 /// [OBC] '@' 'defs' '(' class-name ')' 3205 /// 3206 void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 3207 unsigned TagType, Decl *TagDecl) { 3208 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 3209 "parsing struct/union body"); 3210 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported"); 3211 3212 BalancedDelimiterTracker T(*this, tok::l_brace); 3213 if (T.consumeOpen()) 3214 return; 3215 3216 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 3217 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 3218 3219 SmallVector<Decl *, 32> FieldDecls; 3220 3221 // While we still have something to read, read the declarations in the struct. 3222 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 3223 // Each iteration of this loop reads one struct-declaration. 3224 3225 // Check for extraneous top-level semicolon. 3226 if (Tok.is(tok::semi)) { 3227 ConsumeExtraSemi(InsideStruct, TagType); 3228 continue; 3229 } 3230 3231 // Parse _Static_assert declaration. 3232 if (Tok.is(tok::kw__Static_assert)) { 3233 SourceLocation DeclEnd; 3234 ParseStaticAssertDeclaration(DeclEnd); 3235 continue; 3236 } 3237 3238 if (Tok.is(tok::annot_pragma_pack)) { 3239 HandlePragmaPack(); 3240 continue; 3241 } 3242 3243 if (Tok.is(tok::annot_pragma_align)) { 3244 HandlePragmaAlign(); 3245 continue; 3246 } 3247 3248 if (!Tok.is(tok::at)) { 3249 struct CFieldCallback : FieldCallback { 3250 Parser &P; 3251 Decl *TagDecl; 3252 SmallVectorImpl<Decl *> &FieldDecls; 3253 3254 CFieldCallback(Parser &P, Decl *TagDecl, 3255 SmallVectorImpl<Decl *> &FieldDecls) : 3256 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 3257 3258 void invoke(ParsingFieldDeclarator &FD) { 3259 // Install the declarator into the current TagDecl. 3260 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl, 3261 FD.D.getDeclSpec().getSourceRange().getBegin(), 3262 FD.D, FD.BitfieldSize); 3263 FieldDecls.push_back(Field); 3264 FD.complete(Field); 3265 } 3266 } Callback(*this, TagDecl, FieldDecls); 3267 3268 // Parse all the comma separated declarators. 3269 ParsingDeclSpec DS(*this); 3270 ParseStructDeclaration(DS, Callback); 3271 } else { // Handle @defs 3272 ConsumeToken(); 3273 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 3274 Diag(Tok, diag::err_unexpected_at); 3275 SkipUntil(tok::semi, true); 3276 continue; 3277 } 3278 ConsumeToken(); 3279 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 3280 if (!Tok.is(tok::identifier)) { 3281 Diag(Tok, diag::err_expected_ident); 3282 SkipUntil(tok::semi, true); 3283 continue; 3284 } 3285 SmallVector<Decl *, 16> Fields; 3286 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 3287 Tok.getIdentifierInfo(), Fields); 3288 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 3289 ConsumeToken(); 3290 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 3291 } 3292 3293 if (Tok.is(tok::semi)) { 3294 ConsumeToken(); 3295 } else if (Tok.is(tok::r_brace)) { 3296 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 3297 break; 3298 } else { 3299 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 3300 // Skip to end of block or statement to avoid ext-warning on extra ';'. 3301 SkipUntil(tok::r_brace, true, true); 3302 // If we stopped at a ';', eat it. 3303 if (Tok.is(tok::semi)) ConsumeToken(); 3304 } 3305 } 3306 3307 T.consumeClose(); 3308 3309 ParsedAttributes attrs(AttrFactory); 3310 // If attributes exist after struct contents, parse them. 3311 MaybeParseGNUAttributes(attrs); 3312 3313 Actions.ActOnFields(getCurScope(), 3314 RecordLoc, TagDecl, FieldDecls, 3315 T.getOpenLocation(), T.getCloseLocation(), 3316 attrs.getList()); 3317 StructScope.Exit(); 3318 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 3319 T.getCloseLocation()); 3320 } 3321 3322 /// ParseEnumSpecifier 3323 /// enum-specifier: [C99 6.7.2.2] 3324 /// 'enum' identifier[opt] '{' enumerator-list '}' 3325 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 3326 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 3327 /// '}' attributes[opt] 3328 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] 3329 /// '}' 3330 /// 'enum' identifier 3331 /// [GNU] 'enum' attributes[opt] identifier 3332 /// 3333 /// [C++11] enum-head '{' enumerator-list[opt] '}' 3334 /// [C++11] enum-head '{' enumerator-list ',' '}' 3335 /// 3336 /// enum-head: [C++11] 3337 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] 3338 /// enum-key attribute-specifier-seq[opt] nested-name-specifier 3339 /// identifier enum-base[opt] 3340 /// 3341 /// enum-key: [C++11] 3342 /// 'enum' 3343 /// 'enum' 'class' 3344 /// 'enum' 'struct' 3345 /// 3346 /// enum-base: [C++11] 3347 /// ':' type-specifier-seq 3348 /// 3349 /// [C++] elaborated-type-specifier: 3350 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 3351 /// 3352 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 3353 const ParsedTemplateInfo &TemplateInfo, 3354 AccessSpecifier AS, DeclSpecContext DSC) { 3355 // Parse the tag portion of this. 3356 if (Tok.is(tok::code_completion)) { 3357 // Code completion for an enum name. 3358 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 3359 return cutOffParsing(); 3360 } 3361 3362 // If attributes exist after tag, parse them. 3363 ParsedAttributesWithRange attrs(AttrFactory); 3364 MaybeParseGNUAttributes(attrs); 3365 MaybeParseCXX11Attributes(attrs); 3366 3367 // If declspecs exist after tag, parse them. 3368 while (Tok.is(tok::kw___declspec)) 3369 ParseMicrosoftDeclSpec(attrs); 3370 3371 SourceLocation ScopedEnumKWLoc; 3372 bool IsScopedUsingClassTag = false; 3373 3374 // In C++11, recognize 'enum class' and 'enum struct'. 3375 if (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct)) { 3376 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum 3377 : diag::ext_scoped_enum); 3378 IsScopedUsingClassTag = Tok.is(tok::kw_class); 3379 ScopedEnumKWLoc = ConsumeToken(); 3380 3381 // Attributes are not allowed between these keywords. Diagnose, 3382 // but then just treat them like they appeared in the right place. 3383 ProhibitAttributes(attrs); 3384 3385 // They are allowed afterwards, though. 3386 MaybeParseGNUAttributes(attrs); 3387 MaybeParseCXX11Attributes(attrs); 3388 while (Tok.is(tok::kw___declspec)) 3389 ParseMicrosoftDeclSpec(attrs); 3390 } 3391 3392 // C++11 [temp.explicit]p12: 3393 // The usual access controls do not apply to names used to specify 3394 // explicit instantiations. 3395 // We extend this to also cover explicit specializations. Note that 3396 // we don't suppress if this turns out to be an elaborated type 3397 // specifier. 3398 bool shouldDelayDiagsInTag = 3399 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 3400 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 3401 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 3402 3403 // Enum definitions should not be parsed in a trailing-return-type. 3404 bool AllowDeclaration = DSC != DSC_trailing; 3405 3406 bool AllowFixedUnderlyingType = AllowDeclaration && 3407 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt || 3408 getLangOpts().ObjC2); 3409 3410 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3411 if (getLangOpts().CPlusPlus) { 3412 // "enum foo : bar;" is not a potential typo for "enum foo::bar;" 3413 // if a fixed underlying type is allowed. 3414 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); 3415 3416 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 3417 /*EnteringContext=*/true)) 3418 return; 3419 3420 if (SS.isSet() && Tok.isNot(tok::identifier)) { 3421 Diag(Tok, diag::err_expected_ident); 3422 if (Tok.isNot(tok::l_brace)) { 3423 // Has no name and is not a definition. 3424 // Skip the rest of this declarator, up until the comma or semicolon. 3425 SkipUntil(tok::comma, true); 3426 return; 3427 } 3428 } 3429 } 3430 3431 // Must have either 'enum name' or 'enum {...}'. 3432 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 3433 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) { 3434 Diag(Tok, diag::err_expected_ident_lbrace); 3435 3436 // Skip the rest of this declarator, up until the comma or semicolon. 3437 SkipUntil(tok::comma, true); 3438 return; 3439 } 3440 3441 // If an identifier is present, consume and remember it. 3442 IdentifierInfo *Name = 0; 3443 SourceLocation NameLoc; 3444 if (Tok.is(tok::identifier)) { 3445 Name = Tok.getIdentifierInfo(); 3446 NameLoc = ConsumeToken(); 3447 } 3448 3449 if (!Name && ScopedEnumKWLoc.isValid()) { 3450 // C++0x 7.2p2: The optional identifier shall not be omitted in the 3451 // declaration of a scoped enumeration. 3452 Diag(Tok, diag::err_scoped_enum_missing_identifier); 3453 ScopedEnumKWLoc = SourceLocation(); 3454 IsScopedUsingClassTag = false; 3455 } 3456 3457 // Okay, end the suppression area. We'll decide whether to emit the 3458 // diagnostics in a second. 3459 if (shouldDelayDiagsInTag) 3460 diagsFromTag.done(); 3461 3462 TypeResult BaseType; 3463 3464 // Parse the fixed underlying type. 3465 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 3466 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 3467 bool PossibleBitfield = false; 3468 if (CanBeBitfield) { 3469 // If we're in class scope, this can either be an enum declaration with 3470 // an underlying type, or a declaration of a bitfield member. We try to 3471 // use a simple disambiguation scheme first to catch the common cases 3472 // (integer literal, sizeof); if it's still ambiguous, we then consider 3473 // anything that's a simple-type-specifier followed by '(' as an 3474 // expression. This suffices because function types are not valid 3475 // underlying types anyway. 3476 EnterExpressionEvaluationContext Unevaluated(Actions, 3477 Sema::ConstantEvaluated); 3478 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 3479 // If the next token starts an expression, we know we're parsing a 3480 // bit-field. This is the common case. 3481 if (TPR == TPResult::True()) 3482 PossibleBitfield = true; 3483 // If the next token starts a type-specifier-seq, it may be either a 3484 // a fixed underlying type or the start of a function-style cast in C++; 3485 // lookahead one more token to see if it's obvious that we have a 3486 // fixed underlying type. 3487 else if (TPR == TPResult::False() && 3488 GetLookAheadToken(2).getKind() == tok::semi) { 3489 // Consume the ':'. 3490 ConsumeToken(); 3491 } else { 3492 // We have the start of a type-specifier-seq, so we have to perform 3493 // tentative parsing to determine whether we have an expression or a 3494 // type. 3495 TentativeParsingAction TPA(*this); 3496 3497 // Consume the ':'. 3498 ConsumeToken(); 3499 3500 // If we see a type specifier followed by an open-brace, we have an 3501 // ambiguity between an underlying type and a C++11 braced 3502 // function-style cast. Resolve this by always treating it as an 3503 // underlying type. 3504 // FIXME: The standard is not entirely clear on how to disambiguate in 3505 // this case. 3506 if ((getLangOpts().CPlusPlus && 3507 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) || 3508 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) { 3509 // We'll parse this as a bitfield later. 3510 PossibleBitfield = true; 3511 TPA.Revert(); 3512 } else { 3513 // We have a type-specifier-seq. 3514 TPA.Commit(); 3515 } 3516 } 3517 } else { 3518 // Consume the ':'. 3519 ConsumeToken(); 3520 } 3521 3522 if (!PossibleBitfield) { 3523 SourceRange Range; 3524 BaseType = ParseTypeName(&Range); 3525 3526 if (getLangOpts().CPlusPlus11) { 3527 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); 3528 } else if (!getLangOpts().ObjC2) { 3529 if (getLangOpts().CPlusPlus) 3530 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range; 3531 else 3532 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range; 3533 } 3534 } 3535 } 3536 3537 // There are four options here. If we have 'friend enum foo;' then this is a 3538 // friend declaration, and cannot have an accompanying definition. If we have 3539 // 'enum foo;', then this is a forward declaration. If we have 3540 // 'enum foo {...' then this is a definition. Otherwise we have something 3541 // like 'enum foo xyz', a reference. 3542 // 3543 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 3544 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 3545 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 3546 // 3547 Sema::TagUseKind TUK; 3548 if (!AllowDeclaration) { 3549 TUK = Sema::TUK_Reference; 3550 } else if (Tok.is(tok::l_brace)) { 3551 if (DS.isFriendSpecified()) { 3552 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 3553 << SourceRange(DS.getFriendSpecLoc()); 3554 ConsumeBrace(); 3555 SkipUntil(tok::r_brace); 3556 TUK = Sema::TUK_Friend; 3557 } else { 3558 TUK = Sema::TUK_Definition; 3559 } 3560 } else if (DSC != DSC_type_specifier && 3561 (Tok.is(tok::semi) || 3562 (Tok.isAtStartOfLine() && 3563 !isValidAfterTypeSpecifier(CanBeBitfield)))) { 3564 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 3565 if (Tok.isNot(tok::semi)) { 3566 // A semicolon was missing after this declaration. Diagnose and recover. 3567 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 3568 "enum"); 3569 PP.EnterToken(Tok); 3570 Tok.setKind(tok::semi); 3571 } 3572 } else { 3573 TUK = Sema::TUK_Reference; 3574 } 3575 3576 // If this is an elaborated type specifier, and we delayed 3577 // diagnostics before, just merge them into the current pool. 3578 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) { 3579 diagsFromTag.redelay(); 3580 } 3581 3582 MultiTemplateParamsArg TParams; 3583 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 3584 TUK != Sema::TUK_Reference) { 3585 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) { 3586 // Skip the rest of this declarator, up until the comma or semicolon. 3587 Diag(Tok, diag::err_enum_template); 3588 SkipUntil(tok::comma, true); 3589 return; 3590 } 3591 3592 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 3593 // Enumerations can't be explicitly instantiated. 3594 DS.SetTypeSpecError(); 3595 Diag(StartLoc, diag::err_explicit_instantiation_enum); 3596 return; 3597 } 3598 3599 assert(TemplateInfo.TemplateParams && "no template parameters"); 3600 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(), 3601 TemplateInfo.TemplateParams->size()); 3602 } 3603 3604 if (TUK == Sema::TUK_Reference) 3605 ProhibitAttributes(attrs); 3606 3607 if (!Name && TUK != Sema::TUK_Definition) { 3608 Diag(Tok, diag::err_enumerator_unnamed_no_def); 3609 3610 // Skip the rest of this declarator, up until the comma or semicolon. 3611 SkipUntil(tok::comma, true); 3612 return; 3613 } 3614 3615 bool Owned = false; 3616 bool IsDependent = false; 3617 const char *PrevSpec = 0; 3618 unsigned DiagID; 3619 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 3620 StartLoc, SS, Name, NameLoc, attrs.getList(), 3621 AS, DS.getModulePrivateSpecLoc(), TParams, 3622 Owned, IsDependent, ScopedEnumKWLoc, 3623 IsScopedUsingClassTag, BaseType); 3624 3625 if (IsDependent) { 3626 // This enum has a dependent nested-name-specifier. Handle it as a 3627 // dependent tag. 3628 if (!Name) { 3629 DS.SetTypeSpecError(); 3630 Diag(Tok, diag::err_expected_type_name_after_typename); 3631 return; 3632 } 3633 3634 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum, 3635 TUK, SS, Name, StartLoc, 3636 NameLoc); 3637 if (Type.isInvalid()) { 3638 DS.SetTypeSpecError(); 3639 return; 3640 } 3641 3642 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 3643 NameLoc.isValid() ? NameLoc : StartLoc, 3644 PrevSpec, DiagID, Type.get())) 3645 Diag(StartLoc, DiagID) << PrevSpec; 3646 3647 return; 3648 } 3649 3650 if (!TagDecl) { 3651 // The action failed to produce an enumeration tag. If this is a 3652 // definition, consume the entire definition. 3653 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { 3654 ConsumeBrace(); 3655 SkipUntil(tok::r_brace); 3656 } 3657 3658 DS.SetTypeSpecError(); 3659 return; 3660 } 3661 3662 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) 3663 ParseEnumBody(StartLoc, TagDecl); 3664 3665 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 3666 NameLoc.isValid() ? NameLoc : StartLoc, 3667 PrevSpec, DiagID, TagDecl, Owned)) 3668 Diag(StartLoc, DiagID) << PrevSpec; 3669 } 3670 3671 /// ParseEnumBody - Parse a {} enclosed enumerator-list. 3672 /// enumerator-list: 3673 /// enumerator 3674 /// enumerator-list ',' enumerator 3675 /// enumerator: 3676 /// enumeration-constant 3677 /// enumeration-constant '=' constant-expression 3678 /// enumeration-constant: 3679 /// identifier 3680 /// 3681 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 3682 // Enter the scope of the enum body and start the definition. 3683 ParseScope EnumScope(this, Scope::DeclScope); 3684 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 3685 3686 BalancedDelimiterTracker T(*this, tok::l_brace); 3687 T.consumeOpen(); 3688 3689 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 3690 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) 3691 Diag(Tok, diag::error_empty_enum); 3692 3693 SmallVector<Decl *, 32> EnumConstantDecls; 3694 3695 Decl *LastEnumConstDecl = 0; 3696 3697 // Parse the enumerator-list. 3698 while (Tok.is(tok::identifier)) { 3699 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 3700 SourceLocation IdentLoc = ConsumeToken(); 3701 3702 // If attributes exist after the enumerator, parse them. 3703 ParsedAttributesWithRange attrs(AttrFactory); 3704 MaybeParseGNUAttributes(attrs); 3705 MaybeParseCXX11Attributes(attrs); 3706 ProhibitAttributes(attrs); 3707 3708 SourceLocation EqualLoc; 3709 ExprResult AssignedVal; 3710 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); 3711 3712 if (Tok.is(tok::equal)) { 3713 EqualLoc = ConsumeToken(); 3714 AssignedVal = ParseConstantExpression(); 3715 if (AssignedVal.isInvalid()) 3716 SkipUntil(tok::comma, tok::r_brace, true, true); 3717 } 3718 3719 // Install the enumerator constant into EnumDecl. 3720 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 3721 LastEnumConstDecl, 3722 IdentLoc, Ident, 3723 attrs.getList(), EqualLoc, 3724 AssignedVal.release()); 3725 PD.complete(EnumConstDecl); 3726 3727 EnumConstantDecls.push_back(EnumConstDecl); 3728 LastEnumConstDecl = EnumConstDecl; 3729 3730 if (Tok.is(tok::identifier)) { 3731 // We're missing a comma between enumerators. 3732 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 3733 Diag(Loc, diag::err_enumerator_list_missing_comma) 3734 << FixItHint::CreateInsertion(Loc, ", "); 3735 continue; 3736 } 3737 3738 if (Tok.isNot(tok::comma)) 3739 break; 3740 SourceLocation CommaLoc = ConsumeToken(); 3741 3742 if (Tok.isNot(tok::identifier)) { 3743 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) 3744 Diag(CommaLoc, getLangOpts().CPlusPlus ? 3745 diag::ext_enumerator_list_comma_cxx : 3746 diag::ext_enumerator_list_comma_c) 3747 << FixItHint::CreateRemoval(CommaLoc); 3748 else if (getLangOpts().CPlusPlus11) 3749 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) 3750 << FixItHint::CreateRemoval(CommaLoc); 3751 } 3752 } 3753 3754 // Eat the }. 3755 T.consumeClose(); 3756 3757 // If attributes exist after the identifier list, parse them. 3758 ParsedAttributes attrs(AttrFactory); 3759 MaybeParseGNUAttributes(attrs); 3760 3761 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(), 3762 EnumDecl, EnumConstantDecls, 3763 getCurScope(), 3764 attrs.getList()); 3765 3766 EnumScope.Exit(); 3767 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, 3768 T.getCloseLocation()); 3769 3770 // The next token must be valid after an enum definition. If not, a ';' 3771 // was probably forgotten. 3772 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; 3773 if (!isValidAfterTypeSpecifier(CanBeBitfield)) { 3774 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum"); 3775 // Push this token back into the preprocessor and change our current token 3776 // to ';' so that the rest of the code recovers as though there were an 3777 // ';' after the definition. 3778 PP.EnterToken(Tok); 3779 Tok.setKind(tok::semi); 3780 } 3781 } 3782 3783 /// isTypeSpecifierQualifier - Return true if the current token could be the 3784 /// start of a type-qualifier-list. 3785 bool Parser::isTypeQualifier() const { 3786 switch (Tok.getKind()) { 3787 default: return false; 3788 3789 // type-qualifier only in OpenCL 3790 case tok::kw_private: 3791 return getLangOpts().OpenCL; 3792 3793 // type-qualifier 3794 case tok::kw_const: 3795 case tok::kw_volatile: 3796 case tok::kw_restrict: 3797 case tok::kw___private: 3798 case tok::kw___local: 3799 case tok::kw___global: 3800 case tok::kw___constant: 3801 case tok::kw___read_only: 3802 case tok::kw___read_write: 3803 case tok::kw___write_only: 3804 return true; 3805 } 3806 } 3807 3808 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token 3809 /// is definitely a type-specifier. Return false if it isn't part of a type 3810 /// specifier or if we're not sure. 3811 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 3812 switch (Tok.getKind()) { 3813 default: return false; 3814 // type-specifiers 3815 case tok::kw_short: 3816 case tok::kw_long: 3817 case tok::kw___int64: 3818 case tok::kw___int128: 3819 case tok::kw_signed: 3820 case tok::kw_unsigned: 3821 case tok::kw__Complex: 3822 case tok::kw__Imaginary: 3823 case tok::kw_void: 3824 case tok::kw_char: 3825 case tok::kw_wchar_t: 3826 case tok::kw_char16_t: 3827 case tok::kw_char32_t: 3828 case tok::kw_int: 3829 case tok::kw_half: 3830 case tok::kw_float: 3831 case tok::kw_double: 3832 case tok::kw_bool: 3833 case tok::kw__Bool: 3834 case tok::kw__Decimal32: 3835 case tok::kw__Decimal64: 3836 case tok::kw__Decimal128: 3837 case tok::kw___vector: 3838 3839 // OpenCL specific types: 3840 case tok::kw_image1d_t: 3841 case tok::kw_image1d_array_t: 3842 case tok::kw_image1d_buffer_t: 3843 case tok::kw_image2d_t: 3844 case tok::kw_image2d_array_t: 3845 case tok::kw_image3d_t: 3846 case tok::kw_sampler_t: 3847 case tok::kw_event_t: 3848 3849 // struct-or-union-specifier (C99) or class-specifier (C++) 3850 case tok::kw_class: 3851 case tok::kw_struct: 3852 case tok::kw___interface: 3853 case tok::kw_union: 3854 // enum-specifier 3855 case tok::kw_enum: 3856 3857 // typedef-name 3858 case tok::annot_typename: 3859 return true; 3860 } 3861 } 3862 3863 /// isTypeSpecifierQualifier - Return true if the current token could be the 3864 /// start of a specifier-qualifier-list. 3865 bool Parser::isTypeSpecifierQualifier() { 3866 switch (Tok.getKind()) { 3867 default: return false; 3868 3869 case tok::identifier: // foo::bar 3870 if (TryAltiVecVectorToken()) 3871 return true; 3872 // Fall through. 3873 case tok::kw_typename: // typename T::type 3874 // Annotate typenames and C++ scope specifiers. If we get one, just 3875 // recurse to handle whatever we get. 3876 if (TryAnnotateTypeOrScopeToken()) 3877 return true; 3878 if (Tok.is(tok::identifier)) 3879 return false; 3880 return isTypeSpecifierQualifier(); 3881 3882 case tok::coloncolon: // ::foo::bar 3883 if (NextToken().is(tok::kw_new) || // ::new 3884 NextToken().is(tok::kw_delete)) // ::delete 3885 return false; 3886 3887 if (TryAnnotateTypeOrScopeToken()) 3888 return true; 3889 return isTypeSpecifierQualifier(); 3890 3891 // GNU attributes support. 3892 case tok::kw___attribute: 3893 // GNU typeof support. 3894 case tok::kw_typeof: 3895 3896 // type-specifiers 3897 case tok::kw_short: 3898 case tok::kw_long: 3899 case tok::kw___int64: 3900 case tok::kw___int128: 3901 case tok::kw_signed: 3902 case tok::kw_unsigned: 3903 case tok::kw__Complex: 3904 case tok::kw__Imaginary: 3905 case tok::kw_void: 3906 case tok::kw_char: 3907 case tok::kw_wchar_t: 3908 case tok::kw_char16_t: 3909 case tok::kw_char32_t: 3910 case tok::kw_int: 3911 case tok::kw_half: 3912 case tok::kw_float: 3913 case tok::kw_double: 3914 case tok::kw_bool: 3915 case tok::kw__Bool: 3916 case tok::kw__Decimal32: 3917 case tok::kw__Decimal64: 3918 case tok::kw__Decimal128: 3919 case tok::kw___vector: 3920 3921 // OpenCL specific types: 3922 case tok::kw_image1d_t: 3923 case tok::kw_image1d_array_t: 3924 case tok::kw_image1d_buffer_t: 3925 case tok::kw_image2d_t: 3926 case tok::kw_image2d_array_t: 3927 case tok::kw_image3d_t: 3928 case tok::kw_sampler_t: 3929 case tok::kw_event_t: 3930 3931 // struct-or-union-specifier (C99) or class-specifier (C++) 3932 case tok::kw_class: 3933 case tok::kw_struct: 3934 case tok::kw___interface: 3935 case tok::kw_union: 3936 // enum-specifier 3937 case tok::kw_enum: 3938 3939 // type-qualifier 3940 case tok::kw_const: 3941 case tok::kw_volatile: 3942 case tok::kw_restrict: 3943 3944 // Debugger support. 3945 case tok::kw___unknown_anytype: 3946 3947 // typedef-name 3948 case tok::annot_typename: 3949 return true; 3950 3951 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 3952 case tok::less: 3953 return getLangOpts().ObjC1; 3954 3955 case tok::kw___cdecl: 3956 case tok::kw___stdcall: 3957 case tok::kw___fastcall: 3958 case tok::kw___thiscall: 3959 case tok::kw___w64: 3960 case tok::kw___ptr64: 3961 case tok::kw___ptr32: 3962 case tok::kw___pascal: 3963 case tok::kw___unaligned: 3964 3965 case tok::kw___private: 3966 case tok::kw___local: 3967 case tok::kw___global: 3968 case tok::kw___constant: 3969 case tok::kw___read_only: 3970 case tok::kw___read_write: 3971 case tok::kw___write_only: 3972 3973 return true; 3974 3975 case tok::kw_private: 3976 return getLangOpts().OpenCL; 3977 3978 // C11 _Atomic 3979 case tok::kw__Atomic: 3980 return true; 3981 } 3982 } 3983 3984 /// isDeclarationSpecifier() - Return true if the current token is part of a 3985 /// declaration specifier. 3986 /// 3987 /// \param DisambiguatingWithExpression True to indicate that the purpose of 3988 /// this check is to disambiguate between an expression and a declaration. 3989 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 3990 switch (Tok.getKind()) { 3991 default: return false; 3992 3993 case tok::kw_private: 3994 return getLangOpts().OpenCL; 3995 3996 case tok::identifier: // foo::bar 3997 // Unfortunate hack to support "Class.factoryMethod" notation. 3998 if (getLangOpts().ObjC1 && NextToken().is(tok::period)) 3999 return false; 4000 if (TryAltiVecVectorToken()) 4001 return true; 4002 // Fall through. 4003 case tok::kw_decltype: // decltype(T())::type 4004 case tok::kw_typename: // typename T::type 4005 // Annotate typenames and C++ scope specifiers. If we get one, just 4006 // recurse to handle whatever we get. 4007 if (TryAnnotateTypeOrScopeToken()) 4008 return true; 4009 if (Tok.is(tok::identifier)) 4010 return false; 4011 4012 // If we're in Objective-C and we have an Objective-C class type followed 4013 // by an identifier and then either ':' or ']', in a place where an 4014 // expression is permitted, then this is probably a class message send 4015 // missing the initial '['. In this case, we won't consider this to be 4016 // the start of a declaration. 4017 if (DisambiguatingWithExpression && 4018 isStartOfObjCClassMessageMissingOpenBracket()) 4019 return false; 4020 4021 return isDeclarationSpecifier(); 4022 4023 case tok::coloncolon: // ::foo::bar 4024 if (NextToken().is(tok::kw_new) || // ::new 4025 NextToken().is(tok::kw_delete)) // ::delete 4026 return false; 4027 4028 // Annotate typenames and C++ scope specifiers. If we get one, just 4029 // recurse to handle whatever we get. 4030 if (TryAnnotateTypeOrScopeToken()) 4031 return true; 4032 return isDeclarationSpecifier(); 4033 4034 // storage-class-specifier 4035 case tok::kw_typedef: 4036 case tok::kw_extern: 4037 case tok::kw___private_extern__: 4038 case tok::kw_static: 4039 case tok::kw_auto: 4040 case tok::kw_register: 4041 case tok::kw___thread: 4042 case tok::kw_thread_local: 4043 case tok::kw__Thread_local: 4044 4045 // Modules 4046 case tok::kw___module_private__: 4047 4048 // Debugger support 4049 case tok::kw___unknown_anytype: 4050 4051 // type-specifiers 4052 case tok::kw_short: 4053 case tok::kw_long: 4054 case tok::kw___int64: 4055 case tok::kw___int128: 4056 case tok::kw_signed: 4057 case tok::kw_unsigned: 4058 case tok::kw__Complex: 4059 case tok::kw__Imaginary: 4060 case tok::kw_void: 4061 case tok::kw_char: 4062 case tok::kw_wchar_t: 4063 case tok::kw_char16_t: 4064 case tok::kw_char32_t: 4065 4066 case tok::kw_int: 4067 case tok::kw_half: 4068 case tok::kw_float: 4069 case tok::kw_double: 4070 case tok::kw_bool: 4071 case tok::kw__Bool: 4072 case tok::kw__Decimal32: 4073 case tok::kw__Decimal64: 4074 case tok::kw__Decimal128: 4075 case tok::kw___vector: 4076 4077 // OpenCL specific types: 4078 case tok::kw_image1d_t: 4079 case tok::kw_image1d_array_t: 4080 case tok::kw_image1d_buffer_t: 4081 case tok::kw_image2d_t: 4082 case tok::kw_image2d_array_t: 4083 case tok::kw_image3d_t: 4084 case tok::kw_sampler_t: 4085 case tok::kw_event_t: 4086 4087 // struct-or-union-specifier (C99) or class-specifier (C++) 4088 case tok::kw_class: 4089 case tok::kw_struct: 4090 case tok::kw_union: 4091 case tok::kw___interface: 4092 // enum-specifier 4093 case tok::kw_enum: 4094 4095 // type-qualifier 4096 case tok::kw_const: 4097 case tok::kw_volatile: 4098 case tok::kw_restrict: 4099 4100 // function-specifier 4101 case tok::kw_inline: 4102 case tok::kw_virtual: 4103 case tok::kw_explicit: 4104 case tok::kw__Noreturn: 4105 4106 // alignment-specifier 4107 case tok::kw__Alignas: 4108 4109 // friend keyword. 4110 case tok::kw_friend: 4111 4112 // static_assert-declaration 4113 case tok::kw__Static_assert: 4114 4115 // GNU typeof support. 4116 case tok::kw_typeof: 4117 4118 // GNU attributes. 4119 case tok::kw___attribute: 4120 4121 // C++11 decltype and constexpr. 4122 case tok::annot_decltype: 4123 case tok::kw_constexpr: 4124 4125 // C11 _Atomic 4126 case tok::kw__Atomic: 4127 return true; 4128 4129 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 4130 case tok::less: 4131 return getLangOpts().ObjC1; 4132 4133 // typedef-name 4134 case tok::annot_typename: 4135 return !DisambiguatingWithExpression || 4136 !isStartOfObjCClassMessageMissingOpenBracket(); 4137 4138 case tok::kw___declspec: 4139 case tok::kw___cdecl: 4140 case tok::kw___stdcall: 4141 case tok::kw___fastcall: 4142 case tok::kw___thiscall: 4143 case tok::kw___w64: 4144 case tok::kw___sptr: 4145 case tok::kw___uptr: 4146 case tok::kw___ptr64: 4147 case tok::kw___ptr32: 4148 case tok::kw___forceinline: 4149 case tok::kw___pascal: 4150 case tok::kw___unaligned: 4151 4152 case tok::kw___private: 4153 case tok::kw___local: 4154 case tok::kw___global: 4155 case tok::kw___constant: 4156 case tok::kw___read_only: 4157 case tok::kw___read_write: 4158 case tok::kw___write_only: 4159 4160 return true; 4161 } 4162 } 4163 4164 bool Parser::isConstructorDeclarator() { 4165 TentativeParsingAction TPA(*this); 4166 4167 // Parse the C++ scope specifier. 4168 CXXScopeSpec SS; 4169 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 4170 /*EnteringContext=*/true)) { 4171 TPA.Revert(); 4172 return false; 4173 } 4174 4175 // Parse the constructor name. 4176 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 4177 // We already know that we have a constructor name; just consume 4178 // the token. 4179 ConsumeToken(); 4180 } else { 4181 TPA.Revert(); 4182 return false; 4183 } 4184 4185 // Current class name must be followed by a left parenthesis. 4186 if (Tok.isNot(tok::l_paren)) { 4187 TPA.Revert(); 4188 return false; 4189 } 4190 ConsumeParen(); 4191 4192 // A right parenthesis, or ellipsis followed by a right parenthesis signals 4193 // that we have a constructor. 4194 if (Tok.is(tok::r_paren) || 4195 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { 4196 TPA.Revert(); 4197 return true; 4198 } 4199 4200 // If we need to, enter the specified scope. 4201 DeclaratorScopeObj DeclScopeObj(*this, SS); 4202 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 4203 DeclScopeObj.EnterDeclaratorScope(); 4204 4205 // Optionally skip Microsoft attributes. 4206 ParsedAttributes Attrs(AttrFactory); 4207 MaybeParseMicrosoftAttributes(Attrs); 4208 4209 // Check whether the next token(s) are part of a declaration 4210 // specifier, in which case we have the start of a parameter and, 4211 // therefore, we know that this is a constructor. 4212 bool IsConstructor = false; 4213 if (isDeclarationSpecifier()) 4214 IsConstructor = true; 4215 else if (Tok.is(tok::identifier) || 4216 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { 4217 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. 4218 // This might be a parenthesized member name, but is more likely to 4219 // be a constructor declaration with an invalid argument type. Keep 4220 // looking. 4221 if (Tok.is(tok::annot_cxxscope)) 4222 ConsumeToken(); 4223 ConsumeToken(); 4224 4225 // If this is not a constructor, we must be parsing a declarator, 4226 // which must have one of the following syntactic forms (see the 4227 // grammar extract at the start of ParseDirectDeclarator): 4228 switch (Tok.getKind()) { 4229 case tok::l_paren: 4230 // C(X ( int)); 4231 case tok::l_square: 4232 // C(X [ 5]); 4233 // C(X [ [attribute]]); 4234 case tok::coloncolon: 4235 // C(X :: Y); 4236 // C(X :: *p); 4237 case tok::r_paren: 4238 // C(X ) 4239 // Assume this isn't a constructor, rather than assuming it's a 4240 // constructor with an unnamed parameter of an ill-formed type. 4241 break; 4242 4243 default: 4244 IsConstructor = true; 4245 break; 4246 } 4247 } 4248 4249 TPA.Revert(); 4250 return IsConstructor; 4251 } 4252 4253 /// ParseTypeQualifierListOpt 4254 /// type-qualifier-list: [C99 6.7.5] 4255 /// type-qualifier 4256 /// [vendor] attributes 4257 /// [ only if VendorAttributesAllowed=true ] 4258 /// type-qualifier-list type-qualifier 4259 /// [vendor] type-qualifier-list attributes 4260 /// [ only if VendorAttributesAllowed=true ] 4261 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 4262 /// [ only if CXX11AttributesAllowed=true ] 4263 /// Note: vendor can be GNU, MS, etc. 4264 /// 4265 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, 4266 bool VendorAttributesAllowed, 4267 bool CXX11AttributesAllowed, 4268 bool AtomicAllowed) { 4269 if (getLangOpts().CPlusPlus11 && CXX11AttributesAllowed && 4270 isCXX11AttributeSpecifier()) { 4271 ParsedAttributesWithRange attrs(AttrFactory); 4272 ParseCXX11Attributes(attrs); 4273 DS.takeAttributesFrom(attrs); 4274 } 4275 4276 SourceLocation EndLoc; 4277 4278 while (1) { 4279 bool isInvalid = false; 4280 const char *PrevSpec = 0; 4281 unsigned DiagID = 0; 4282 SourceLocation Loc = Tok.getLocation(); 4283 4284 switch (Tok.getKind()) { 4285 case tok::code_completion: 4286 Actions.CodeCompleteTypeQualifiers(DS); 4287 return cutOffParsing(); 4288 4289 case tok::kw_const: 4290 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 4291 getLangOpts()); 4292 break; 4293 case tok::kw_volatile: 4294 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 4295 getLangOpts()); 4296 break; 4297 case tok::kw_restrict: 4298 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 4299 getLangOpts()); 4300 break; 4301 case tok::kw__Atomic: 4302 if (!AtomicAllowed) 4303 goto DoneWithTypeQuals; 4304 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, 4305 getLangOpts()); 4306 break; 4307 4308 // OpenCL qualifiers: 4309 case tok::kw_private: 4310 if (!getLangOpts().OpenCL) 4311 goto DoneWithTypeQuals; 4312 case tok::kw___private: 4313 case tok::kw___global: 4314 case tok::kw___local: 4315 case tok::kw___constant: 4316 case tok::kw___read_only: 4317 case tok::kw___write_only: 4318 case tok::kw___read_write: 4319 ParseOpenCLQualifiers(DS); 4320 break; 4321 4322 case tok::kw___sptr: 4323 case tok::kw___uptr: 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 /// 4371 void 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 4377 static 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] 4413 void 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 4557 static 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. 4611 void 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 /// 4803 void 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 /// 4919 void 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. 5087 bool 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 /// 5118 void 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 /// 5198 void 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] 5355 void 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 /// 5470 void 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 /// 5533 void 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. 5567 bool 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 5593 bool 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