ParseDecl.cpp revision 338d7f7362d18fa9c39c6bb5282b4e20574a9309
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/Scope.h" 18#include "clang/Sema/ParsedTemplate.h" 19#include "clang/Sema/PrettyDeclStackTrace.h" 20#include "RAIIObjectsForParser.h" 21#include "llvm/ADT/SmallSet.h" 22using namespace clang; 23 24//===----------------------------------------------------------------------===// 25// C99 6.7: Declarations. 26//===----------------------------------------------------------------------===// 27 28/// ParseTypeName 29/// type-name: [C99 6.7.6] 30/// specifier-qualifier-list abstract-declarator[opt] 31/// 32/// Called type-id in C++. 33TypeResult Parser::ParseTypeName(SourceRange *Range, 34 Declarator::TheContext Context) { 35 // Parse the common declaration-specifiers piece. 36 DeclSpec DS(AttrFactory); 37 ParseSpecifierQualifierList(DS); 38 39 // Parse the abstract-declarator, if present. 40 Declarator DeclaratorInfo(DS, Context); 41 ParseDeclarator(DeclaratorInfo); 42 if (Range) 43 *Range = DeclaratorInfo.getSourceRange(); 44 45 if (DeclaratorInfo.isInvalidType()) 46 return true; 47 48 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 49} 50 51/// ParseGNUAttributes - Parse a non-empty attributes list. 52/// 53/// [GNU] attributes: 54/// attribute 55/// attributes attribute 56/// 57/// [GNU] attribute: 58/// '__attribute__' '(' '(' attribute-list ')' ')' 59/// 60/// [GNU] attribute-list: 61/// attrib 62/// attribute_list ',' attrib 63/// 64/// [GNU] attrib: 65/// empty 66/// attrib-name 67/// attrib-name '(' identifier ')' 68/// attrib-name '(' identifier ',' nonempty-expr-list ')' 69/// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 70/// 71/// [GNU] attrib-name: 72/// identifier 73/// typespec 74/// typequal 75/// storageclass 76/// 77/// FIXME: The GCC grammar/code for this construct implies we need two 78/// token lookahead. Comment from gcc: "If they start with an identifier 79/// which is followed by a comma or close parenthesis, then the arguments 80/// start with that identifier; otherwise they are an expression list." 81/// 82/// At the moment, I am not doing 2 token lookahead. I am also unaware of 83/// any attributes that don't work (based on my limited testing). Most 84/// attributes are very simple in practice. Until we find a bug, I don't see 85/// a pressing need to implement the 2 token lookahead. 86 87void Parser::ParseGNUAttributes(ParsedAttributes &attrs, 88 SourceLocation *endLoc) { 89 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!"); 90 91 while (Tok.is(tok::kw___attribute)) { 92 ConsumeToken(); 93 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 94 "attribute")) { 95 SkipUntil(tok::r_paren, true); // skip until ) or ; 96 return; 97 } 98 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 99 SkipUntil(tok::r_paren, true); // skip until ) or ; 100 return; 101 } 102 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 103 while (Tok.is(tok::identifier) || isDeclarationSpecifier() || 104 Tok.is(tok::comma)) { 105 106 if (Tok.is(tok::comma)) { 107 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,)) 108 ConsumeToken(); 109 continue; 110 } 111 // we have an identifier or declaration specifier (const, int, etc.) 112 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 113 SourceLocation AttrNameLoc = ConsumeToken(); 114 115 // Availability attributes have their own grammar. 116 if (AttrName->isStr("availability")) 117 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, attrs, endLoc); 118 // check if we have a "parameterized" attribute 119 else if (Tok.is(tok::l_paren)) { 120 ConsumeParen(); // ignore the left paren loc for now 121 122 if (Tok.is(tok::identifier)) { 123 IdentifierInfo *ParmName = Tok.getIdentifierInfo(); 124 SourceLocation ParmLoc = ConsumeToken(); 125 126 if (Tok.is(tok::r_paren)) { 127 // __attribute__(( mode(byte) )) 128 ConsumeParen(); // ignore the right paren loc for now 129 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 130 ParmName, ParmLoc, 0, 0); 131 } else if (Tok.is(tok::comma)) { 132 ConsumeToken(); 133 // __attribute__(( format(printf, 1, 2) )) 134 ExprVector ArgExprs(Actions); 135 bool ArgExprsOk = true; 136 137 // now parse the non-empty comma separated list of expressions 138 while (1) { 139 ExprResult ArgExpr(ParseAssignmentExpression()); 140 if (ArgExpr.isInvalid()) { 141 ArgExprsOk = false; 142 SkipUntil(tok::r_paren); 143 break; 144 } else { 145 ArgExprs.push_back(ArgExpr.release()); 146 } 147 if (Tok.isNot(tok::comma)) 148 break; 149 ConsumeToken(); // Eat the comma, move to the next argument 150 } 151 if (ArgExprsOk && Tok.is(tok::r_paren)) { 152 ConsumeParen(); // ignore the right paren loc for now 153 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 154 ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size()); 155 } 156 } 157 } else { // not an identifier 158 switch (Tok.getKind()) { 159 case tok::r_paren: 160 // parse a possibly empty comma separated list of expressions 161 // __attribute__(( nonnull() )) 162 ConsumeParen(); // ignore the right paren loc for now 163 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 164 0, SourceLocation(), 0, 0); 165 break; 166 case tok::kw_char: 167 case tok::kw_wchar_t: 168 case tok::kw_char16_t: 169 case tok::kw_char32_t: 170 case tok::kw_bool: 171 case tok::kw_short: 172 case tok::kw_int: 173 case tok::kw_long: 174 case tok::kw___int64: 175 case tok::kw_signed: 176 case tok::kw_unsigned: 177 case tok::kw_float: 178 case tok::kw_double: 179 case tok::kw_void: 180 case tok::kw_typeof: { 181 AttributeList *attr 182 = attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 183 0, SourceLocation(), 0, 0); 184 if (attr->getKind() == AttributeList::AT_IBOutletCollection) 185 Diag(Tok, diag::err_iboutletcollection_builtintype); 186 // If it's a builtin type name, eat it and expect a rparen 187 // __attribute__(( vec_type_hint(char) )) 188 ConsumeToken(); 189 if (Tok.is(tok::r_paren)) 190 ConsumeParen(); 191 break; 192 } 193 default: 194 // __attribute__(( aligned(16) )) 195 ExprVector ArgExprs(Actions); 196 bool ArgExprsOk = true; 197 198 // now parse the list of expressions 199 while (1) { 200 ExprResult ArgExpr(ParseAssignmentExpression()); 201 if (ArgExpr.isInvalid()) { 202 ArgExprsOk = false; 203 SkipUntil(tok::r_paren); 204 break; 205 } else { 206 ArgExprs.push_back(ArgExpr.release()); 207 } 208 if (Tok.isNot(tok::comma)) 209 break; 210 ConsumeToken(); // Eat the comma, move to the next argument 211 } 212 // Match the ')'. 213 if (ArgExprsOk && Tok.is(tok::r_paren)) { 214 ConsumeParen(); // ignore the right paren loc for now 215 attrs.addNew(AttrName, AttrNameLoc, 0, 216 AttrNameLoc, 0, SourceLocation(), 217 ArgExprs.take(), ArgExprs.size()); 218 } 219 break; 220 } 221 } 222 } else { 223 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 224 0, SourceLocation(), 0, 0); 225 } 226 } 227 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 228 SkipUntil(tok::r_paren, false); 229 SourceLocation Loc = Tok.getLocation(); 230 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 231 SkipUntil(tok::r_paren, false); 232 } 233 if (endLoc) 234 *endLoc = Loc; 235 } 236} 237 238/// ParseMicrosoftDeclSpec - Parse an __declspec construct 239/// 240/// [MS] decl-specifier: 241/// __declspec ( extended-decl-modifier-seq ) 242/// 243/// [MS] extended-decl-modifier-seq: 244/// extended-decl-modifier[opt] 245/// extended-decl-modifier extended-decl-modifier-seq 246 247void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) { 248 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 249 250 ConsumeToken(); 251 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 252 "declspec")) { 253 SkipUntil(tok::r_paren, true); // skip until ) or ; 254 return; 255 } 256 while (Tok.getIdentifierInfo()) { 257 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 258 SourceLocation AttrNameLoc = ConsumeToken(); 259 if (Tok.is(tok::l_paren)) { 260 ConsumeParen(); 261 // FIXME: This doesn't parse __declspec(property(get=get_func_name)) 262 // correctly. 263 ExprResult ArgExpr(ParseAssignmentExpression()); 264 if (!ArgExpr.isInvalid()) { 265 Expr *ExprList = ArgExpr.take(); 266 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 267 SourceLocation(), &ExprList, 1, true); 268 } 269 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 270 SkipUntil(tok::r_paren, false); 271 } else { 272 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 273 0, SourceLocation(), 0, 0, true); 274 } 275 } 276 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 277 SkipUntil(tok::r_paren, false); 278 return; 279} 280 281void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) { 282 // Treat these like attributes 283 // FIXME: Allow Sema to distinguish between these and real attributes! 284 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) || 285 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) || 286 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) { 287 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 288 SourceLocation AttrNameLoc = ConsumeToken(); 289 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) 290 // FIXME: Support these properly! 291 continue; 292 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 293 SourceLocation(), 0, 0, true); 294 } 295} 296 297void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { 298 // Treat these like attributes 299 while (Tok.is(tok::kw___pascal)) { 300 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 301 SourceLocation AttrNameLoc = ConsumeToken(); 302 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 303 SourceLocation(), 0, 0, true); 304 } 305} 306 307void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) { 308 // Treat these like attributes 309 while (Tok.is(tok::kw___kernel)) { 310 SourceLocation AttrNameLoc = ConsumeToken(); 311 attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"), 312 AttrNameLoc, 0, AttrNameLoc, 0, 313 SourceLocation(), 0, 0, false); 314 } 315} 316 317void Parser::ParseOpenCLQualifiers(DeclSpec &DS) { 318 SourceLocation Loc = Tok.getLocation(); 319 switch(Tok.getKind()) { 320 // OpenCL qualifiers: 321 case tok::kw___private: 322 case tok::kw_private: 323 DS.getAttributes().addNewInteger( 324 Actions.getASTContext(), 325 PP.getIdentifierInfo("address_space"), Loc, 0); 326 break; 327 328 case tok::kw___global: 329 DS.getAttributes().addNewInteger( 330 Actions.getASTContext(), 331 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global); 332 break; 333 334 case tok::kw___local: 335 DS.getAttributes().addNewInteger( 336 Actions.getASTContext(), 337 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local); 338 break; 339 340 case tok::kw___constant: 341 DS.getAttributes().addNewInteger( 342 Actions.getASTContext(), 343 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant); 344 break; 345 346 case tok::kw___read_only: 347 DS.getAttributes().addNewInteger( 348 Actions.getASTContext(), 349 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only); 350 break; 351 352 case tok::kw___write_only: 353 DS.getAttributes().addNewInteger( 354 Actions.getASTContext(), 355 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only); 356 break; 357 358 case tok::kw___read_write: 359 DS.getAttributes().addNewInteger( 360 Actions.getASTContext(), 361 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write); 362 break; 363 default: break; 364 } 365} 366 367/// \brief Parse a version number. 368/// 369/// version: 370/// simple-integer 371/// simple-integer ',' simple-integer 372/// simple-integer ',' simple-integer ',' simple-integer 373VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { 374 Range = Tok.getLocation(); 375 376 if (!Tok.is(tok::numeric_constant)) { 377 Diag(Tok, diag::err_expected_version); 378 SkipUntil(tok::comma, tok::r_paren, true, true, true); 379 return VersionTuple(); 380 } 381 382 // Parse the major (and possibly minor and subminor) versions, which 383 // are stored in the numeric constant. We utilize a quirk of the 384 // lexer, which is that it handles something like 1.2.3 as a single 385 // numeric constant, rather than two separate tokens. 386 llvm::SmallString<512> Buffer; 387 Buffer.resize(Tok.getLength()+1); 388 const char *ThisTokBegin = &Buffer[0]; 389 390 // Get the spelling of the token, which eliminates trigraphs, etc. 391 bool Invalid = false; 392 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 393 if (Invalid) 394 return VersionTuple(); 395 396 // Parse the major version. 397 unsigned AfterMajor = 0; 398 unsigned Major = 0; 399 while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) { 400 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0'; 401 ++AfterMajor; 402 } 403 404 if (AfterMajor == 0) { 405 Diag(Tok, diag::err_expected_version); 406 SkipUntil(tok::comma, tok::r_paren, true, true, true); 407 return VersionTuple(); 408 } 409 410 if (AfterMajor == ActualLength) { 411 ConsumeToken(); 412 413 // We only had a single version component. 414 if (Major == 0) { 415 Diag(Tok, diag::err_zero_version); 416 return VersionTuple(); 417 } 418 419 return VersionTuple(Major); 420 } 421 422 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) { 423 Diag(Tok, diag::err_expected_version); 424 SkipUntil(tok::comma, tok::r_paren, true, true, true); 425 return VersionTuple(); 426 } 427 428 // Parse the minor version. 429 unsigned AfterMinor = AfterMajor + 1; 430 unsigned Minor = 0; 431 while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) { 432 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0'; 433 ++AfterMinor; 434 } 435 436 if (AfterMinor == ActualLength) { 437 ConsumeToken(); 438 439 // We had major.minor. 440 if (Major == 0 && Minor == 0) { 441 Diag(Tok, diag::err_zero_version); 442 return VersionTuple(); 443 } 444 445 return VersionTuple(Major, Minor); 446 } 447 448 // If what follows is not a '.', we have a problem. 449 if (ThisTokBegin[AfterMinor] != '.') { 450 Diag(Tok, diag::err_expected_version); 451 SkipUntil(tok::comma, tok::r_paren, true, true, true); 452 return VersionTuple(); 453 } 454 455 // Parse the subminor version. 456 unsigned AfterSubminor = AfterMinor + 1; 457 unsigned Subminor = 0; 458 while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) { 459 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0'; 460 ++AfterSubminor; 461 } 462 463 if (AfterSubminor != ActualLength) { 464 Diag(Tok, diag::err_expected_version); 465 SkipUntil(tok::comma, tok::r_paren, true, true, true); 466 return VersionTuple(); 467 } 468 ConsumeToken(); 469 return VersionTuple(Major, Minor, Subminor); 470} 471 472/// \brief Parse the contents of the "availability" attribute. 473/// 474/// availability-attribute: 475/// 'availability' '(' platform ',' version-arg-list ')' 476/// 477/// platform: 478/// identifier 479/// 480/// version-arg-list: 481/// version-arg 482/// version-arg ',' version-arg-list 483/// 484/// version-arg: 485/// 'introduced' '=' version 486/// 'deprecated' '=' version 487/// 'removed' = version 488/// 'unavailable' 489void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, 490 SourceLocation AvailabilityLoc, 491 ParsedAttributes &attrs, 492 SourceLocation *endLoc) { 493 SourceLocation PlatformLoc; 494 IdentifierInfo *Platform = 0; 495 496 enum { Introduced, Deprecated, Obsoleted, Unknown }; 497 AvailabilityChange Changes[Unknown]; 498 499 // Opening '('. 500 SourceLocation LParenLoc; 501 if (!Tok.is(tok::l_paren)) { 502 Diag(Tok, diag::err_expected_lparen); 503 return; 504 } 505 LParenLoc = ConsumeParen(); 506 507 // Parse the platform name, 508 if (Tok.isNot(tok::identifier)) { 509 Diag(Tok, diag::err_availability_expected_platform); 510 SkipUntil(tok::r_paren); 511 return; 512 } 513 Platform = Tok.getIdentifierInfo(); 514 PlatformLoc = ConsumeToken(); 515 516 // Parse the ',' following the platform name. 517 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren)) 518 return; 519 520 // If we haven't grabbed the pointers for the identifiers 521 // "introduced", "deprecated", and "obsoleted", do so now. 522 if (!Ident_introduced) { 523 Ident_introduced = PP.getIdentifierInfo("introduced"); 524 Ident_deprecated = PP.getIdentifierInfo("deprecated"); 525 Ident_obsoleted = PP.getIdentifierInfo("obsoleted"); 526 Ident_unavailable = PP.getIdentifierInfo("unavailable"); 527 } 528 529 // Parse the set of introductions/deprecations/removals. 530 SourceLocation UnavailableLoc; 531 do { 532 if (Tok.isNot(tok::identifier)) { 533 Diag(Tok, diag::err_availability_expected_change); 534 SkipUntil(tok::r_paren); 535 return; 536 } 537 IdentifierInfo *Keyword = Tok.getIdentifierInfo(); 538 SourceLocation KeywordLoc = ConsumeToken(); 539 540 if (Keyword == Ident_unavailable) { 541 if (UnavailableLoc.isValid()) { 542 Diag(KeywordLoc, diag::err_availability_redundant) 543 << Keyword << SourceRange(UnavailableLoc); 544 } 545 UnavailableLoc = KeywordLoc; 546 547 if (Tok.isNot(tok::comma)) 548 break; 549 550 ConsumeToken(); 551 continue; 552 } 553 554 if (Tok.isNot(tok::equal)) { 555 Diag(Tok, diag::err_expected_equal_after) 556 << Keyword; 557 SkipUntil(tok::r_paren); 558 return; 559 } 560 ConsumeToken(); 561 562 SourceRange VersionRange; 563 VersionTuple Version = ParseVersionTuple(VersionRange); 564 565 if (Version.empty()) { 566 SkipUntil(tok::r_paren); 567 return; 568 } 569 570 unsigned Index; 571 if (Keyword == Ident_introduced) 572 Index = Introduced; 573 else if (Keyword == Ident_deprecated) 574 Index = Deprecated; 575 else if (Keyword == Ident_obsoleted) 576 Index = Obsoleted; 577 else 578 Index = Unknown; 579 580 if (Index < Unknown) { 581 if (!Changes[Index].KeywordLoc.isInvalid()) { 582 Diag(KeywordLoc, diag::err_availability_redundant) 583 << Keyword 584 << SourceRange(Changes[Index].KeywordLoc, 585 Changes[Index].VersionRange.getEnd()); 586 } 587 588 Changes[Index].KeywordLoc = KeywordLoc; 589 Changes[Index].Version = Version; 590 Changes[Index].VersionRange = VersionRange; 591 } else { 592 Diag(KeywordLoc, diag::err_availability_unknown_change) 593 << Keyword << VersionRange; 594 } 595 596 if (Tok.isNot(tok::comma)) 597 break; 598 599 ConsumeToken(); 600 } while (true); 601 602 // Closing ')'. 603 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 604 if (RParenLoc.isInvalid()) 605 return; 606 607 if (endLoc) 608 *endLoc = RParenLoc; 609 610 // The 'unavailable' availability cannot be combined with any other 611 // availability changes. Make sure that hasn't happened. 612 if (UnavailableLoc.isValid()) { 613 bool Complained = false; 614 for (unsigned Index = Introduced; Index != Unknown; ++Index) { 615 if (Changes[Index].KeywordLoc.isValid()) { 616 if (!Complained) { 617 Diag(UnavailableLoc, diag::warn_availability_and_unavailable) 618 << SourceRange(Changes[Index].KeywordLoc, 619 Changes[Index].VersionRange.getEnd()); 620 Complained = true; 621 } 622 623 // Clear out the availability. 624 Changes[Index] = AvailabilityChange(); 625 } 626 } 627 } 628 629 // Record this attribute 630 attrs.addNew(&Availability, AvailabilityLoc, 631 0, SourceLocation(), 632 Platform, PlatformLoc, 633 Changes[Introduced], 634 Changes[Deprecated], 635 Changes[Obsoleted], 636 UnavailableLoc, false, false); 637} 638 639void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) { 640 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) 641 << attrs.Range; 642} 643 644/// ParseDeclaration - Parse a full 'declaration', which consists of 645/// declaration-specifiers, some number of declarators, and a semicolon. 646/// 'Context' should be a Declarator::TheContext value. This returns the 647/// location of the semicolon in DeclEnd. 648/// 649/// declaration: [C99 6.7] 650/// block-declaration -> 651/// simple-declaration 652/// others [FIXME] 653/// [C++] template-declaration 654/// [C++] namespace-definition 655/// [C++] using-directive 656/// [C++] using-declaration 657/// [C++0x/C1X] static_assert-declaration 658/// others... [FIXME] 659/// 660Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts, 661 unsigned Context, 662 SourceLocation &DeclEnd, 663 ParsedAttributesWithRange &attrs) { 664 ParenBraceBracketBalancer BalancerRAIIObj(*this); 665 666 Decl *SingleDecl = 0; 667 switch (Tok.getKind()) { 668 case tok::kw_template: 669 case tok::kw_export: 670 ProhibitAttributes(attrs); 671 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 672 break; 673 case tok::kw_inline: 674 // Could be the start of an inline namespace. Allowed as an ext in C++03. 675 if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) { 676 ProhibitAttributes(attrs); 677 SourceLocation InlineLoc = ConsumeToken(); 678 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc); 679 break; 680 } 681 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, 682 true); 683 case tok::kw_namespace: 684 ProhibitAttributes(attrs); 685 SingleDecl = ParseNamespace(Context, DeclEnd); 686 break; 687 case tok::kw_using: 688 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), 689 DeclEnd, attrs); 690 break; 691 case tok::kw_static_assert: 692 case tok::kw__Static_assert: 693 ProhibitAttributes(attrs); 694 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 695 break; 696 default: 697 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true); 698 } 699 700 // This routine returns a DeclGroup, if the thing we parsed only contains a 701 // single decl, convert it now. 702 return Actions.ConvertDeclToDeclGroup(SingleDecl); 703} 704 705/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 706/// declaration-specifiers init-declarator-list[opt] ';' 707///[C90/C++]init-declarator-list ';' [TODO] 708/// [OMP] threadprivate-directive [TODO] 709/// 710/// for-range-declaration: [C++0x 6.5p1: stmt.ranged] 711/// attribute-specifier-seq[opt] type-specifier-seq declarator 712/// 713/// If RequireSemi is false, this does not check for a ';' at the end of the 714/// declaration. If it is true, it checks for and eats it. 715/// 716/// If FRI is non-null, we might be parsing a for-range-declaration instead 717/// of a simple-declaration. If we find that we are, we also parse the 718/// for-range-initializer, and place it here. 719Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts, 720 unsigned Context, 721 SourceLocation &DeclEnd, 722 ParsedAttributes &attrs, 723 bool RequireSemi, 724 ForRangeInit *FRI) { 725 // Parse the common declaration-specifiers piece. 726 ParsingDeclSpec DS(*this); 727 DS.takeAttributesFrom(attrs); 728 729 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, 730 getDeclSpecContextFromDeclaratorContext(Context)); 731 StmtResult R = Actions.ActOnVlaStmt(DS); 732 if (R.isUsable()) 733 Stmts.push_back(R.release()); 734 735 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 736 // declaration-specifiers init-declarator-list[opt] ';' 737 if (Tok.is(tok::semi)) { 738 if (RequireSemi) ConsumeToken(); 739 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 740 DS); 741 DS.complete(TheDecl); 742 return Actions.ConvertDeclToDeclGroup(TheDecl); 743 } 744 745 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI); 746} 747 748/// ParseDeclGroup - Having concluded that this is either a function 749/// definition or a group of object declarations, actually parse the 750/// result. 751Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, 752 unsigned Context, 753 bool AllowFunctionDefinitions, 754 SourceLocation *DeclEnd, 755 ForRangeInit *FRI) { 756 // Parse the first declarator. 757 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context)); 758 ParseDeclarator(D); 759 760 // Bail out if the first declarator didn't seem well-formed. 761 if (!D.hasName() && !D.mayOmitIdentifier()) { 762 // Skip until ; or }. 763 SkipUntil(tok::r_brace, true, true); 764 if (Tok.is(tok::semi)) 765 ConsumeToken(); 766 return DeclGroupPtrTy(); 767 } 768 769 // Check to see if we have a function *definition* which must have a body. 770 if (AllowFunctionDefinitions && D.isFunctionDeclarator() && 771 // Look at the next token to make sure that this isn't a function 772 // declaration. We have to check this because __attribute__ might be the 773 // start of a function definition in GCC-extended K&R C. 774 !isDeclarationAfterDeclarator()) { 775 776 if (isStartOfFunctionDefinition(D)) { 777 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 778 Diag(Tok, diag::err_function_declared_typedef); 779 780 // Recover by treating the 'typedef' as spurious. 781 DS.ClearStorageClassSpecs(); 782 } 783 784 Decl *TheDecl = ParseFunctionDefinition(D); 785 return Actions.ConvertDeclToDeclGroup(TheDecl); 786 } 787 788 if (isDeclarationSpecifier()) { 789 // If there is an invalid declaration specifier right after the function 790 // prototype, then we must be in a missing semicolon case where this isn't 791 // actually a body. Just fall through into the code that handles it as a 792 // prototype, and let the top-level code handle the erroneous declspec 793 // where it would otherwise expect a comma or semicolon. 794 } else { 795 Diag(Tok, diag::err_expected_fn_body); 796 SkipUntil(tok::semi); 797 return DeclGroupPtrTy(); 798 } 799 } 800 801 if (ParseAttributesAfterDeclarator(D)) 802 return DeclGroupPtrTy(); 803 804 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we 805 // must parse and analyze the for-range-initializer before the declaration is 806 // analyzed. 807 if (FRI && Tok.is(tok::colon)) { 808 FRI->ColonLoc = ConsumeToken(); 809 // FIXME: handle braced-init-list here. 810 FRI->RangeExpr = ParseExpression(); 811 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 812 Actions.ActOnCXXForRangeDecl(ThisDecl); 813 Actions.FinalizeDeclaration(ThisDecl); 814 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1); 815 } 816 817 llvm::SmallVector<Decl *, 8> DeclsInGroup; 818 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D); 819 D.complete(FirstDecl); 820 if (FirstDecl) 821 DeclsInGroup.push_back(FirstDecl); 822 823 // If we don't have a comma, it is either the end of the list (a ';') or an 824 // error, bail out. 825 while (Tok.is(tok::comma)) { 826 // Consume the comma. 827 ConsumeToken(); 828 829 // Parse the next declarator. 830 D.clear(); 831 832 // Accept attributes in an init-declarator. In the first declarator in a 833 // declaration, these would be part of the declspec. In subsequent 834 // declarators, they become part of the declarator itself, so that they 835 // don't apply to declarators after *this* one. Examples: 836 // short __attribute__((common)) var; -> declspec 837 // short var __attribute__((common)); -> declarator 838 // short x, __attribute__((common)) var; -> declarator 839 MaybeParseGNUAttributes(D); 840 841 ParseDeclarator(D); 842 843 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 844 D.complete(ThisDecl); 845 if (ThisDecl) 846 DeclsInGroup.push_back(ThisDecl); 847 } 848 849 if (DeclEnd) 850 *DeclEnd = Tok.getLocation(); 851 852 if (Context != Declarator::ForContext && 853 ExpectAndConsume(tok::semi, 854 Context == Declarator::FileContext 855 ? diag::err_invalid_token_after_toplevel_declarator 856 : diag::err_expected_semi_declaration)) { 857 // Okay, there was no semicolon and one was expected. If we see a 858 // declaration specifier, just assume it was missing and continue parsing. 859 // Otherwise things are very confused and we skip to recover. 860 if (!isDeclarationSpecifier()) { 861 SkipUntil(tok::r_brace, true, true); 862 if (Tok.is(tok::semi)) 863 ConsumeToken(); 864 } 865 } 866 867 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, 868 DeclsInGroup.data(), 869 DeclsInGroup.size()); 870} 871 872/// Parse an optional simple-asm-expr and attributes, and attach them to a 873/// declarator. Returns true on an error. 874bool Parser::ParseAttributesAfterDeclarator(Declarator &D) { 875 // If a simple-asm-expr is present, parse it. 876 if (Tok.is(tok::kw_asm)) { 877 SourceLocation Loc; 878 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 879 if (AsmLabel.isInvalid()) { 880 SkipUntil(tok::semi, true, true); 881 return true; 882 } 883 884 D.setAsmLabel(AsmLabel.release()); 885 D.SetRangeEnd(Loc); 886 } 887 888 MaybeParseGNUAttributes(D); 889 return false; 890} 891 892/// \brief Parse 'declaration' after parsing 'declaration-specifiers 893/// declarator'. This method parses the remainder of the declaration 894/// (including any attributes or initializer, among other things) and 895/// finalizes the declaration. 896/// 897/// init-declarator: [C99 6.7] 898/// declarator 899/// declarator '=' initializer 900/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 901/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 902/// [C++] declarator initializer[opt] 903/// 904/// [C++] initializer: 905/// [C++] '=' initializer-clause 906/// [C++] '(' expression-list ')' 907/// [C++0x] '=' 'default' [TODO] 908/// [C++0x] '=' 'delete' 909/// 910/// According to the standard grammar, =default and =delete are function 911/// definitions, but that definitely doesn't fit with the parser here. 912/// 913Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D, 914 const ParsedTemplateInfo &TemplateInfo) { 915 if (ParseAttributesAfterDeclarator(D)) 916 return 0; 917 918 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); 919} 920 921Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D, 922 const ParsedTemplateInfo &TemplateInfo) { 923 // Inform the current actions module that we just parsed this declarator. 924 Decl *ThisDecl = 0; 925 switch (TemplateInfo.Kind) { 926 case ParsedTemplateInfo::NonTemplate: 927 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 928 break; 929 930 case ParsedTemplateInfo::Template: 931 case ParsedTemplateInfo::ExplicitSpecialization: 932 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 933 MultiTemplateParamsArg(Actions, 934 TemplateInfo.TemplateParams->data(), 935 TemplateInfo.TemplateParams->size()), 936 D); 937 break; 938 939 case ParsedTemplateInfo::ExplicitInstantiation: { 940 DeclResult ThisRes 941 = Actions.ActOnExplicitInstantiation(getCurScope(), 942 TemplateInfo.ExternLoc, 943 TemplateInfo.TemplateLoc, 944 D); 945 if (ThisRes.isInvalid()) { 946 SkipUntil(tok::semi, true, true); 947 return 0; 948 } 949 950 ThisDecl = ThisRes.get(); 951 break; 952 } 953 } 954 955 bool TypeContainsAuto = 956 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 957 958 // Parse declarator '=' initializer. 959 if (isTokenEqualOrMistypedEqualEqual( 960 diag::err_invalid_equalequal_after_declarator)) { 961 ConsumeToken(); 962 if (Tok.is(tok::kw_delete)) { 963 SourceLocation DelLoc = ConsumeToken(); 964 965 if (!getLang().CPlusPlus0x) 966 Diag(DelLoc, diag::warn_deleted_function_accepted_as_extension); 967 968 Actions.SetDeclDeleted(ThisDecl, DelLoc); 969 } else { 970 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 971 EnterScope(0); 972 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 973 } 974 975 if (Tok.is(tok::code_completion)) { 976 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 977 ConsumeCodeCompletionToken(); 978 SkipUntil(tok::comma, true, true); 979 return ThisDecl; 980 } 981 982 ExprResult Init(ParseInitializer()); 983 984 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 985 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 986 ExitScope(); 987 } 988 989 if (Init.isInvalid()) { 990 SkipUntil(tok::comma, true, true); 991 Actions.ActOnInitializerError(ThisDecl); 992 } else 993 Actions.AddInitializerToDecl(ThisDecl, Init.take(), 994 /*DirectInit=*/false, TypeContainsAuto); 995 } 996 } else if (Tok.is(tok::l_paren)) { 997 // Parse C++ direct initializer: '(' expression-list ')' 998 SourceLocation LParenLoc = ConsumeParen(); 999 ExprVector Exprs(Actions); 1000 CommaLocsTy CommaLocs; 1001 1002 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1003 EnterScope(0); 1004 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 1005 } 1006 1007 if (ParseExpressionList(Exprs, CommaLocs)) { 1008 SkipUntil(tok::r_paren); 1009 1010 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1011 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1012 ExitScope(); 1013 } 1014 } else { 1015 // Match the ')'. 1016 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1017 1018 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 1019 "Unexpected number of commas!"); 1020 1021 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 1022 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 1023 ExitScope(); 1024 } 1025 1026 Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc, 1027 move_arg(Exprs), 1028 RParenLoc, 1029 TypeContainsAuto); 1030 } 1031 } else { 1032 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); 1033 } 1034 1035 Actions.FinalizeDeclaration(ThisDecl); 1036 1037 return ThisDecl; 1038} 1039 1040/// ParseSpecifierQualifierList 1041/// specifier-qualifier-list: 1042/// type-specifier specifier-qualifier-list[opt] 1043/// type-qualifier specifier-qualifier-list[opt] 1044/// [GNU] attributes specifier-qualifier-list[opt] 1045/// 1046void Parser::ParseSpecifierQualifierList(DeclSpec &DS) { 1047 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 1048 /// parse declaration-specifiers and complain about extra stuff. 1049 ParseDeclarationSpecifiers(DS); 1050 1051 // Validate declspec for type-name. 1052 unsigned Specs = DS.getParsedSpecifiers(); 1053 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && 1054 !DS.hasAttributes()) 1055 Diag(Tok, diag::err_typename_requires_specqual); 1056 1057 // Issue diagnostic and remove storage class if present. 1058 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 1059 if (DS.getStorageClassSpecLoc().isValid()) 1060 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 1061 else 1062 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); 1063 DS.ClearStorageClassSpecs(); 1064 } 1065 1066 // Issue diagnostic and remove function specfier if present. 1067 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 1068 if (DS.isInlineSpecified()) 1069 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 1070 if (DS.isVirtualSpecified()) 1071 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 1072 if (DS.isExplicitSpecified()) 1073 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 1074 DS.ClearFunctionSpecs(); 1075 } 1076} 1077 1078/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 1079/// specified token is valid after the identifier in a declarator which 1080/// immediately follows the declspec. For example, these things are valid: 1081/// 1082/// int x [ 4]; // direct-declarator 1083/// int x ( int y); // direct-declarator 1084/// int(int x ) // direct-declarator 1085/// int x ; // simple-declaration 1086/// int x = 17; // init-declarator-list 1087/// int x , y; // init-declarator-list 1088/// int x __asm__ ("foo"); // init-declarator-list 1089/// int x : 4; // struct-declarator 1090/// int x { 5}; // C++'0x unified initializers 1091/// 1092/// This is not, because 'x' does not immediately follow the declspec (though 1093/// ')' happens to be valid anyway). 1094/// int (x) 1095/// 1096static bool isValidAfterIdentifierInDeclarator(const Token &T) { 1097 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) || 1098 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) || 1099 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon); 1100} 1101 1102 1103/// ParseImplicitInt - This method is called when we have an non-typename 1104/// identifier in a declspec (which normally terminates the decl spec) when 1105/// the declspec has no type specifier. In this case, the declspec is either 1106/// malformed or is "implicit int" (in K&R and C89). 1107/// 1108/// This method handles diagnosing this prettily and returns false if the 1109/// declspec is done being processed. If it recovers and thinks there may be 1110/// other pieces of declspec after it, it returns true. 1111/// 1112bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 1113 const ParsedTemplateInfo &TemplateInfo, 1114 AccessSpecifier AS) { 1115 assert(Tok.is(tok::identifier) && "should have identifier"); 1116 1117 SourceLocation Loc = Tok.getLocation(); 1118 // If we see an identifier that is not a type name, we normally would 1119 // parse it as the identifer being declared. However, when a typename 1120 // is typo'd or the definition is not included, this will incorrectly 1121 // parse the typename as the identifier name and fall over misparsing 1122 // later parts of the diagnostic. 1123 // 1124 // As such, we try to do some look-ahead in cases where this would 1125 // otherwise be an "implicit-int" case to see if this is invalid. For 1126 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 1127 // an identifier with implicit int, we'd get a parse error because the 1128 // next token is obviously invalid for a type. Parse these as a case 1129 // with an invalid type specifier. 1130 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 1131 1132 // Since we know that this either implicit int (which is rare) or an 1133 // error, we'd do lookahead to try to do better recovery. 1134 if (isValidAfterIdentifierInDeclarator(NextToken())) { 1135 // If this token is valid for implicit int, e.g. "static x = 4", then 1136 // we just avoid eating the identifier, so it will be parsed as the 1137 // identifier in the declarator. 1138 return false; 1139 } 1140 1141 // Otherwise, if we don't consume this token, we are going to emit an 1142 // error anyway. Try to recover from various common problems. Check 1143 // to see if this was a reference to a tag name without a tag specified. 1144 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 1145 // 1146 // C++ doesn't need this, and isTagName doesn't take SS. 1147 if (SS == 0) { 1148 const char *TagName = 0, *FixitTagName = 0; 1149 tok::TokenKind TagKind = tok::unknown; 1150 1151 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 1152 default: break; 1153 case DeclSpec::TST_enum: 1154 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break; 1155 case DeclSpec::TST_union: 1156 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break; 1157 case DeclSpec::TST_struct: 1158 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break; 1159 case DeclSpec::TST_class: 1160 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break; 1161 } 1162 1163 if (TagName) { 1164 Diag(Loc, diag::err_use_of_tag_name_without_tag) 1165 << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus 1166 << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName); 1167 1168 // Parse this as a tag as if the missing tag were present. 1169 if (TagKind == tok::kw_enum) 1170 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS); 1171 else 1172 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS); 1173 return true; 1174 } 1175 } 1176 1177 // This is almost certainly an invalid type name. Let the action emit a 1178 // diagnostic and attempt to recover. 1179 ParsedType T; 1180 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc, 1181 getCurScope(), SS, T)) { 1182 // The action emitted a diagnostic, so we don't have to. 1183 if (T) { 1184 // The action has suggested that the type T could be used. Set that as 1185 // the type in the declaration specifiers, consume the would-be type 1186 // name token, and we're done. 1187 const char *PrevSpec; 1188 unsigned DiagID; 1189 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T); 1190 DS.SetRangeEnd(Tok.getLocation()); 1191 ConsumeToken(); 1192 1193 // There may be other declaration specifiers after this. 1194 return true; 1195 } 1196 1197 // Fall through; the action had no suggestion for us. 1198 } else { 1199 // The action did not emit a diagnostic, so emit one now. 1200 SourceRange R; 1201 if (SS) R = SS->getRange(); 1202 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R; 1203 } 1204 1205 // Mark this as an error. 1206 const char *PrevSpec; 1207 unsigned DiagID; 1208 DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID); 1209 DS.SetRangeEnd(Tok.getLocation()); 1210 ConsumeToken(); 1211 1212 // TODO: Could inject an invalid typedef decl in an enclosing scope to 1213 // avoid rippling error messages on subsequent uses of the same type, 1214 // could be useful if #include was forgotten. 1215 return false; 1216} 1217 1218/// \brief Determine the declaration specifier context from the declarator 1219/// context. 1220/// 1221/// \param Context the declarator context, which is one of the 1222/// Declarator::TheContext enumerator values. 1223Parser::DeclSpecContext 1224Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { 1225 if (Context == Declarator::MemberContext) 1226 return DSC_class; 1227 if (Context == Declarator::FileContext) 1228 return DSC_top_level; 1229 return DSC_normal; 1230} 1231 1232/// ParseDeclarationSpecifiers 1233/// declaration-specifiers: [C99 6.7] 1234/// storage-class-specifier declaration-specifiers[opt] 1235/// type-specifier declaration-specifiers[opt] 1236/// [C99] function-specifier declaration-specifiers[opt] 1237/// [GNU] attributes declaration-specifiers[opt] 1238/// 1239/// storage-class-specifier: [C99 6.7.1] 1240/// 'typedef' 1241/// 'extern' 1242/// 'static' 1243/// 'auto' 1244/// 'register' 1245/// [C++] 'mutable' 1246/// [GNU] '__thread' 1247/// function-specifier: [C99 6.7.4] 1248/// [C99] 'inline' 1249/// [C++] 'virtual' 1250/// [C++] 'explicit' 1251/// [OpenCL] '__kernel' 1252/// 'friend': [C++ dcl.friend] 1253/// 'constexpr': [C++0x dcl.constexpr] 1254 1255/// 1256void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 1257 const ParsedTemplateInfo &TemplateInfo, 1258 AccessSpecifier AS, 1259 DeclSpecContext DSContext) { 1260 if (DS.getSourceRange().isInvalid()) { 1261 DS.SetRangeStart(Tok.getLocation()); 1262 DS.SetRangeEnd(Tok.getLocation()); 1263 } 1264 1265 while (1) { 1266 bool isInvalid = false; 1267 const char *PrevSpec = 0; 1268 unsigned DiagID = 0; 1269 1270 SourceLocation Loc = Tok.getLocation(); 1271 1272 switch (Tok.getKind()) { 1273 default: 1274 DoneWithDeclSpec: 1275 // If this is not a declaration specifier token, we're done reading decl 1276 // specifiers. First verify that DeclSpec's are consistent. 1277 DS.Finish(Diags, PP); 1278 return; 1279 1280 case tok::code_completion: { 1281 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 1282 if (DS.hasTypeSpecifier()) { 1283 bool AllowNonIdentifiers 1284 = (getCurScope()->getFlags() & (Scope::ControlScope | 1285 Scope::BlockScope | 1286 Scope::TemplateParamScope | 1287 Scope::FunctionPrototypeScope | 1288 Scope::AtCatchScope)) == 0; 1289 bool AllowNestedNameSpecifiers 1290 = DSContext == DSC_top_level || 1291 (DSContext == DSC_class && DS.isFriendSpecified()); 1292 1293 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 1294 AllowNonIdentifiers, 1295 AllowNestedNameSpecifiers); 1296 ConsumeCodeCompletionToken(); 1297 return; 1298 } 1299 1300 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) 1301 CCC = Sema::PCC_LocalDeclarationSpecifiers; 1302 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 1303 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate 1304 : Sema::PCC_Template; 1305 else if (DSContext == DSC_class) 1306 CCC = Sema::PCC_Class; 1307 else if (ObjCImpDecl) 1308 CCC = Sema::PCC_ObjCImplementation; 1309 1310 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 1311 ConsumeCodeCompletionToken(); 1312 return; 1313 } 1314 1315 case tok::coloncolon: // ::foo::bar 1316 // C++ scope specifier. Annotate and loop, or bail out on error. 1317 if (TryAnnotateCXXScopeToken(true)) { 1318 if (!DS.hasTypeSpecifier()) 1319 DS.SetTypeSpecError(); 1320 goto DoneWithDeclSpec; 1321 } 1322 if (Tok.is(tok::coloncolon)) // ::new or ::delete 1323 goto DoneWithDeclSpec; 1324 continue; 1325 1326 case tok::annot_cxxscope: { 1327 if (DS.hasTypeSpecifier()) 1328 goto DoneWithDeclSpec; 1329 1330 CXXScopeSpec SS; 1331 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 1332 Tok.getAnnotationRange(), 1333 SS); 1334 1335 // We are looking for a qualified typename. 1336 Token Next = NextToken(); 1337 if (Next.is(tok::annot_template_id) && 1338 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 1339 ->Kind == TNK_Type_template) { 1340 // We have a qualified template-id, e.g., N::A<int> 1341 1342 // C++ [class.qual]p2: 1343 // In a lookup in which the constructor is an acceptable lookup 1344 // result and the nested-name-specifier nominates a class C: 1345 // 1346 // - if the name specified after the 1347 // nested-name-specifier, when looked up in C, is the 1348 // injected-class-name of C (Clause 9), or 1349 // 1350 // - if the name specified after the nested-name-specifier 1351 // is the same as the identifier or the 1352 // simple-template-id's template-name in the last 1353 // component of the nested-name-specifier, 1354 // 1355 // the name is instead considered to name the constructor of 1356 // class C. 1357 // 1358 // Thus, if the template-name is actually the constructor 1359 // name, then the code is ill-formed; this interpretation is 1360 // reinforced by the NAD status of core issue 635. 1361 TemplateIdAnnotation *TemplateId 1362 = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()); 1363 if ((DSContext == DSC_top_level || 1364 (DSContext == DSC_class && DS.isFriendSpecified())) && 1365 TemplateId->Name && 1366 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 1367 if (isConstructorDeclarator()) { 1368 // The user meant this to be an out-of-line constructor 1369 // definition, but template arguments are not allowed 1370 // there. Just allow this as a constructor; we'll 1371 // complain about it later. 1372 goto DoneWithDeclSpec; 1373 } 1374 1375 // The user meant this to name a type, but it actually names 1376 // a constructor with some extraneous template 1377 // arguments. Complain, then parse it as a type as the user 1378 // intended. 1379 Diag(TemplateId->TemplateNameLoc, 1380 diag::err_out_of_line_template_id_names_constructor) 1381 << TemplateId->Name; 1382 } 1383 1384 DS.getTypeSpecScope() = SS; 1385 ConsumeToken(); // The C++ scope. 1386 assert(Tok.is(tok::annot_template_id) && 1387 "ParseOptionalCXXScopeSpecifier not working"); 1388 AnnotateTemplateIdTokenAsType(); 1389 continue; 1390 } 1391 1392 if (Next.is(tok::annot_typename)) { 1393 DS.getTypeSpecScope() = SS; 1394 ConsumeToken(); // The C++ scope. 1395 if (Tok.getAnnotationValue()) { 1396 ParsedType T = getTypeAnnotation(Tok); 1397 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 1398 Tok.getAnnotationEndLoc(), 1399 PrevSpec, DiagID, T); 1400 } 1401 else 1402 DS.SetTypeSpecError(); 1403 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1404 ConsumeToken(); // The typename 1405 } 1406 1407 if (Next.isNot(tok::identifier)) 1408 goto DoneWithDeclSpec; 1409 1410 // If we're in a context where the identifier could be a class name, 1411 // check whether this is a constructor declaration. 1412 if ((DSContext == DSC_top_level || 1413 (DSContext == DSC_class && DS.isFriendSpecified())) && 1414 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 1415 &SS)) { 1416 if (isConstructorDeclarator()) 1417 goto DoneWithDeclSpec; 1418 1419 // As noted in C++ [class.qual]p2 (cited above), when the name 1420 // of the class is qualified in a context where it could name 1421 // a constructor, its a constructor name. However, we've 1422 // looked at the declarator, and the user probably meant this 1423 // to be a type. Complain that it isn't supposed to be treated 1424 // as a type, then proceed to parse it as a type. 1425 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 1426 << Next.getIdentifierInfo(); 1427 } 1428 1429 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 1430 Next.getLocation(), 1431 getCurScope(), &SS, 1432 false, false, ParsedType(), 1433 /*NonTrivialSourceInfo=*/true); 1434 1435 // If the referenced identifier is not a type, then this declspec is 1436 // erroneous: We already checked about that it has no type specifier, and 1437 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 1438 // typename. 1439 if (TypeRep == 0) { 1440 ConsumeToken(); // Eat the scope spec so the identifier is current. 1441 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue; 1442 goto DoneWithDeclSpec; 1443 } 1444 1445 DS.getTypeSpecScope() = SS; 1446 ConsumeToken(); // The C++ scope. 1447 1448 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1449 DiagID, TypeRep); 1450 if (isInvalid) 1451 break; 1452 1453 DS.SetRangeEnd(Tok.getLocation()); 1454 ConsumeToken(); // The typename. 1455 1456 continue; 1457 } 1458 1459 case tok::annot_typename: { 1460 if (Tok.getAnnotationValue()) { 1461 ParsedType T = getTypeAnnotation(Tok); 1462 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1463 DiagID, T); 1464 } else 1465 DS.SetTypeSpecError(); 1466 1467 if (isInvalid) 1468 break; 1469 1470 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1471 ConsumeToken(); // The typename 1472 1473 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1474 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1475 // Objective-C interface. 1476 if (Tok.is(tok::less) && getLang().ObjC1) 1477 ParseObjCProtocolQualifiers(DS); 1478 1479 continue; 1480 } 1481 1482 // typedef-name 1483 case tok::identifier: { 1484 // In C++, check to see if this is a scope specifier like foo::bar::, if 1485 // so handle it as such. This is important for ctor parsing. 1486 if (getLang().CPlusPlus) { 1487 if (TryAnnotateCXXScopeToken(true)) { 1488 if (!DS.hasTypeSpecifier()) 1489 DS.SetTypeSpecError(); 1490 goto DoneWithDeclSpec; 1491 } 1492 if (!Tok.is(tok::identifier)) 1493 continue; 1494 } 1495 1496 // This identifier can only be a typedef name if we haven't already seen 1497 // a type-specifier. Without this check we misparse: 1498 // typedef int X; struct Y { short X; }; as 'short int'. 1499 if (DS.hasTypeSpecifier()) 1500 goto DoneWithDeclSpec; 1501 1502 // Check for need to substitute AltiVec keyword tokens. 1503 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 1504 break; 1505 1506 // It has to be available as a typedef too! 1507 ParsedType TypeRep = 1508 Actions.getTypeName(*Tok.getIdentifierInfo(), 1509 Tok.getLocation(), getCurScope()); 1510 1511 // If this is not a typedef name, don't parse it as part of the declspec, 1512 // it must be an implicit int or an error. 1513 if (!TypeRep) { 1514 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue; 1515 goto DoneWithDeclSpec; 1516 } 1517 1518 // If we're in a context where the identifier could be a class name, 1519 // check whether this is a constructor declaration. 1520 if (getLang().CPlusPlus && DSContext == DSC_class && 1521 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 1522 isConstructorDeclarator()) 1523 goto DoneWithDeclSpec; 1524 1525 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1526 DiagID, TypeRep); 1527 if (isInvalid) 1528 break; 1529 1530 DS.SetRangeEnd(Tok.getLocation()); 1531 ConsumeToken(); // The identifier 1532 1533 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1534 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1535 // Objective-C interface. 1536 if (Tok.is(tok::less) && getLang().ObjC1) 1537 ParseObjCProtocolQualifiers(DS); 1538 1539 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1540 // If a type specifier follows, it will be diagnosed elsewhere. 1541 continue; 1542 } 1543 1544 // type-name 1545 case tok::annot_template_id: { 1546 TemplateIdAnnotation *TemplateId 1547 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1548 if (TemplateId->Kind != TNK_Type_template) { 1549 // This template-id does not refer to a type name, so we're 1550 // done with the type-specifiers. 1551 goto DoneWithDeclSpec; 1552 } 1553 1554 // If we're in a context where the template-id could be a 1555 // constructor name or specialization, check whether this is a 1556 // constructor declaration. 1557 if (getLang().CPlusPlus && DSContext == DSC_class && 1558 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 1559 isConstructorDeclarator()) 1560 goto DoneWithDeclSpec; 1561 1562 // Turn the template-id annotation token into a type annotation 1563 // token, then try again to parse it as a type-specifier. 1564 AnnotateTemplateIdTokenAsType(); 1565 continue; 1566 } 1567 1568 // GNU attributes support. 1569 case tok::kw___attribute: 1570 ParseGNUAttributes(DS.getAttributes()); 1571 continue; 1572 1573 // Microsoft declspec support. 1574 case tok::kw___declspec: 1575 ParseMicrosoftDeclSpec(DS.getAttributes()); 1576 continue; 1577 1578 // Microsoft single token adornments. 1579 case tok::kw___forceinline: 1580 // FIXME: Add handling here! 1581 break; 1582 1583 case tok::kw___ptr64: 1584 case tok::kw___w64: 1585 case tok::kw___cdecl: 1586 case tok::kw___stdcall: 1587 case tok::kw___fastcall: 1588 case tok::kw___thiscall: 1589 ParseMicrosoftTypeAttributes(DS.getAttributes()); 1590 continue; 1591 1592 // Borland single token adornments. 1593 case tok::kw___pascal: 1594 ParseBorlandTypeAttributes(DS.getAttributes()); 1595 continue; 1596 1597 // OpenCL single token adornments. 1598 case tok::kw___kernel: 1599 ParseOpenCLAttributes(DS.getAttributes()); 1600 continue; 1601 1602 // storage-class-specifier 1603 case tok::kw_typedef: 1604 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec, 1605 DiagID, getLang()); 1606 break; 1607 case tok::kw_extern: 1608 if (DS.isThreadSpecified()) 1609 Diag(Tok, diag::ext_thread_before) << "extern"; 1610 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec, 1611 DiagID, getLang()); 1612 break; 1613 case tok::kw___private_extern__: 1614 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc, 1615 PrevSpec, DiagID, getLang()); 1616 break; 1617 case tok::kw_static: 1618 if (DS.isThreadSpecified()) 1619 Diag(Tok, diag::ext_thread_before) << "static"; 1620 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec, 1621 DiagID, getLang()); 1622 break; 1623 case tok::kw_auto: 1624 if (getLang().CPlusPlus0x) { 1625 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 1626 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec, 1627 DiagID, getLang()); 1628 if (!isInvalid) 1629 Diag(Tok, diag::auto_storage_class) 1630 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 1631 } 1632 else 1633 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 1634 DiagID); 1635 } 1636 else 1637 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec, 1638 DiagID, getLang()); 1639 break; 1640 case tok::kw_register: 1641 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec, 1642 DiagID, getLang()); 1643 break; 1644 case tok::kw_mutable: 1645 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec, 1646 DiagID, getLang()); 1647 break; 1648 case tok::kw___thread: 1649 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); 1650 break; 1651 1652 // function-specifier 1653 case tok::kw_inline: 1654 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 1655 break; 1656 case tok::kw_virtual: 1657 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID); 1658 break; 1659 case tok::kw_explicit: 1660 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID); 1661 break; 1662 1663 // friend 1664 case tok::kw_friend: 1665 if (DSContext == DSC_class) 1666 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 1667 else { 1668 PrevSpec = ""; // not actually used by the diagnostic 1669 DiagID = diag::err_friend_invalid_in_context; 1670 isInvalid = true; 1671 } 1672 break; 1673 1674 // constexpr 1675 case tok::kw_constexpr: 1676 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 1677 break; 1678 1679 // type-specifier 1680 case tok::kw_short: 1681 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 1682 DiagID); 1683 break; 1684 case tok::kw_long: 1685 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1686 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1687 DiagID); 1688 else 1689 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1690 DiagID); 1691 break; 1692 case tok::kw___int64: 1693 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1694 DiagID); 1695 break; 1696 case tok::kw_signed: 1697 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 1698 DiagID); 1699 break; 1700 case tok::kw_unsigned: 1701 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1702 DiagID); 1703 break; 1704 case tok::kw__Complex: 1705 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1706 DiagID); 1707 break; 1708 case tok::kw__Imaginary: 1709 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1710 DiagID); 1711 break; 1712 case tok::kw_void: 1713 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 1714 DiagID); 1715 break; 1716 case tok::kw_char: 1717 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 1718 DiagID); 1719 break; 1720 case tok::kw_int: 1721 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 1722 DiagID); 1723 break; 1724 case tok::kw_float: 1725 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 1726 DiagID); 1727 break; 1728 case tok::kw_double: 1729 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 1730 DiagID); 1731 break; 1732 case tok::kw_wchar_t: 1733 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 1734 DiagID); 1735 break; 1736 case tok::kw_char16_t: 1737 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 1738 DiagID); 1739 break; 1740 case tok::kw_char32_t: 1741 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 1742 DiagID); 1743 break; 1744 case tok::kw_bool: 1745 case tok::kw__Bool: 1746 if (Tok.is(tok::kw_bool) && 1747 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 1748 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1749 PrevSpec = ""; // Not used by the diagnostic. 1750 DiagID = diag::err_bool_redeclaration; 1751 // For better error recovery. 1752 Tok.setKind(tok::identifier); 1753 isInvalid = true; 1754 } else { 1755 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 1756 DiagID); 1757 } 1758 break; 1759 case tok::kw__Decimal32: 1760 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1761 DiagID); 1762 break; 1763 case tok::kw__Decimal64: 1764 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1765 DiagID); 1766 break; 1767 case tok::kw__Decimal128: 1768 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1769 DiagID); 1770 break; 1771 case tok::kw___vector: 1772 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 1773 break; 1774 case tok::kw___pixel: 1775 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 1776 break; 1777 case tok::kw___unknown_anytype: 1778 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, 1779 PrevSpec, DiagID); 1780 break; 1781 1782 // class-specifier: 1783 case tok::kw_class: 1784 case tok::kw_struct: 1785 case tok::kw_union: { 1786 tok::TokenKind Kind = Tok.getKind(); 1787 ConsumeToken(); 1788 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS); 1789 continue; 1790 } 1791 1792 // enum-specifier: 1793 case tok::kw_enum: 1794 ConsumeToken(); 1795 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS); 1796 continue; 1797 1798 // cv-qualifier: 1799 case tok::kw_const: 1800 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 1801 getLang()); 1802 break; 1803 case tok::kw_volatile: 1804 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 1805 getLang()); 1806 break; 1807 case tok::kw_restrict: 1808 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 1809 getLang()); 1810 break; 1811 1812 // C++ typename-specifier: 1813 case tok::kw_typename: 1814 if (TryAnnotateTypeOrScopeToken()) { 1815 DS.SetTypeSpecError(); 1816 goto DoneWithDeclSpec; 1817 } 1818 if (!Tok.is(tok::kw_typename)) 1819 continue; 1820 break; 1821 1822 // GNU typeof support. 1823 case tok::kw_typeof: 1824 ParseTypeofSpecifier(DS); 1825 continue; 1826 1827 case tok::kw_decltype: 1828 ParseDecltypeSpecifier(DS); 1829 continue; 1830 1831 // OpenCL qualifiers: 1832 case tok::kw_private: 1833 if (!getLang().OpenCL) 1834 goto DoneWithDeclSpec; 1835 case tok::kw___private: 1836 case tok::kw___global: 1837 case tok::kw___local: 1838 case tok::kw___constant: 1839 case tok::kw___read_only: 1840 case tok::kw___write_only: 1841 case tok::kw___read_write: 1842 ParseOpenCLQualifiers(DS); 1843 break; 1844 1845 case tok::less: 1846 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 1847 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 1848 // but we support it. 1849 if (DS.hasTypeSpecifier() || !getLang().ObjC1) 1850 goto DoneWithDeclSpec; 1851 1852 if (!ParseObjCProtocolQualifiers(DS)) 1853 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 1854 << FixItHint::CreateInsertion(Loc, "id") 1855 << SourceRange(Loc, DS.getSourceRange().getEnd()); 1856 1857 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1858 // If a type specifier follows, it will be diagnosed elsewhere. 1859 continue; 1860 } 1861 // If the specifier wasn't legal, issue a diagnostic. 1862 if (isInvalid) { 1863 assert(PrevSpec && "Method did not return previous specifier!"); 1864 assert(DiagID); 1865 1866 if (DiagID == diag::ext_duplicate_declspec) 1867 Diag(Tok, DiagID) 1868 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 1869 else 1870 Diag(Tok, DiagID) << PrevSpec; 1871 } 1872 1873 DS.SetRangeEnd(Tok.getLocation()); 1874 if (DiagID != diag::err_bool_redeclaration) 1875 ConsumeToken(); 1876 } 1877} 1878 1879/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We 1880/// primarily follow the C++ grammar with additions for C99 and GNU, 1881/// which together subsume the C grammar. Note that the C++ 1882/// type-specifier also includes the C type-qualifier (for const, 1883/// volatile, and C99 restrict). Returns true if a type-specifier was 1884/// found (and parsed), false otherwise. 1885/// 1886/// type-specifier: [C++ 7.1.5] 1887/// simple-type-specifier 1888/// class-specifier 1889/// enum-specifier 1890/// elaborated-type-specifier [TODO] 1891/// cv-qualifier 1892/// 1893/// cv-qualifier: [C++ 7.1.5.1] 1894/// 'const' 1895/// 'volatile' 1896/// [C99] 'restrict' 1897/// 1898/// simple-type-specifier: [ C++ 7.1.5.2] 1899/// '::'[opt] nested-name-specifier[opt] type-name [TODO] 1900/// '::'[opt] nested-name-specifier 'template' template-id [TODO] 1901/// 'char' 1902/// 'wchar_t' 1903/// 'bool' 1904/// 'short' 1905/// 'int' 1906/// 'long' 1907/// 'signed' 1908/// 'unsigned' 1909/// 'float' 1910/// 'double' 1911/// 'void' 1912/// [C99] '_Bool' 1913/// [C99] '_Complex' 1914/// [C99] '_Imaginary' // Removed in TC2? 1915/// [GNU] '_Decimal32' 1916/// [GNU] '_Decimal64' 1917/// [GNU] '_Decimal128' 1918/// [GNU] typeof-specifier 1919/// [OBJC] class-name objc-protocol-refs[opt] [TODO] 1920/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO] 1921/// [C++0x] 'decltype' ( expression ) 1922/// [AltiVec] '__vector' 1923bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, 1924 const char *&PrevSpec, 1925 unsigned &DiagID, 1926 const ParsedTemplateInfo &TemplateInfo, 1927 bool SuppressDeclarations) { 1928 SourceLocation Loc = Tok.getLocation(); 1929 1930 switch (Tok.getKind()) { 1931 case tok::identifier: // foo::bar 1932 // If we already have a type specifier, this identifier is not a type. 1933 if (DS.getTypeSpecType() != DeclSpec::TST_unspecified || 1934 DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified || 1935 DS.getTypeSpecSign() != DeclSpec::TSS_unspecified) 1936 return false; 1937 // Check for need to substitute AltiVec keyword tokens. 1938 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 1939 break; 1940 // Fall through. 1941 case tok::kw_typename: // typename foo::bar 1942 // Annotate typenames and C++ scope specifiers. If we get one, just 1943 // recurse to handle whatever we get. 1944 if (TryAnnotateTypeOrScopeToken()) 1945 return true; 1946 if (Tok.is(tok::identifier)) 1947 return false; 1948 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1949 TemplateInfo, SuppressDeclarations); 1950 case tok::coloncolon: // ::foo::bar 1951 if (NextToken().is(tok::kw_new) || // ::new 1952 NextToken().is(tok::kw_delete)) // ::delete 1953 return false; 1954 1955 // Annotate typenames and C++ scope specifiers. If we get one, just 1956 // recurse to handle whatever we get. 1957 if (TryAnnotateTypeOrScopeToken()) 1958 return true; 1959 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1960 TemplateInfo, SuppressDeclarations); 1961 1962 // simple-type-specifier: 1963 case tok::annot_typename: { 1964 if (ParsedType T = getTypeAnnotation(Tok)) { 1965 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 1966 Tok.getAnnotationEndLoc(), PrevSpec, 1967 DiagID, T); 1968 } else 1969 DS.SetTypeSpecError(); 1970 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1971 ConsumeToken(); // The typename 1972 1973 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1974 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1975 // Objective-C interface. If we don't have Objective-C or a '<', this is 1976 // just a normal reference to a typedef name. 1977 if (Tok.is(tok::less) && getLang().ObjC1) 1978 ParseObjCProtocolQualifiers(DS); 1979 1980 return true; 1981 } 1982 1983 case tok::kw_short: 1984 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 1985 break; 1986 case tok::kw_long: 1987 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1988 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1989 DiagID); 1990 else 1991 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1992 DiagID); 1993 break; 1994 case tok::kw___int64: 1995 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1996 DiagID); 1997 break; 1998 case tok::kw_signed: 1999 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 2000 break; 2001 case tok::kw_unsigned: 2002 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 2003 DiagID); 2004 break; 2005 case tok::kw__Complex: 2006 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 2007 DiagID); 2008 break; 2009 case tok::kw__Imaginary: 2010 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 2011 DiagID); 2012 break; 2013 case tok::kw_void: 2014 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 2015 break; 2016 case tok::kw_char: 2017 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 2018 break; 2019 case tok::kw_int: 2020 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 2021 break; 2022 case tok::kw_float: 2023 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 2024 break; 2025 case tok::kw_double: 2026 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 2027 break; 2028 case tok::kw_wchar_t: 2029 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 2030 break; 2031 case tok::kw_char16_t: 2032 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 2033 break; 2034 case tok::kw_char32_t: 2035 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 2036 break; 2037 case tok::kw_bool: 2038 case tok::kw__Bool: 2039 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 2040 break; 2041 case tok::kw__Decimal32: 2042 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 2043 DiagID); 2044 break; 2045 case tok::kw__Decimal64: 2046 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 2047 DiagID); 2048 break; 2049 case tok::kw__Decimal128: 2050 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 2051 DiagID); 2052 break; 2053 case tok::kw___vector: 2054 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 2055 break; 2056 case tok::kw___pixel: 2057 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 2058 break; 2059 2060 // class-specifier: 2061 case tok::kw_class: 2062 case tok::kw_struct: 2063 case tok::kw_union: { 2064 tok::TokenKind Kind = Tok.getKind(); 2065 ConsumeToken(); 2066 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none, 2067 SuppressDeclarations); 2068 return true; 2069 } 2070 2071 // enum-specifier: 2072 case tok::kw_enum: 2073 ConsumeToken(); 2074 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none); 2075 return true; 2076 2077 // cv-qualifier: 2078 case tok::kw_const: 2079 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 2080 DiagID, getLang()); 2081 break; 2082 case tok::kw_volatile: 2083 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 2084 DiagID, getLang()); 2085 break; 2086 case tok::kw_restrict: 2087 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 2088 DiagID, getLang()); 2089 break; 2090 2091 // GNU typeof support. 2092 case tok::kw_typeof: 2093 ParseTypeofSpecifier(DS); 2094 return true; 2095 2096 // C++0x decltype support. 2097 case tok::kw_decltype: 2098 ParseDecltypeSpecifier(DS); 2099 return true; 2100 2101 // OpenCL qualifiers: 2102 case tok::kw_private: 2103 if (!getLang().OpenCL) 2104 return false; 2105 case tok::kw___private: 2106 case tok::kw___global: 2107 case tok::kw___local: 2108 case tok::kw___constant: 2109 case tok::kw___read_only: 2110 case tok::kw___write_only: 2111 case tok::kw___read_write: 2112 ParseOpenCLQualifiers(DS); 2113 break; 2114 2115 // C++0x auto support. 2116 case tok::kw_auto: 2117 if (!getLang().CPlusPlus0x) 2118 return false; 2119 2120 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID); 2121 break; 2122 2123 case tok::kw___ptr64: 2124 case tok::kw___w64: 2125 case tok::kw___cdecl: 2126 case tok::kw___stdcall: 2127 case tok::kw___fastcall: 2128 case tok::kw___thiscall: 2129 ParseMicrosoftTypeAttributes(DS.getAttributes()); 2130 return true; 2131 2132 case tok::kw___pascal: 2133 ParseBorlandTypeAttributes(DS.getAttributes()); 2134 return true; 2135 2136 default: 2137 // Not a type-specifier; do nothing. 2138 return false; 2139 } 2140 2141 // If the specifier combination wasn't legal, issue a diagnostic. 2142 if (isInvalid) { 2143 assert(PrevSpec && "Method did not return previous specifier!"); 2144 // Pick between error or extwarn. 2145 Diag(Tok, DiagID) << PrevSpec; 2146 } 2147 DS.SetRangeEnd(Tok.getLocation()); 2148 ConsumeToken(); // whatever we parsed above. 2149 return true; 2150} 2151 2152/// ParseStructDeclaration - Parse a struct declaration without the terminating 2153/// semicolon. 2154/// 2155/// struct-declaration: 2156/// specifier-qualifier-list struct-declarator-list 2157/// [GNU] __extension__ struct-declaration 2158/// [GNU] specifier-qualifier-list 2159/// struct-declarator-list: 2160/// struct-declarator 2161/// struct-declarator-list ',' struct-declarator 2162/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 2163/// struct-declarator: 2164/// declarator 2165/// [GNU] declarator attributes[opt] 2166/// declarator[opt] ':' constant-expression 2167/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 2168/// 2169void Parser:: 2170ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) { 2171 if (Tok.is(tok::kw___extension__)) { 2172 // __extension__ silences extension warnings in the subexpression. 2173 ExtensionRAIIObject O(Diags); // Use RAII to do this. 2174 ConsumeToken(); 2175 return ParseStructDeclaration(DS, Fields); 2176 } 2177 2178 // Parse the common specifier-qualifiers-list piece. 2179 ParseSpecifierQualifierList(DS); 2180 2181 // If there are no declarators, this is a free-standing declaration 2182 // specifier. Let the actions module cope with it. 2183 if (Tok.is(tok::semi)) { 2184 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS); 2185 return; 2186 } 2187 2188 // Read struct-declarators until we find the semicolon. 2189 bool FirstDeclarator = true; 2190 while (1) { 2191 ParsingDeclRAIIObject PD(*this); 2192 FieldDeclarator DeclaratorInfo(DS); 2193 2194 // Attributes are only allowed here on successive declarators. 2195 if (!FirstDeclarator) 2196 MaybeParseGNUAttributes(DeclaratorInfo.D); 2197 2198 /// struct-declarator: declarator 2199 /// struct-declarator: declarator[opt] ':' constant-expression 2200 if (Tok.isNot(tok::colon)) { 2201 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 2202 ColonProtectionRAIIObject X(*this); 2203 ParseDeclarator(DeclaratorInfo.D); 2204 } 2205 2206 if (Tok.is(tok::colon)) { 2207 ConsumeToken(); 2208 ExprResult Res(ParseConstantExpression()); 2209 if (Res.isInvalid()) 2210 SkipUntil(tok::semi, true, true); 2211 else 2212 DeclaratorInfo.BitfieldSize = Res.release(); 2213 } 2214 2215 // If attributes exist after the declarator, parse them. 2216 MaybeParseGNUAttributes(DeclaratorInfo.D); 2217 2218 // We're done with this declarator; invoke the callback. 2219 Decl *D = Fields.invoke(DeclaratorInfo); 2220 PD.complete(D); 2221 2222 // If we don't have a comma, it is either the end of the list (a ';') 2223 // or an error, bail out. 2224 if (Tok.isNot(tok::comma)) 2225 return; 2226 2227 // Consume the comma. 2228 ConsumeToken(); 2229 2230 FirstDeclarator = false; 2231 } 2232} 2233 2234/// ParseStructUnionBody 2235/// struct-contents: 2236/// struct-declaration-list 2237/// [EXT] empty 2238/// [GNU] "struct-declaration-list" without terminatoring ';' 2239/// struct-declaration-list: 2240/// struct-declaration 2241/// struct-declaration-list struct-declaration 2242/// [OBC] '@' 'defs' '(' class-name ')' 2243/// 2244void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 2245 unsigned TagType, Decl *TagDecl) { 2246 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 2247 "parsing struct/union body"); 2248 2249 SourceLocation LBraceLoc = ConsumeBrace(); 2250 2251 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 2252 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 2253 2254 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 2255 // C++. 2256 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 2257 Diag(Tok, diag::ext_empty_struct_union) 2258 << (TagType == TST_union); 2259 2260 llvm::SmallVector<Decl *, 32> FieldDecls; 2261 2262 // While we still have something to read, read the declarations in the struct. 2263 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 2264 // Each iteration of this loop reads one struct-declaration. 2265 2266 // Check for extraneous top-level semicolon. 2267 if (Tok.is(tok::semi)) { 2268 Diag(Tok, diag::ext_extra_struct_semi) 2269 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType) 2270 << FixItHint::CreateRemoval(Tok.getLocation()); 2271 ConsumeToken(); 2272 continue; 2273 } 2274 2275 // Parse all the comma separated declarators. 2276 DeclSpec DS(AttrFactory); 2277 2278 if (!Tok.is(tok::at)) { 2279 struct CFieldCallback : FieldCallback { 2280 Parser &P; 2281 Decl *TagDecl; 2282 llvm::SmallVectorImpl<Decl *> &FieldDecls; 2283 2284 CFieldCallback(Parser &P, Decl *TagDecl, 2285 llvm::SmallVectorImpl<Decl *> &FieldDecls) : 2286 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 2287 2288 virtual Decl *invoke(FieldDeclarator &FD) { 2289 // Install the declarator into the current TagDecl. 2290 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl, 2291 FD.D.getDeclSpec().getSourceRange().getBegin(), 2292 FD.D, FD.BitfieldSize); 2293 FieldDecls.push_back(Field); 2294 return Field; 2295 } 2296 } Callback(*this, TagDecl, FieldDecls); 2297 2298 ParseStructDeclaration(DS, Callback); 2299 } else { // Handle @defs 2300 ConsumeToken(); 2301 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 2302 Diag(Tok, diag::err_unexpected_at); 2303 SkipUntil(tok::semi, true); 2304 continue; 2305 } 2306 ConsumeToken(); 2307 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 2308 if (!Tok.is(tok::identifier)) { 2309 Diag(Tok, diag::err_expected_ident); 2310 SkipUntil(tok::semi, true); 2311 continue; 2312 } 2313 llvm::SmallVector<Decl *, 16> Fields; 2314 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 2315 Tok.getIdentifierInfo(), Fields); 2316 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 2317 ConsumeToken(); 2318 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 2319 } 2320 2321 if (Tok.is(tok::semi)) { 2322 ConsumeToken(); 2323 } else if (Tok.is(tok::r_brace)) { 2324 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 2325 break; 2326 } else { 2327 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 2328 // Skip to end of block or statement to avoid ext-warning on extra ';'. 2329 SkipUntil(tok::r_brace, true, true); 2330 // If we stopped at a ';', eat it. 2331 if (Tok.is(tok::semi)) ConsumeToken(); 2332 } 2333 } 2334 2335 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 2336 2337 ParsedAttributes attrs(AttrFactory); 2338 // If attributes exist after struct contents, parse them. 2339 MaybeParseGNUAttributes(attrs); 2340 2341 Actions.ActOnFields(getCurScope(), 2342 RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(), 2343 LBraceLoc, RBraceLoc, 2344 attrs.getList()); 2345 StructScope.Exit(); 2346 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc); 2347} 2348 2349/// ParseEnumSpecifier 2350/// enum-specifier: [C99 6.7.2.2] 2351/// 'enum' identifier[opt] '{' enumerator-list '}' 2352///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 2353/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 2354/// '}' attributes[opt] 2355/// 'enum' identifier 2356/// [GNU] 'enum' attributes[opt] identifier 2357/// 2358/// [C++0x] enum-head '{' enumerator-list[opt] '}' 2359/// [C++0x] enum-head '{' enumerator-list ',' '}' 2360/// 2361/// enum-head: [C++0x] 2362/// enum-key attributes[opt] identifier[opt] enum-base[opt] 2363/// enum-key attributes[opt] nested-name-specifier identifier enum-base[opt] 2364/// 2365/// enum-key: [C++0x] 2366/// 'enum' 2367/// 'enum' 'class' 2368/// 'enum' 'struct' 2369/// 2370/// enum-base: [C++0x] 2371/// ':' type-specifier-seq 2372/// 2373/// [C++] elaborated-type-specifier: 2374/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 2375/// 2376void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 2377 const ParsedTemplateInfo &TemplateInfo, 2378 AccessSpecifier AS) { 2379 // Parse the tag portion of this. 2380 if (Tok.is(tok::code_completion)) { 2381 // Code completion for an enum name. 2382 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 2383 ConsumeCodeCompletionToken(); 2384 } 2385 2386 // If attributes exist after tag, parse them. 2387 ParsedAttributes attrs(AttrFactory); 2388 MaybeParseGNUAttributes(attrs); 2389 2390 CXXScopeSpec &SS = DS.getTypeSpecScope(); 2391 if (getLang().CPlusPlus) { 2392 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false)) 2393 return; 2394 2395 if (SS.isSet() && Tok.isNot(tok::identifier)) { 2396 Diag(Tok, diag::err_expected_ident); 2397 if (Tok.isNot(tok::l_brace)) { 2398 // Has no name and is not a definition. 2399 // Skip the rest of this declarator, up until the comma or semicolon. 2400 SkipUntil(tok::comma, true); 2401 return; 2402 } 2403 } 2404 } 2405 2406 bool AllowFixedUnderlyingType = getLang().CPlusPlus0x || getLang().Microsoft; 2407 bool IsScopedEnum = false; 2408 bool IsScopedUsingClassTag = false; 2409 2410 if (getLang().CPlusPlus0x && 2411 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) { 2412 IsScopedEnum = true; 2413 IsScopedUsingClassTag = Tok.is(tok::kw_class); 2414 ConsumeToken(); 2415 } 2416 2417 // Must have either 'enum name' or 'enum {...}'. 2418 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 2419 (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) { 2420 Diag(Tok, diag::err_expected_ident_lbrace); 2421 2422 // Skip the rest of this declarator, up until the comma or semicolon. 2423 SkipUntil(tok::comma, true); 2424 return; 2425 } 2426 2427 // If an identifier is present, consume and remember it. 2428 IdentifierInfo *Name = 0; 2429 SourceLocation NameLoc; 2430 if (Tok.is(tok::identifier)) { 2431 Name = Tok.getIdentifierInfo(); 2432 NameLoc = ConsumeToken(); 2433 } 2434 2435 if (!Name && IsScopedEnum) { 2436 // C++0x 7.2p2: The optional identifier shall not be omitted in the 2437 // declaration of a scoped enumeration. 2438 Diag(Tok, diag::err_scoped_enum_missing_identifier); 2439 IsScopedEnum = false; 2440 IsScopedUsingClassTag = false; 2441 } 2442 2443 TypeResult BaseType; 2444 2445 // Parse the fixed underlying type. 2446 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 2447 bool PossibleBitfield = false; 2448 if (getCurScope()->getFlags() & Scope::ClassScope) { 2449 // If we're in class scope, this can either be an enum declaration with 2450 // an underlying type, or a declaration of a bitfield member. We try to 2451 // use a simple disambiguation scheme first to catch the common cases 2452 // (integer literal, sizeof); if it's still ambiguous, we then consider 2453 // anything that's a simple-type-specifier followed by '(' as an 2454 // expression. This suffices because function types are not valid 2455 // underlying types anyway. 2456 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 2457 // If the next token starts an expression, we know we're parsing a 2458 // bit-field. This is the common case. 2459 if (TPR == TPResult::True()) 2460 PossibleBitfield = true; 2461 // If the next token starts a type-specifier-seq, it may be either a 2462 // a fixed underlying type or the start of a function-style cast in C++; 2463 // lookahead one more token to see if it's obvious that we have a 2464 // fixed underlying type. 2465 else if (TPR == TPResult::False() && 2466 GetLookAheadToken(2).getKind() == tok::semi) { 2467 // Consume the ':'. 2468 ConsumeToken(); 2469 } else { 2470 // We have the start of a type-specifier-seq, so we have to perform 2471 // tentative parsing to determine whether we have an expression or a 2472 // type. 2473 TentativeParsingAction TPA(*this); 2474 2475 // Consume the ':'. 2476 ConsumeToken(); 2477 2478 if ((getLang().CPlusPlus && 2479 isCXXDeclarationSpecifier() != TPResult::True()) || 2480 (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) { 2481 // We'll parse this as a bitfield later. 2482 PossibleBitfield = true; 2483 TPA.Revert(); 2484 } else { 2485 // We have a type-specifier-seq. 2486 TPA.Commit(); 2487 } 2488 } 2489 } else { 2490 // Consume the ':'. 2491 ConsumeToken(); 2492 } 2493 2494 if (!PossibleBitfield) { 2495 SourceRange Range; 2496 BaseType = ParseTypeName(&Range); 2497 2498 if (!getLang().CPlusPlus0x) 2499 Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type) 2500 << Range; 2501 } 2502 } 2503 2504 // There are three options here. If we have 'enum foo;', then this is a 2505 // forward declaration. If we have 'enum foo {...' then this is a 2506 // definition. Otherwise we have something like 'enum foo xyz', a reference. 2507 // 2508 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 2509 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 2510 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 2511 // 2512 Sema::TagUseKind TUK; 2513 if (Tok.is(tok::l_brace)) 2514 TUK = Sema::TUK_Definition; 2515 else if (Tok.is(tok::semi)) 2516 TUK = Sema::TUK_Declaration; 2517 else 2518 TUK = Sema::TUK_Reference; 2519 2520 // enums cannot be templates, although they can be referenced from a 2521 // template. 2522 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 2523 TUK != Sema::TUK_Reference) { 2524 Diag(Tok, diag::err_enum_template); 2525 2526 // Skip the rest of this declarator, up until the comma or semicolon. 2527 SkipUntil(tok::comma, true); 2528 return; 2529 } 2530 2531 if (!Name && TUK != Sema::TUK_Definition) { 2532 Diag(Tok, diag::err_enumerator_unnamed_no_def); 2533 2534 // Skip the rest of this declarator, up until the comma or semicolon. 2535 SkipUntil(tok::comma, true); 2536 return; 2537 } 2538 2539 bool Owned = false; 2540 bool IsDependent = false; 2541 const char *PrevSpec = 0; 2542 unsigned DiagID; 2543 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 2544 StartLoc, SS, Name, NameLoc, attrs.getList(), 2545 AS, 2546 MultiTemplateParamsArg(Actions), 2547 Owned, IsDependent, IsScopedEnum, 2548 IsScopedUsingClassTag, BaseType); 2549 2550 if (IsDependent) { 2551 // This enum has a dependent nested-name-specifier. Handle it as a 2552 // dependent tag. 2553 if (!Name) { 2554 DS.SetTypeSpecError(); 2555 Diag(Tok, diag::err_expected_type_name_after_typename); 2556 return; 2557 } 2558 2559 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum, 2560 TUK, SS, Name, StartLoc, 2561 NameLoc); 2562 if (Type.isInvalid()) { 2563 DS.SetTypeSpecError(); 2564 return; 2565 } 2566 2567 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 2568 NameLoc.isValid() ? NameLoc : StartLoc, 2569 PrevSpec, DiagID, Type.get())) 2570 Diag(StartLoc, DiagID) << PrevSpec; 2571 2572 return; 2573 } 2574 2575 if (!TagDecl) { 2576 // The action failed to produce an enumeration tag. If this is a 2577 // definition, consume the entire definition. 2578 if (Tok.is(tok::l_brace)) { 2579 ConsumeBrace(); 2580 SkipUntil(tok::r_brace); 2581 } 2582 2583 DS.SetTypeSpecError(); 2584 return; 2585 } 2586 2587 if (Tok.is(tok::l_brace)) 2588 ParseEnumBody(StartLoc, TagDecl); 2589 2590 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, 2591 NameLoc.isValid() ? NameLoc : StartLoc, 2592 PrevSpec, DiagID, TagDecl, Owned)) 2593 Diag(StartLoc, DiagID) << PrevSpec; 2594} 2595 2596/// ParseEnumBody - Parse a {} enclosed enumerator-list. 2597/// enumerator-list: 2598/// enumerator 2599/// enumerator-list ',' enumerator 2600/// enumerator: 2601/// enumeration-constant 2602/// enumeration-constant '=' constant-expression 2603/// enumeration-constant: 2604/// identifier 2605/// 2606void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 2607 // Enter the scope of the enum body and start the definition. 2608 ParseScope EnumScope(this, Scope::DeclScope); 2609 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 2610 2611 SourceLocation LBraceLoc = ConsumeBrace(); 2612 2613 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 2614 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 2615 Diag(Tok, diag::error_empty_enum); 2616 2617 llvm::SmallVector<Decl *, 32> EnumConstantDecls; 2618 2619 Decl *LastEnumConstDecl = 0; 2620 2621 // Parse the enumerator-list. 2622 while (Tok.is(tok::identifier)) { 2623 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 2624 SourceLocation IdentLoc = ConsumeToken(); 2625 2626 // If attributes exist after the enumerator, parse them. 2627 ParsedAttributes attrs(AttrFactory); 2628 MaybeParseGNUAttributes(attrs); 2629 2630 SourceLocation EqualLoc; 2631 ExprResult AssignedVal; 2632 if (Tok.is(tok::equal)) { 2633 EqualLoc = ConsumeToken(); 2634 AssignedVal = ParseConstantExpression(); 2635 if (AssignedVal.isInvalid()) 2636 SkipUntil(tok::comma, tok::r_brace, true, true); 2637 } 2638 2639 // Install the enumerator constant into EnumDecl. 2640 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 2641 LastEnumConstDecl, 2642 IdentLoc, Ident, 2643 attrs.getList(), EqualLoc, 2644 AssignedVal.release()); 2645 EnumConstantDecls.push_back(EnumConstDecl); 2646 LastEnumConstDecl = EnumConstDecl; 2647 2648 if (Tok.is(tok::identifier)) { 2649 // We're missing a comma between enumerators. 2650 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 2651 Diag(Loc, diag::err_enumerator_list_missing_comma) 2652 << FixItHint::CreateInsertion(Loc, ", "); 2653 continue; 2654 } 2655 2656 if (Tok.isNot(tok::comma)) 2657 break; 2658 SourceLocation CommaLoc = ConsumeToken(); 2659 2660 if (Tok.isNot(tok::identifier) && 2661 !(getLang().C99 || getLang().CPlusPlus0x)) 2662 Diag(CommaLoc, diag::ext_enumerator_list_comma) 2663 << getLang().CPlusPlus 2664 << FixItHint::CreateRemoval(CommaLoc); 2665 } 2666 2667 // Eat the }. 2668 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 2669 2670 // If attributes exist after the identifier list, parse them. 2671 ParsedAttributes attrs(AttrFactory); 2672 MaybeParseGNUAttributes(attrs); 2673 2674 Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl, 2675 EnumConstantDecls.data(), EnumConstantDecls.size(), 2676 getCurScope(), attrs.getList()); 2677 2678 EnumScope.Exit(); 2679 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, RBraceLoc); 2680} 2681 2682/// isTypeSpecifierQualifier - Return true if the current token could be the 2683/// start of a type-qualifier-list. 2684bool Parser::isTypeQualifier() const { 2685 switch (Tok.getKind()) { 2686 default: return false; 2687 2688 // type-qualifier only in OpenCL 2689 case tok::kw_private: 2690 return getLang().OpenCL; 2691 2692 // type-qualifier 2693 case tok::kw_const: 2694 case tok::kw_volatile: 2695 case tok::kw_restrict: 2696 case tok::kw___private: 2697 case tok::kw___local: 2698 case tok::kw___global: 2699 case tok::kw___constant: 2700 case tok::kw___read_only: 2701 case tok::kw___read_write: 2702 case tok::kw___write_only: 2703 return true; 2704 } 2705} 2706 2707/// isKnownToBeTypeSpecifier - Return true if we know that the specified token 2708/// is definitely a type-specifier. Return false if it isn't part of a type 2709/// specifier or if we're not sure. 2710bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 2711 switch (Tok.getKind()) { 2712 default: return false; 2713 // type-specifiers 2714 case tok::kw_short: 2715 case tok::kw_long: 2716 case tok::kw___int64: 2717 case tok::kw_signed: 2718 case tok::kw_unsigned: 2719 case tok::kw__Complex: 2720 case tok::kw__Imaginary: 2721 case tok::kw_void: 2722 case tok::kw_char: 2723 case tok::kw_wchar_t: 2724 case tok::kw_char16_t: 2725 case tok::kw_char32_t: 2726 case tok::kw_int: 2727 case tok::kw_float: 2728 case tok::kw_double: 2729 case tok::kw_bool: 2730 case tok::kw__Bool: 2731 case tok::kw__Decimal32: 2732 case tok::kw__Decimal64: 2733 case tok::kw__Decimal128: 2734 case tok::kw___vector: 2735 2736 // struct-or-union-specifier (C99) or class-specifier (C++) 2737 case tok::kw_class: 2738 case tok::kw_struct: 2739 case tok::kw_union: 2740 // enum-specifier 2741 case tok::kw_enum: 2742 2743 // typedef-name 2744 case tok::annot_typename: 2745 return true; 2746 } 2747} 2748 2749/// isTypeSpecifierQualifier - Return true if the current token could be the 2750/// start of a specifier-qualifier-list. 2751bool Parser::isTypeSpecifierQualifier() { 2752 switch (Tok.getKind()) { 2753 default: return false; 2754 2755 case tok::identifier: // foo::bar 2756 if (TryAltiVecVectorToken()) 2757 return true; 2758 // Fall through. 2759 case tok::kw_typename: // typename T::type 2760 // Annotate typenames and C++ scope specifiers. If we get one, just 2761 // recurse to handle whatever we get. 2762 if (TryAnnotateTypeOrScopeToken()) 2763 return true; 2764 if (Tok.is(tok::identifier)) 2765 return false; 2766 return isTypeSpecifierQualifier(); 2767 2768 case tok::coloncolon: // ::foo::bar 2769 if (NextToken().is(tok::kw_new) || // ::new 2770 NextToken().is(tok::kw_delete)) // ::delete 2771 return false; 2772 2773 if (TryAnnotateTypeOrScopeToken()) 2774 return true; 2775 return isTypeSpecifierQualifier(); 2776 2777 // GNU attributes support. 2778 case tok::kw___attribute: 2779 // GNU typeof support. 2780 case tok::kw_typeof: 2781 2782 // type-specifiers 2783 case tok::kw_short: 2784 case tok::kw_long: 2785 case tok::kw___int64: 2786 case tok::kw_signed: 2787 case tok::kw_unsigned: 2788 case tok::kw__Complex: 2789 case tok::kw__Imaginary: 2790 case tok::kw_void: 2791 case tok::kw_char: 2792 case tok::kw_wchar_t: 2793 case tok::kw_char16_t: 2794 case tok::kw_char32_t: 2795 case tok::kw_int: 2796 case tok::kw_float: 2797 case tok::kw_double: 2798 case tok::kw_bool: 2799 case tok::kw__Bool: 2800 case tok::kw__Decimal32: 2801 case tok::kw__Decimal64: 2802 case tok::kw__Decimal128: 2803 case tok::kw___vector: 2804 2805 // struct-or-union-specifier (C99) or class-specifier (C++) 2806 case tok::kw_class: 2807 case tok::kw_struct: 2808 case tok::kw_union: 2809 // enum-specifier 2810 case tok::kw_enum: 2811 2812 // type-qualifier 2813 case tok::kw_const: 2814 case tok::kw_volatile: 2815 case tok::kw_restrict: 2816 2817 // typedef-name 2818 case tok::annot_typename: 2819 return true; 2820 2821 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2822 case tok::less: 2823 return getLang().ObjC1; 2824 2825 case tok::kw___cdecl: 2826 case tok::kw___stdcall: 2827 case tok::kw___fastcall: 2828 case tok::kw___thiscall: 2829 case tok::kw___w64: 2830 case tok::kw___ptr64: 2831 case tok::kw___pascal: 2832 2833 case tok::kw___private: 2834 case tok::kw___local: 2835 case tok::kw___global: 2836 case tok::kw___constant: 2837 case tok::kw___read_only: 2838 case tok::kw___read_write: 2839 case tok::kw___write_only: 2840 2841 return true; 2842 2843 case tok::kw_private: 2844 return getLang().OpenCL; 2845 } 2846} 2847 2848/// isDeclarationSpecifier() - Return true if the current token is part of a 2849/// declaration specifier. 2850/// 2851/// \param DisambiguatingWithExpression True to indicate that the purpose of 2852/// this check is to disambiguate between an expression and a declaration. 2853bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 2854 switch (Tok.getKind()) { 2855 default: return false; 2856 2857 case tok::kw_private: 2858 return getLang().OpenCL; 2859 2860 case tok::identifier: // foo::bar 2861 // Unfortunate hack to support "Class.factoryMethod" notation. 2862 if (getLang().ObjC1 && NextToken().is(tok::period)) 2863 return false; 2864 if (TryAltiVecVectorToken()) 2865 return true; 2866 // Fall through. 2867 case tok::kw_typename: // typename T::type 2868 // Annotate typenames and C++ scope specifiers. If we get one, just 2869 // recurse to handle whatever we get. 2870 if (TryAnnotateTypeOrScopeToken()) 2871 return true; 2872 if (Tok.is(tok::identifier)) 2873 return false; 2874 2875 // If we're in Objective-C and we have an Objective-C class type followed 2876 // by an identifier and then either ':' or ']', in a place where an 2877 // expression is permitted, then this is probably a class message send 2878 // missing the initial '['. In this case, we won't consider this to be 2879 // the start of a declaration. 2880 if (DisambiguatingWithExpression && 2881 isStartOfObjCClassMessageMissingOpenBracket()) 2882 return false; 2883 2884 return isDeclarationSpecifier(); 2885 2886 case tok::coloncolon: // ::foo::bar 2887 if (NextToken().is(tok::kw_new) || // ::new 2888 NextToken().is(tok::kw_delete)) // ::delete 2889 return false; 2890 2891 // Annotate typenames and C++ scope specifiers. If we get one, just 2892 // recurse to handle whatever we get. 2893 if (TryAnnotateTypeOrScopeToken()) 2894 return true; 2895 return isDeclarationSpecifier(); 2896 2897 // storage-class-specifier 2898 case tok::kw_typedef: 2899 case tok::kw_extern: 2900 case tok::kw___private_extern__: 2901 case tok::kw_static: 2902 case tok::kw_auto: 2903 case tok::kw_register: 2904 case tok::kw___thread: 2905 2906 // type-specifiers 2907 case tok::kw_short: 2908 case tok::kw_long: 2909 case tok::kw___int64: 2910 case tok::kw_signed: 2911 case tok::kw_unsigned: 2912 case tok::kw__Complex: 2913 case tok::kw__Imaginary: 2914 case tok::kw_void: 2915 case tok::kw_char: 2916 case tok::kw_wchar_t: 2917 case tok::kw_char16_t: 2918 case tok::kw_char32_t: 2919 2920 case tok::kw_int: 2921 case tok::kw_float: 2922 case tok::kw_double: 2923 case tok::kw_bool: 2924 case tok::kw__Bool: 2925 case tok::kw__Decimal32: 2926 case tok::kw__Decimal64: 2927 case tok::kw__Decimal128: 2928 case tok::kw___vector: 2929 2930 // struct-or-union-specifier (C99) or class-specifier (C++) 2931 case tok::kw_class: 2932 case tok::kw_struct: 2933 case tok::kw_union: 2934 // enum-specifier 2935 case tok::kw_enum: 2936 2937 // type-qualifier 2938 case tok::kw_const: 2939 case tok::kw_volatile: 2940 case tok::kw_restrict: 2941 2942 // function-specifier 2943 case tok::kw_inline: 2944 case tok::kw_virtual: 2945 case tok::kw_explicit: 2946 2947 // static_assert-declaration 2948 case tok::kw__Static_assert: 2949 2950 // GNU typeof support. 2951 case tok::kw_typeof: 2952 2953 // GNU attributes. 2954 case tok::kw___attribute: 2955 return true; 2956 2957 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2958 case tok::less: 2959 return getLang().ObjC1; 2960 2961 // typedef-name 2962 case tok::annot_typename: 2963 return !DisambiguatingWithExpression || 2964 !isStartOfObjCClassMessageMissingOpenBracket(); 2965 2966 case tok::kw___declspec: 2967 case tok::kw___cdecl: 2968 case tok::kw___stdcall: 2969 case tok::kw___fastcall: 2970 case tok::kw___thiscall: 2971 case tok::kw___w64: 2972 case tok::kw___ptr64: 2973 case tok::kw___forceinline: 2974 case tok::kw___pascal: 2975 2976 case tok::kw___private: 2977 case tok::kw___local: 2978 case tok::kw___global: 2979 case tok::kw___constant: 2980 case tok::kw___read_only: 2981 case tok::kw___read_write: 2982 case tok::kw___write_only: 2983 2984 return true; 2985 } 2986} 2987 2988bool Parser::isConstructorDeclarator() { 2989 TentativeParsingAction TPA(*this); 2990 2991 // Parse the C++ scope specifier. 2992 CXXScopeSpec SS; 2993 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) { 2994 TPA.Revert(); 2995 return false; 2996 } 2997 2998 // Parse the constructor name. 2999 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 3000 // We already know that we have a constructor name; just consume 3001 // the token. 3002 ConsumeToken(); 3003 } else { 3004 TPA.Revert(); 3005 return false; 3006 } 3007 3008 // Current class name must be followed by a left parentheses. 3009 if (Tok.isNot(tok::l_paren)) { 3010 TPA.Revert(); 3011 return false; 3012 } 3013 ConsumeParen(); 3014 3015 // A right parentheses or ellipsis signals that we have a constructor. 3016 if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) { 3017 TPA.Revert(); 3018 return true; 3019 } 3020 3021 // If we need to, enter the specified scope. 3022 DeclaratorScopeObj DeclScopeObj(*this, SS); 3023 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 3024 DeclScopeObj.EnterDeclaratorScope(); 3025 3026 // Optionally skip Microsoft attributes. 3027 ParsedAttributes Attrs(AttrFactory); 3028 MaybeParseMicrosoftAttributes(Attrs); 3029 3030 // Check whether the next token(s) are part of a declaration 3031 // specifier, in which case we have the start of a parameter and, 3032 // therefore, we know that this is a constructor. 3033 bool IsConstructor = isDeclarationSpecifier(); 3034 TPA.Revert(); 3035 return IsConstructor; 3036} 3037 3038/// ParseTypeQualifierListOpt 3039/// type-qualifier-list: [C99 6.7.5] 3040/// type-qualifier 3041/// [vendor] attributes 3042/// [ only if VendorAttributesAllowed=true ] 3043/// type-qualifier-list type-qualifier 3044/// [vendor] type-qualifier-list attributes 3045/// [ only if VendorAttributesAllowed=true ] 3046/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 3047/// [ only if CXX0XAttributesAllowed=true ] 3048/// Note: vendor can be GNU, MS, etc. 3049/// 3050void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, 3051 bool VendorAttributesAllowed, 3052 bool CXX0XAttributesAllowed) { 3053 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 3054 SourceLocation Loc = Tok.getLocation(); 3055 ParsedAttributesWithRange attrs(AttrFactory); 3056 ParseCXX0XAttributes(attrs); 3057 if (CXX0XAttributesAllowed) 3058 DS.takeAttributesFrom(attrs); 3059 else 3060 Diag(Loc, diag::err_attributes_not_allowed); 3061 } 3062 3063 SourceLocation EndLoc; 3064 3065 while (1) { 3066 bool isInvalid = false; 3067 const char *PrevSpec = 0; 3068 unsigned DiagID = 0; 3069 SourceLocation Loc = Tok.getLocation(); 3070 3071 switch (Tok.getKind()) { 3072 case tok::code_completion: 3073 Actions.CodeCompleteTypeQualifiers(DS); 3074 ConsumeCodeCompletionToken(); 3075 break; 3076 3077 case tok::kw_const: 3078 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 3079 getLang()); 3080 break; 3081 case tok::kw_volatile: 3082 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 3083 getLang()); 3084 break; 3085 case tok::kw_restrict: 3086 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 3087 getLang()); 3088 break; 3089 3090 // OpenCL qualifiers: 3091 case tok::kw_private: 3092 if (!getLang().OpenCL) 3093 goto DoneWithTypeQuals; 3094 case tok::kw___private: 3095 case tok::kw___global: 3096 case tok::kw___local: 3097 case tok::kw___constant: 3098 case tok::kw___read_only: 3099 case tok::kw___write_only: 3100 case tok::kw___read_write: 3101 ParseOpenCLQualifiers(DS); 3102 break; 3103 3104 case tok::kw___w64: 3105 case tok::kw___ptr64: 3106 case tok::kw___cdecl: 3107 case tok::kw___stdcall: 3108 case tok::kw___fastcall: 3109 case tok::kw___thiscall: 3110 if (VendorAttributesAllowed) { 3111 ParseMicrosoftTypeAttributes(DS.getAttributes()); 3112 continue; 3113 } 3114 goto DoneWithTypeQuals; 3115 case tok::kw___pascal: 3116 if (VendorAttributesAllowed) { 3117 ParseBorlandTypeAttributes(DS.getAttributes()); 3118 continue; 3119 } 3120 goto DoneWithTypeQuals; 3121 case tok::kw___attribute: 3122 if (VendorAttributesAllowed) { 3123 ParseGNUAttributes(DS.getAttributes()); 3124 continue; // do *not* consume the next token! 3125 } 3126 // otherwise, FALL THROUGH! 3127 default: 3128 DoneWithTypeQuals: 3129 // If this is not a type-qualifier token, we're done reading type 3130 // qualifiers. First verify that DeclSpec's are consistent. 3131 DS.Finish(Diags, PP); 3132 if (EndLoc.isValid()) 3133 DS.SetRangeEnd(EndLoc); 3134 return; 3135 } 3136 3137 // If the specifier combination wasn't legal, issue a diagnostic. 3138 if (isInvalid) { 3139 assert(PrevSpec && "Method did not return previous specifier!"); 3140 Diag(Tok, DiagID) << PrevSpec; 3141 } 3142 EndLoc = ConsumeToken(); 3143 } 3144} 3145 3146 3147/// ParseDeclarator - Parse and verify a newly-initialized declarator. 3148/// 3149void Parser::ParseDeclarator(Declarator &D) { 3150 /// This implements the 'declarator' production in the C grammar, then checks 3151 /// for well-formedness and issues diagnostics. 3152 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 3153} 3154 3155/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 3156/// is parsed by the function passed to it. Pass null, and the direct-declarator 3157/// isn't parsed at all, making this function effectively parse the C++ 3158/// ptr-operator production. 3159/// 3160/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 3161/// [C] pointer[opt] direct-declarator 3162/// [C++] direct-declarator 3163/// [C++] ptr-operator declarator 3164/// 3165/// pointer: [C99 6.7.5] 3166/// '*' type-qualifier-list[opt] 3167/// '*' type-qualifier-list[opt] pointer 3168/// 3169/// ptr-operator: 3170/// '*' cv-qualifier-seq[opt] 3171/// '&' 3172/// [C++0x] '&&' 3173/// [GNU] '&' restrict[opt] attributes[opt] 3174/// [GNU?] '&&' restrict[opt] attributes[opt] 3175/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 3176void Parser::ParseDeclaratorInternal(Declarator &D, 3177 DirectDeclParseFunction DirectDeclParser) { 3178 if (Diags.hasAllExtensionsSilenced()) 3179 D.setExtension(); 3180 3181 // C++ member pointers start with a '::' or a nested-name. 3182 // Member pointers get special handling, since there's no place for the 3183 // scope spec in the generic path below. 3184 if (getLang().CPlusPlus && 3185 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 3186 Tok.is(tok::annot_cxxscope))) { 3187 CXXScopeSpec SS; 3188 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail 3189 3190 if (SS.isNotEmpty()) { 3191 if (Tok.isNot(tok::star)) { 3192 // The scope spec really belongs to the direct-declarator. 3193 D.getCXXScopeSpec() = SS; 3194 if (DirectDeclParser) 3195 (this->*DirectDeclParser)(D); 3196 return; 3197 } 3198 3199 SourceLocation Loc = ConsumeToken(); 3200 D.SetRangeEnd(Loc); 3201 DeclSpec DS(AttrFactory); 3202 ParseTypeQualifierListOpt(DS); 3203 D.ExtendWithDeclSpec(DS); 3204 3205 // Recurse to parse whatever is left. 3206 ParseDeclaratorInternal(D, DirectDeclParser); 3207 3208 // Sema will have to catch (syntactically invalid) pointers into global 3209 // scope. It has to catch pointers into namespace scope anyway. 3210 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 3211 Loc), 3212 DS.getAttributes(), 3213 /* Don't replace range end. */SourceLocation()); 3214 return; 3215 } 3216 } 3217 3218 tok::TokenKind Kind = Tok.getKind(); 3219 // Not a pointer, C++ reference, or block. 3220 if (Kind != tok::star && Kind != tok::caret && 3221 (Kind != tok::amp || !getLang().CPlusPlus) && 3222 // We parse rvalue refs in C++03, because otherwise the errors are scary. 3223 (Kind != tok::ampamp || !getLang().CPlusPlus)) { 3224 if (DirectDeclParser) 3225 (this->*DirectDeclParser)(D); 3226 return; 3227 } 3228 3229 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 3230 // '&&' -> rvalue reference 3231 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 3232 D.SetRangeEnd(Loc); 3233 3234 if (Kind == tok::star || Kind == tok::caret) { 3235 // Is a pointer. 3236 DeclSpec DS(AttrFactory); 3237 3238 ParseTypeQualifierListOpt(DS); 3239 D.ExtendWithDeclSpec(DS); 3240 3241 // Recursively parse the declarator. 3242 ParseDeclaratorInternal(D, DirectDeclParser); 3243 if (Kind == tok::star) 3244 // Remember that we parsed a pointer type, and remember the type-quals. 3245 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 3246 DS.getConstSpecLoc(), 3247 DS.getVolatileSpecLoc(), 3248 DS.getRestrictSpecLoc()), 3249 DS.getAttributes(), 3250 SourceLocation()); 3251 else 3252 // Remember that we parsed a Block type, and remember the type-quals. 3253 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 3254 Loc), 3255 DS.getAttributes(), 3256 SourceLocation()); 3257 } else { 3258 // Is a reference 3259 DeclSpec DS(AttrFactory); 3260 3261 // Complain about rvalue references in C++03, but then go on and build 3262 // the declarator. 3263 if (Kind == tok::ampamp && !getLang().CPlusPlus0x) 3264 Diag(Loc, diag::ext_rvalue_reference); 3265 3266 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 3267 // cv-qualifiers are introduced through the use of a typedef or of a 3268 // template type argument, in which case the cv-qualifiers are ignored. 3269 // 3270 // [GNU] Retricted references are allowed. 3271 // [GNU] Attributes on references are allowed. 3272 // [C++0x] Attributes on references are not allowed. 3273 ParseTypeQualifierListOpt(DS, true, false); 3274 D.ExtendWithDeclSpec(DS); 3275 3276 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 3277 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3278 Diag(DS.getConstSpecLoc(), 3279 diag::err_invalid_reference_qualifier_application) << "const"; 3280 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3281 Diag(DS.getVolatileSpecLoc(), 3282 diag::err_invalid_reference_qualifier_application) << "volatile"; 3283 } 3284 3285 // Recursively parse the declarator. 3286 ParseDeclaratorInternal(D, DirectDeclParser); 3287 3288 if (D.getNumTypeObjects() > 0) { 3289 // C++ [dcl.ref]p4: There shall be no references to references. 3290 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 3291 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 3292 if (const IdentifierInfo *II = D.getIdentifier()) 3293 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 3294 << II; 3295 else 3296 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 3297 << "type name"; 3298 3299 // Once we've complained about the reference-to-reference, we 3300 // can go ahead and build the (technically ill-formed) 3301 // declarator: reference collapsing will take care of it. 3302 } 3303 } 3304 3305 // Remember that we parsed a reference type. It doesn't have type-quals. 3306 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 3307 Kind == tok::amp), 3308 DS.getAttributes(), 3309 SourceLocation()); 3310 } 3311} 3312 3313/// ParseDirectDeclarator 3314/// direct-declarator: [C99 6.7.5] 3315/// [C99] identifier 3316/// '(' declarator ')' 3317/// [GNU] '(' attributes declarator ')' 3318/// [C90] direct-declarator '[' constant-expression[opt] ']' 3319/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 3320/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 3321/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 3322/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 3323/// direct-declarator '(' parameter-type-list ')' 3324/// direct-declarator '(' identifier-list[opt] ')' 3325/// [GNU] direct-declarator '(' parameter-forward-declarations 3326/// parameter-type-list[opt] ')' 3327/// [C++] direct-declarator '(' parameter-declaration-clause ')' 3328/// cv-qualifier-seq[opt] exception-specification[opt] 3329/// [C++] declarator-id 3330/// 3331/// declarator-id: [C++ 8] 3332/// '...'[opt] id-expression 3333/// '::'[opt] nested-name-specifier[opt] type-name 3334/// 3335/// id-expression: [C++ 5.1] 3336/// unqualified-id 3337/// qualified-id 3338/// 3339/// unqualified-id: [C++ 5.1] 3340/// identifier 3341/// operator-function-id 3342/// conversion-function-id 3343/// '~' class-name 3344/// template-id 3345/// 3346void Parser::ParseDirectDeclarator(Declarator &D) { 3347 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 3348 3349 if (getLang().CPlusPlus && D.mayHaveIdentifier()) { 3350 // ParseDeclaratorInternal might already have parsed the scope. 3351 if (D.getCXXScopeSpec().isEmpty()) { 3352 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true); 3353 } 3354 3355 if (D.getCXXScopeSpec().isValid()) { 3356 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 3357 // Change the declaration context for name lookup, until this function 3358 // is exited (and the declarator has been parsed). 3359 DeclScopeObj.EnterDeclaratorScope(); 3360 } 3361 3362 // C++0x [dcl.fct]p14: 3363 // There is a syntactic ambiguity when an ellipsis occurs at the end 3364 // of a parameter-declaration-clause without a preceding comma. In 3365 // this case, the ellipsis is parsed as part of the 3366 // abstract-declarator if the type of the parameter names a template 3367 // parameter pack that has not been expanded; otherwise, it is parsed 3368 // as part of the parameter-declaration-clause. 3369 if (Tok.is(tok::ellipsis) && 3370 !((D.getContext() == Declarator::PrototypeContext || 3371 D.getContext() == Declarator::BlockLiteralContext) && 3372 NextToken().is(tok::r_paren) && 3373 !Actions.containsUnexpandedParameterPacks(D))) 3374 D.setEllipsisLoc(ConsumeToken()); 3375 3376 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 3377 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 3378 // We found something that indicates the start of an unqualified-id. 3379 // Parse that unqualified-id. 3380 bool AllowConstructorName; 3381 if (D.getDeclSpec().hasTypeSpecifier()) 3382 AllowConstructorName = false; 3383 else if (D.getCXXScopeSpec().isSet()) 3384 AllowConstructorName = 3385 (D.getContext() == Declarator::FileContext || 3386 (D.getContext() == Declarator::MemberContext && 3387 D.getDeclSpec().isFriendSpecified())); 3388 else 3389 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 3390 3391 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 3392 /*EnteringContext=*/true, 3393 /*AllowDestructorName=*/true, 3394 AllowConstructorName, 3395 ParsedType(), 3396 D.getName()) || 3397 // Once we're past the identifier, if the scope was bad, mark the 3398 // whole declarator bad. 3399 D.getCXXScopeSpec().isInvalid()) { 3400 D.SetIdentifier(0, Tok.getLocation()); 3401 D.setInvalidType(true); 3402 } else { 3403 // Parsed the unqualified-id; update range information and move along. 3404 if (D.getSourceRange().getBegin().isInvalid()) 3405 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 3406 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 3407 } 3408 goto PastIdentifier; 3409 } 3410 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 3411 assert(!getLang().CPlusPlus && 3412 "There's a C++-specific check for tok::identifier above"); 3413 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 3414 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 3415 ConsumeToken(); 3416 goto PastIdentifier; 3417 } 3418 3419 if (Tok.is(tok::l_paren)) { 3420 // direct-declarator: '(' declarator ')' 3421 // direct-declarator: '(' attributes declarator ')' 3422 // Example: 'char (*X)' or 'int (*XX)(void)' 3423 ParseParenDeclarator(D); 3424 3425 // If the declarator was parenthesized, we entered the declarator 3426 // scope when parsing the parenthesized declarator, then exited 3427 // the scope already. Re-enter the scope, if we need to. 3428 if (D.getCXXScopeSpec().isSet()) { 3429 // If there was an error parsing parenthesized declarator, declarator 3430 // scope may have been enterred before. Don't do it again. 3431 if (!D.isInvalidType() && 3432 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 3433 // Change the declaration context for name lookup, until this function 3434 // is exited (and the declarator has been parsed). 3435 DeclScopeObj.EnterDeclaratorScope(); 3436 } 3437 } else if (D.mayOmitIdentifier()) { 3438 // This could be something simple like "int" (in which case the declarator 3439 // portion is empty), if an abstract-declarator is allowed. 3440 D.SetIdentifier(0, Tok.getLocation()); 3441 } else { 3442 if (D.getContext() == Declarator::MemberContext) 3443 Diag(Tok, diag::err_expected_member_name_or_semi) 3444 << D.getDeclSpec().getSourceRange(); 3445 else if (getLang().CPlusPlus) 3446 Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus; 3447 else 3448 Diag(Tok, diag::err_expected_ident_lparen); 3449 D.SetIdentifier(0, Tok.getLocation()); 3450 D.setInvalidType(true); 3451 } 3452 3453 PastIdentifier: 3454 assert(D.isPastIdentifier() && 3455 "Haven't past the location of the identifier yet?"); 3456 3457 // Don't parse attributes unless we have an identifier. 3458 if (D.getIdentifier()) 3459 MaybeParseCXX0XAttributes(D); 3460 3461 while (1) { 3462 if (Tok.is(tok::l_paren)) { 3463 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 3464 // In such a case, check if we actually have a function declarator; if it 3465 // is not, the declarator has been fully parsed. 3466 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 3467 // When not in file scope, warn for ambiguous function declarators, just 3468 // in case the author intended it as a variable definition. 3469 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 3470 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 3471 break; 3472 } 3473 ParsedAttributes attrs(AttrFactory); 3474 ParseFunctionDeclarator(ConsumeParen(), D, attrs); 3475 } else if (Tok.is(tok::l_square)) { 3476 ParseBracketDeclarator(D); 3477 } else { 3478 break; 3479 } 3480 } 3481} 3482 3483/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 3484/// only called before the identifier, so these are most likely just grouping 3485/// parens for precedence. If we find that these are actually function 3486/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 3487/// 3488/// direct-declarator: 3489/// '(' declarator ')' 3490/// [GNU] '(' attributes declarator ')' 3491/// direct-declarator '(' parameter-type-list ')' 3492/// direct-declarator '(' identifier-list[opt] ')' 3493/// [GNU] direct-declarator '(' parameter-forward-declarations 3494/// parameter-type-list[opt] ')' 3495/// 3496void Parser::ParseParenDeclarator(Declarator &D) { 3497 SourceLocation StartLoc = ConsumeParen(); 3498 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 3499 3500 // Eat any attributes before we look at whether this is a grouping or function 3501 // declarator paren. If this is a grouping paren, the attribute applies to 3502 // the type being built up, for example: 3503 // int (__attribute__(()) *x)(long y) 3504 // If this ends up not being a grouping paren, the attribute applies to the 3505 // first argument, for example: 3506 // int (__attribute__(()) int x) 3507 // In either case, we need to eat any attributes to be able to determine what 3508 // sort of paren this is. 3509 // 3510 ParsedAttributes attrs(AttrFactory); 3511 bool RequiresArg = false; 3512 if (Tok.is(tok::kw___attribute)) { 3513 ParseGNUAttributes(attrs); 3514 3515 // We require that the argument list (if this is a non-grouping paren) be 3516 // present even if the attribute list was empty. 3517 RequiresArg = true; 3518 } 3519 // Eat any Microsoft extensions. 3520 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 3521 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) || 3522 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64)) { 3523 ParseMicrosoftTypeAttributes(attrs); 3524 } 3525 // Eat any Borland extensions. 3526 if (Tok.is(tok::kw___pascal)) 3527 ParseBorlandTypeAttributes(attrs); 3528 3529 // If we haven't past the identifier yet (or where the identifier would be 3530 // stored, if this is an abstract declarator), then this is probably just 3531 // grouping parens. However, if this could be an abstract-declarator, then 3532 // this could also be the start of function arguments (consider 'void()'). 3533 bool isGrouping; 3534 3535 if (!D.mayOmitIdentifier()) { 3536 // If this can't be an abstract-declarator, this *must* be a grouping 3537 // paren, because we haven't seen the identifier yet. 3538 isGrouping = true; 3539 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 3540 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...) 3541 isDeclarationSpecifier()) { // 'int(int)' is a function. 3542 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 3543 // considered to be a type, not a K&R identifier-list. 3544 isGrouping = false; 3545 } else { 3546 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 3547 isGrouping = true; 3548 } 3549 3550 // If this is a grouping paren, handle: 3551 // direct-declarator: '(' declarator ')' 3552 // direct-declarator: '(' attributes declarator ')' 3553 if (isGrouping) { 3554 bool hadGroupingParens = D.hasGroupingParens(); 3555 D.setGroupingParens(true); 3556 3557 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 3558 // Match the ')'. 3559 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, StartLoc); 3560 D.AddTypeInfo(DeclaratorChunk::getParen(StartLoc, EndLoc), 3561 attrs, EndLoc); 3562 3563 D.setGroupingParens(hadGroupingParens); 3564 return; 3565 } 3566 3567 // Okay, if this wasn't a grouping paren, it must be the start of a function 3568 // argument list. Recognize that this declarator will never have an 3569 // identifier (and remember where it would have been), then call into 3570 // ParseFunctionDeclarator to handle of argument list. 3571 D.SetIdentifier(0, Tok.getLocation()); 3572 3573 ParseFunctionDeclarator(StartLoc, D, attrs, RequiresArg); 3574} 3575 3576/// ParseFunctionDeclarator - We are after the identifier and have parsed the 3577/// declarator D up to a paren, which indicates that we are parsing function 3578/// arguments. 3579/// 3580/// If AttrList is non-null, then the caller parsed those arguments immediately 3581/// after the open paren - they should be considered to be the first argument of 3582/// a parameter. If RequiresArg is true, then the first argument of the 3583/// function is required to be present and required to not be an identifier 3584/// list. 3585/// 3586/// This method also handles this portion of the grammar: 3587/// parameter-type-list: [C99 6.7.5] 3588/// parameter-list 3589/// parameter-list ',' '...' 3590/// [C++] parameter-list '...' 3591/// 3592/// parameter-list: [C99 6.7.5] 3593/// parameter-declaration 3594/// parameter-list ',' parameter-declaration 3595/// 3596/// parameter-declaration: [C99 6.7.5] 3597/// declaration-specifiers declarator 3598/// [C++] declaration-specifiers declarator '=' assignment-expression 3599/// [GNU] declaration-specifiers declarator attributes 3600/// declaration-specifiers abstract-declarator[opt] 3601/// [C++] declaration-specifiers abstract-declarator[opt] 3602/// '=' assignment-expression 3603/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 3604/// 3605/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]", 3606/// C++0x "ref-qualifier[opt]" and "exception-specification[opt]". 3607/// 3608/// [C++0x] exception-specification: 3609/// dynamic-exception-specification 3610/// noexcept-specification 3611/// 3612void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 3613 ParsedAttributes &attrs, 3614 bool RequiresArg) { 3615 // lparen is already consumed! 3616 assert(D.isPastIdentifier() && "Should not call before identifier!"); 3617 3618 ParsedType TrailingReturnType; 3619 3620 // This parameter list may be empty. 3621 if (Tok.is(tok::r_paren)) { 3622 if (RequiresArg) 3623 Diag(Tok, diag::err_argument_required_after_attribute); 3624 3625 SourceLocation EndLoc = ConsumeParen(); // Eat the closing ')'. 3626 3627 // cv-qualifier-seq[opt]. 3628 DeclSpec DS(AttrFactory); 3629 SourceLocation RefQualifierLoc; 3630 bool RefQualifierIsLValueRef = true; 3631 ExceptionSpecificationType ESpecType = EST_None; 3632 SourceRange ESpecRange; 3633 llvm::SmallVector<ParsedType, 2> DynamicExceptions; 3634 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges; 3635 ExprResult NoexceptExpr; 3636 if (getLang().CPlusPlus) { 3637 MaybeParseCXX0XAttributes(attrs); 3638 3639 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3640 if (!DS.getSourceRange().getEnd().isInvalid()) 3641 EndLoc = DS.getSourceRange().getEnd(); 3642 3643 // Parse ref-qualifier[opt] 3644 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 3645 if (!getLang().CPlusPlus0x) 3646 Diag(Tok, diag::ext_ref_qualifier); 3647 3648 RefQualifierIsLValueRef = Tok.is(tok::amp); 3649 RefQualifierLoc = ConsumeToken(); 3650 EndLoc = RefQualifierLoc; 3651 } 3652 3653 // Parse exception-specification[opt]. 3654 ESpecType = MaybeParseExceptionSpecification(ESpecRange, 3655 DynamicExceptions, 3656 DynamicExceptionRanges, 3657 NoexceptExpr); 3658 if (ESpecType != EST_None) 3659 EndLoc = ESpecRange.getEnd(); 3660 3661 // Parse trailing-return-type. 3662 if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) { 3663 TrailingReturnType = ParseTrailingReturnType().get(); 3664 } 3665 } 3666 3667 // Remember that we parsed a function type, and remember the attributes. 3668 // int() -> no prototype, no '...'. 3669 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus, 3670 /*variadic*/ false, 3671 SourceLocation(), 3672 /*arglist*/ 0, 0, 3673 DS.getTypeQualifiers(), 3674 RefQualifierIsLValueRef, 3675 RefQualifierLoc, 3676 ESpecType, ESpecRange.getBegin(), 3677 DynamicExceptions.data(), 3678 DynamicExceptionRanges.data(), 3679 DynamicExceptions.size(), 3680 NoexceptExpr.isUsable() ? 3681 NoexceptExpr.get() : 0, 3682 LParenLoc, EndLoc, D, 3683 TrailingReturnType), 3684 attrs, EndLoc); 3685 return; 3686 } 3687 3688 // Alternatively, this parameter list may be an identifier list form for a 3689 // K&R-style function: void foo(a,b,c) 3690 if (!getLang().CPlusPlus && Tok.is(tok::identifier) 3691 && !TryAltiVecVectorToken()) { 3692 if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) { 3693 // K&R identifier lists can't have typedefs as identifiers, per 3694 // C99 6.7.5.3p11. 3695 if (RequiresArg) 3696 Diag(Tok, diag::err_argument_required_after_attribute); 3697 3698 // Identifier list. Note that '(' identifier-list ')' is only allowed for 3699 // normal declarators, not for abstract-declarators. Get the first 3700 // identifier. 3701 Token FirstTok = Tok; 3702 ConsumeToken(); // eat the first identifier. 3703 3704 // Identifier lists follow a really simple grammar: the identifiers can 3705 // be followed *only* by a ", moreidentifiers" or ")". However, K&R 3706 // identifier lists are really rare in the brave new modern world, and it 3707 // is very common for someone to typo a type in a non-k&r style list. If 3708 // we are presented with something like: "void foo(intptr x, float y)", 3709 // we don't want to start parsing the function declarator as though it is 3710 // a K&R style declarator just because intptr is an invalid type. 3711 // 3712 // To handle this, we check to see if the token after the first identifier 3713 // is a "," or ")". Only if so, do we parse it as an identifier list. 3714 if (Tok.is(tok::comma) || Tok.is(tok::r_paren)) 3715 return ParseFunctionDeclaratorIdentifierList(LParenLoc, 3716 FirstTok.getIdentifierInfo(), 3717 FirstTok.getLocation(), D); 3718 3719 // If we get here, the code is invalid. Push the first identifier back 3720 // into the token stream and parse the first argument as an (invalid) 3721 // normal argument declarator. 3722 PP.EnterToken(Tok); 3723 Tok = FirstTok; 3724 } 3725 } 3726 3727 // Finally, a normal, non-empty parameter type list. 3728 3729 // Build up an array of information about the parsed arguments. 3730 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 3731 3732 // Enter function-declaration scope, limiting any declarators to the 3733 // function prototype scope, including parameter declarators. 3734 ParseScope PrototypeScope(this, 3735 Scope::FunctionPrototypeScope|Scope::DeclScope); 3736 3737 bool IsVariadic = false; 3738 SourceLocation EllipsisLoc; 3739 while (1) { 3740 if (Tok.is(tok::ellipsis)) { 3741 IsVariadic = true; 3742 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 3743 break; 3744 } 3745 3746 // Parse the declaration-specifiers. 3747 // Just use the ParsingDeclaration "scope" of the declarator. 3748 DeclSpec DS(AttrFactory); 3749 3750 // Skip any Microsoft attributes before a param. 3751 if (getLang().Microsoft && Tok.is(tok::l_square)) 3752 ParseMicrosoftAttributes(DS.getAttributes()); 3753 3754 SourceLocation DSStart = Tok.getLocation(); 3755 3756 // If the caller parsed attributes for the first argument, add them now. 3757 // Take them so that we only apply the attributes to the first parameter. 3758 DS.takeAttributesFrom(attrs); 3759 3760 ParseDeclarationSpecifiers(DS); 3761 3762 // Parse the declarator. This is "PrototypeContext", because we must 3763 // accept either 'declarator' or 'abstract-declarator' here. 3764 Declarator ParmDecl(DS, Declarator::PrototypeContext); 3765 ParseDeclarator(ParmDecl); 3766 3767 // Parse GNU attributes, if present. 3768 MaybeParseGNUAttributes(ParmDecl); 3769 3770 // Remember this parsed parameter in ParamInfo. 3771 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 3772 3773 // DefArgToks is used when the parsing of default arguments needs 3774 // to be delayed. 3775 CachedTokens *DefArgToks = 0; 3776 3777 // If no parameter was specified, verify that *something* was specified, 3778 // otherwise we have a missing type and identifier. 3779 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 3780 ParmDecl.getNumTypeObjects() == 0) { 3781 // Completely missing, emit error. 3782 Diag(DSStart, diag::err_missing_param); 3783 } else { 3784 // Otherwise, we have something. Add it and let semantic analysis try 3785 // to grok it and add the result to the ParamInfo we are building. 3786 3787 // Inform the actions module about the parameter declarator, so it gets 3788 // added to the current scope. 3789 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 3790 3791 // Parse the default argument, if any. We parse the default 3792 // arguments in all dialects; the semantic analysis in 3793 // ActOnParamDefaultArgument will reject the default argument in 3794 // C. 3795 if (Tok.is(tok::equal)) { 3796 SourceLocation EqualLoc = Tok.getLocation(); 3797 3798 // Parse the default argument 3799 if (D.getContext() == Declarator::MemberContext) { 3800 // If we're inside a class definition, cache the tokens 3801 // corresponding to the default argument. We'll actually parse 3802 // them when we see the end of the class definition. 3803 // FIXME: Templates will require something similar. 3804 // FIXME: Can we use a smart pointer for Toks? 3805 DefArgToks = new CachedTokens; 3806 3807 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 3808 /*StopAtSemi=*/true, 3809 /*ConsumeFinalToken=*/false)) { 3810 delete DefArgToks; 3811 DefArgToks = 0; 3812 Actions.ActOnParamDefaultArgumentError(Param); 3813 } else { 3814 // Mark the end of the default argument so that we know when to 3815 // stop when we parse it later on. 3816 Token DefArgEnd; 3817 DefArgEnd.startToken(); 3818 DefArgEnd.setKind(tok::cxx_defaultarg_end); 3819 DefArgEnd.setLocation(Tok.getLocation()); 3820 DefArgToks->push_back(DefArgEnd); 3821 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 3822 (*DefArgToks)[1].getLocation()); 3823 } 3824 } else { 3825 // Consume the '='. 3826 ConsumeToken(); 3827 3828 // The argument isn't actually potentially evaluated unless it is 3829 // used. 3830 EnterExpressionEvaluationContext Eval(Actions, 3831 Sema::PotentiallyEvaluatedIfUsed); 3832 3833 ExprResult DefArgResult(ParseAssignmentExpression()); 3834 if (DefArgResult.isInvalid()) { 3835 Actions.ActOnParamDefaultArgumentError(Param); 3836 SkipUntil(tok::comma, tok::r_paren, true, true); 3837 } else { 3838 // Inform the actions module about the default argument 3839 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 3840 DefArgResult.take()); 3841 } 3842 } 3843 } 3844 3845 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 3846 ParmDecl.getIdentifierLoc(), Param, 3847 DefArgToks)); 3848 } 3849 3850 // If the next token is a comma, consume it and keep reading arguments. 3851 if (Tok.isNot(tok::comma)) { 3852 if (Tok.is(tok::ellipsis)) { 3853 IsVariadic = true; 3854 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 3855 3856 if (!getLang().CPlusPlus) { 3857 // We have ellipsis without a preceding ',', which is ill-formed 3858 // in C. Complain and provide the fix. 3859 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 3860 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 3861 } 3862 } 3863 3864 break; 3865 } 3866 3867 // Consume the comma. 3868 ConsumeToken(); 3869 } 3870 3871 // If we have the closing ')', eat it. 3872 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 3873 3874 DeclSpec DS(AttrFactory); 3875 SourceLocation RefQualifierLoc; 3876 bool RefQualifierIsLValueRef = true; 3877 ExceptionSpecificationType ESpecType = EST_None; 3878 SourceRange ESpecRange; 3879 llvm::SmallVector<ParsedType, 2> DynamicExceptions; 3880 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges; 3881 ExprResult NoexceptExpr; 3882 3883 if (getLang().CPlusPlus) { 3884 MaybeParseCXX0XAttributes(attrs); 3885 3886 // Parse cv-qualifier-seq[opt]. 3887 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3888 if (!DS.getSourceRange().getEnd().isInvalid()) 3889 EndLoc = DS.getSourceRange().getEnd(); 3890 3891 // Parse ref-qualifier[opt] 3892 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 3893 if (!getLang().CPlusPlus0x) 3894 Diag(Tok, diag::ext_ref_qualifier); 3895 3896 RefQualifierIsLValueRef = Tok.is(tok::amp); 3897 RefQualifierLoc = ConsumeToken(); 3898 EndLoc = RefQualifierLoc; 3899 } 3900 3901 // FIXME: We should leave the prototype scope before parsing the exception 3902 // specification, and then reenter it when parsing the trailing return type. 3903 // FIXMEFIXME: Why? That wouldn't be right for the noexcept clause. 3904 3905 // Parse exception-specification[opt]. 3906 ESpecType = MaybeParseExceptionSpecification(ESpecRange, 3907 DynamicExceptions, 3908 DynamicExceptionRanges, 3909 NoexceptExpr); 3910 if (ESpecType != EST_None) 3911 EndLoc = ESpecRange.getEnd(); 3912 3913 // Parse trailing-return-type. 3914 if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) { 3915 TrailingReturnType = ParseTrailingReturnType().get(); 3916 } 3917 } 3918 3919 // Leave prototype scope. 3920 PrototypeScope.Exit(); 3921 3922 // Remember that we parsed a function type, and remember the attributes. 3923 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic, 3924 EllipsisLoc, 3925 ParamInfo.data(), ParamInfo.size(), 3926 DS.getTypeQualifiers(), 3927 RefQualifierIsLValueRef, 3928 RefQualifierLoc, 3929 ESpecType, ESpecRange.getBegin(), 3930 DynamicExceptions.data(), 3931 DynamicExceptionRanges.data(), 3932 DynamicExceptions.size(), 3933 NoexceptExpr.isUsable() ? 3934 NoexceptExpr.get() : 0, 3935 LParenLoc, EndLoc, D, 3936 TrailingReturnType), 3937 attrs, EndLoc); 3938} 3939 3940/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 3941/// we found a K&R-style identifier list instead of a type argument list. The 3942/// first identifier has already been consumed, and the current token is the 3943/// token right after it. 3944/// 3945/// identifier-list: [C99 6.7.5] 3946/// identifier 3947/// identifier-list ',' identifier 3948/// 3949void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 3950 IdentifierInfo *FirstIdent, 3951 SourceLocation FirstIdentLoc, 3952 Declarator &D) { 3953 // Build up an array of information about the parsed arguments. 3954 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 3955 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 3956 3957 // If there was no identifier specified for the declarator, either we are in 3958 // an abstract-declarator, or we are in a parameter declarator which was found 3959 // to be abstract. In abstract-declarators, identifier lists are not valid: 3960 // diagnose this. 3961 if (!D.getIdentifier()) 3962 Diag(FirstIdentLoc, diag::ext_ident_list_in_param); 3963 3964 // The first identifier was already read, and is known to be the first 3965 // identifier in the list. Remember this identifier in ParamInfo. 3966 ParamsSoFar.insert(FirstIdent); 3967 ParamInfo.push_back(DeclaratorChunk::ParamInfo(FirstIdent, FirstIdentLoc, 0)); 3968 3969 while (Tok.is(tok::comma)) { 3970 // Eat the comma. 3971 ConsumeToken(); 3972 3973 // If this isn't an identifier, report the error and skip until ')'. 3974 if (Tok.isNot(tok::identifier)) { 3975 Diag(Tok, diag::err_expected_ident); 3976 SkipUntil(tok::r_paren); 3977 return; 3978 } 3979 3980 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 3981 3982 // Reject 'typedef int y; int test(x, y)', but continue parsing. 3983 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 3984 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 3985 3986 // Verify that the argument identifier has not already been mentioned. 3987 if (!ParamsSoFar.insert(ParmII)) { 3988 Diag(Tok, diag::err_param_redefinition) << ParmII; 3989 } else { 3990 // Remember this identifier in ParamInfo. 3991 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 3992 Tok.getLocation(), 3993 0)); 3994 } 3995 3996 // Eat the identifier. 3997 ConsumeToken(); 3998 } 3999 4000 // If we have the closing ')', eat it and we're done. 4001 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 4002 4003 // Remember that we parsed a function type, and remember the attributes. This 4004 // function type is always a K&R style function type, which is not varargs and 4005 // has no prototype. 4006 ParsedAttributes attrs(AttrFactory); 4007 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false, 4008 SourceLocation(), 4009 &ParamInfo[0], ParamInfo.size(), 4010 /*TypeQuals*/0, 4011 true, SourceLocation(), 4012 EST_None, SourceLocation(), 0, 0, 4013 0, 0, LParenLoc, RLoc, D), 4014 attrs, RLoc); 4015} 4016 4017/// [C90] direct-declarator '[' constant-expression[opt] ']' 4018/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 4019/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 4020/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 4021/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 4022void Parser::ParseBracketDeclarator(Declarator &D) { 4023 SourceLocation StartLoc = ConsumeBracket(); 4024 4025 // C array syntax has many features, but by-far the most common is [] and [4]. 4026 // This code does a fast path to handle some of the most obvious cases. 4027 if (Tok.getKind() == tok::r_square) { 4028 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 4029 ParsedAttributes attrs(AttrFactory); 4030 MaybeParseCXX0XAttributes(attrs); 4031 4032 // Remember that we parsed the empty array type. 4033 ExprResult NumElements; 4034 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, 4035 StartLoc, EndLoc), 4036 attrs, EndLoc); 4037 return; 4038 } else if (Tok.getKind() == tok::numeric_constant && 4039 GetLookAheadToken(1).is(tok::r_square)) { 4040 // [4] is very common. Parse the numeric constant expression. 4041 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok)); 4042 ConsumeToken(); 4043 4044 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 4045 ParsedAttributes attrs(AttrFactory); 4046 MaybeParseCXX0XAttributes(attrs); 4047 4048 // Remember that we parsed a array type, and remember its features. 4049 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, 4050 ExprRes.release(), 4051 StartLoc, EndLoc), 4052 attrs, EndLoc); 4053 return; 4054 } 4055 4056 // If valid, this location is the position where we read the 'static' keyword. 4057 SourceLocation StaticLoc; 4058 if (Tok.is(tok::kw_static)) 4059 StaticLoc = ConsumeToken(); 4060 4061 // If there is a type-qualifier-list, read it now. 4062 // Type qualifiers in an array subscript are a C99 feature. 4063 DeclSpec DS(AttrFactory); 4064 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 4065 4066 // If we haven't already read 'static', check to see if there is one after the 4067 // type-qualifier-list. 4068 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 4069 StaticLoc = ConsumeToken(); 4070 4071 // Handle "direct-declarator [ type-qual-list[opt] * ]". 4072 bool isStar = false; 4073 ExprResult NumElements; 4074 4075 // Handle the case where we have '[*]' as the array size. However, a leading 4076 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 4077 // the the token after the star is a ']'. Since stars in arrays are 4078 // infrequent, use of lookahead is not costly here. 4079 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 4080 ConsumeToken(); // Eat the '*'. 4081 4082 if (StaticLoc.isValid()) { 4083 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 4084 StaticLoc = SourceLocation(); // Drop the static. 4085 } 4086 isStar = true; 4087 } else if (Tok.isNot(tok::r_square)) { 4088 // Note, in C89, this production uses the constant-expr production instead 4089 // of assignment-expr. The only difference is that assignment-expr allows 4090 // things like '=' and '*='. Sema rejects these in C89 mode because they 4091 // are not i-c-e's, so we don't need to distinguish between the two here. 4092 4093 // Parse the constant-expression or assignment-expression now (depending 4094 // on dialect). 4095 if (getLang().CPlusPlus) 4096 NumElements = ParseConstantExpression(); 4097 else 4098 NumElements = ParseAssignmentExpression(); 4099 } 4100 4101 // If there was an error parsing the assignment-expression, recover. 4102 if (NumElements.isInvalid()) { 4103 D.setInvalidType(true); 4104 // If the expression was invalid, skip it. 4105 SkipUntil(tok::r_square); 4106 return; 4107 } 4108 4109 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 4110 4111 ParsedAttributes attrs(AttrFactory); 4112 MaybeParseCXX0XAttributes(attrs); 4113 4114 // Remember that we parsed a array type, and remember its features. 4115 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 4116 StaticLoc.isValid(), isStar, 4117 NumElements.release(), 4118 StartLoc, EndLoc), 4119 attrs, EndLoc); 4120} 4121 4122/// [GNU] typeof-specifier: 4123/// typeof ( expressions ) 4124/// typeof ( type-name ) 4125/// [GNU/C++] typeof unary-expression 4126/// 4127void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 4128 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 4129 Token OpTok = Tok; 4130 SourceLocation StartLoc = ConsumeToken(); 4131 4132 const bool hasParens = Tok.is(tok::l_paren); 4133 4134 bool isCastExpr; 4135 ParsedType CastTy; 4136 SourceRange CastRange; 4137 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, 4138 CastTy, CastRange); 4139 if (hasParens) 4140 DS.setTypeofParensRange(CastRange); 4141 4142 if (CastRange.getEnd().isInvalid()) 4143 // FIXME: Not accurate, the range gets one token more than it should. 4144 DS.SetRangeEnd(Tok.getLocation()); 4145 else 4146 DS.SetRangeEnd(CastRange.getEnd()); 4147 4148 if (isCastExpr) { 4149 if (!CastTy) { 4150 DS.SetTypeSpecError(); 4151 return; 4152 } 4153 4154 const char *PrevSpec = 0; 4155 unsigned DiagID; 4156 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 4157 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 4158 DiagID, CastTy)) 4159 Diag(StartLoc, DiagID) << PrevSpec; 4160 return; 4161 } 4162 4163 // If we get here, the operand to the typeof was an expresion. 4164 if (Operand.isInvalid()) { 4165 DS.SetTypeSpecError(); 4166 return; 4167 } 4168 4169 const char *PrevSpec = 0; 4170 unsigned DiagID; 4171 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 4172 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 4173 DiagID, Operand.get())) 4174 Diag(StartLoc, DiagID) << PrevSpec; 4175} 4176 4177 4178/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 4179/// from TryAltiVecVectorToken. 4180bool Parser::TryAltiVecVectorTokenOutOfLine() { 4181 Token Next = NextToken(); 4182 switch (Next.getKind()) { 4183 default: return false; 4184 case tok::kw_short: 4185 case tok::kw_long: 4186 case tok::kw_signed: 4187 case tok::kw_unsigned: 4188 case tok::kw_void: 4189 case tok::kw_char: 4190 case tok::kw_int: 4191 case tok::kw_float: 4192 case tok::kw_double: 4193 case tok::kw_bool: 4194 case tok::kw___pixel: 4195 Tok.setKind(tok::kw___vector); 4196 return true; 4197 case tok::identifier: 4198 if (Next.getIdentifierInfo() == Ident_pixel) { 4199 Tok.setKind(tok::kw___vector); 4200 return true; 4201 } 4202 return false; 4203 } 4204} 4205 4206bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 4207 const char *&PrevSpec, unsigned &DiagID, 4208 bool &isInvalid) { 4209 if (Tok.getIdentifierInfo() == Ident_vector) { 4210 Token Next = NextToken(); 4211 switch (Next.getKind()) { 4212 case tok::kw_short: 4213 case tok::kw_long: 4214 case tok::kw_signed: 4215 case tok::kw_unsigned: 4216 case tok::kw_void: 4217 case tok::kw_char: 4218 case tok::kw_int: 4219 case tok::kw_float: 4220 case tok::kw_double: 4221 case tok::kw_bool: 4222 case tok::kw___pixel: 4223 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 4224 return true; 4225 case tok::identifier: 4226 if (Next.getIdentifierInfo() == Ident_pixel) { 4227 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 4228 return true; 4229 } 4230 break; 4231 default: 4232 break; 4233 } 4234 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 4235 DS.isTypeAltiVecVector()) { 4236 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 4237 return true; 4238 } 4239 return false; 4240} 4241