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