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