ParseDeclCXX.cpp revision 249423
1//===--- ParseDeclCXX.cpp - C++ 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 C++ Declaration portions of the Parser interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Parse/Parser.h" 15#include "RAIIObjectsForParser.h" 16#include "clang/Basic/CharInfo.h" 17#include "clang/Basic/OperatorKinds.h" 18#include "clang/Parse/ParseDiagnostic.h" 19#include "clang/Sema/DeclSpec.h" 20#include "clang/Sema/ParsedTemplate.h" 21#include "clang/Sema/PrettyDeclStackTrace.h" 22#include "clang/Sema/Scope.h" 23#include "clang/Sema/SemaDiagnostic.h" 24#include "llvm/ADT/SmallString.h" 25using namespace clang; 26 27/// ParseNamespace - We know that the current token is a namespace keyword. This 28/// may either be a top level namespace or a block-level namespace alias. If 29/// there was an inline keyword, it has already been parsed. 30/// 31/// namespace-definition: [C++ 7.3: basic.namespace] 32/// named-namespace-definition 33/// unnamed-namespace-definition 34/// 35/// unnamed-namespace-definition: 36/// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}' 37/// 38/// named-namespace-definition: 39/// original-namespace-definition 40/// extension-namespace-definition 41/// 42/// original-namespace-definition: 43/// 'inline'[opt] 'namespace' identifier attributes[opt] 44/// '{' namespace-body '}' 45/// 46/// extension-namespace-definition: 47/// 'inline'[opt] 'namespace' original-namespace-name 48/// '{' namespace-body '}' 49/// 50/// namespace-alias-definition: [C++ 7.3.2: namespace.alias] 51/// 'namespace' identifier '=' qualified-namespace-specifier ';' 52/// 53Decl *Parser::ParseNamespace(unsigned Context, 54 SourceLocation &DeclEnd, 55 SourceLocation InlineLoc) { 56 assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); 57 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. 58 ObjCDeclContextSwitch ObjCDC(*this); 59 60 if (Tok.is(tok::code_completion)) { 61 Actions.CodeCompleteNamespaceDecl(getCurScope()); 62 cutOffParsing(); 63 return 0; 64 } 65 66 SourceLocation IdentLoc; 67 IdentifierInfo *Ident = 0; 68 std::vector<SourceLocation> ExtraIdentLoc; 69 std::vector<IdentifierInfo*> ExtraIdent; 70 std::vector<SourceLocation> ExtraNamespaceLoc; 71 72 Token attrTok; 73 74 if (Tok.is(tok::identifier)) { 75 Ident = Tok.getIdentifierInfo(); 76 IdentLoc = ConsumeToken(); // eat the identifier. 77 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) { 78 ExtraNamespaceLoc.push_back(ConsumeToken()); 79 ExtraIdent.push_back(Tok.getIdentifierInfo()); 80 ExtraIdentLoc.push_back(ConsumeToken()); 81 } 82 } 83 84 // Read label attributes, if present. 85 ParsedAttributes attrs(AttrFactory); 86 if (Tok.is(tok::kw___attribute)) { 87 attrTok = Tok; 88 ParseGNUAttributes(attrs); 89 } 90 91 if (Tok.is(tok::equal)) { 92 if (Ident == 0) { 93 Diag(Tok, diag::err_expected_ident); 94 // Skip to end of the definition and eat the ';'. 95 SkipUntil(tok::semi); 96 return 0; 97 } 98 if (!attrs.empty()) 99 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias); 100 if (InlineLoc.isValid()) 101 Diag(InlineLoc, diag::err_inline_namespace_alias) 102 << FixItHint::CreateRemoval(InlineLoc); 103 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd); 104 } 105 106 107 BalancedDelimiterTracker T(*this, tok::l_brace); 108 if (T.consumeOpen()) { 109 if (!ExtraIdent.empty()) { 110 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 111 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 112 } 113 Diag(Tok, Ident ? diag::err_expected_lbrace : 114 diag::err_expected_ident_lbrace); 115 return 0; 116 } 117 118 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || 119 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || 120 getCurScope()->getFnParent()) { 121 if (!ExtraIdent.empty()) { 122 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 123 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 124 } 125 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope); 126 SkipUntil(tok::r_brace, false); 127 return 0; 128 } 129 130 if (!ExtraIdent.empty()) { 131 TentativeParsingAction TPA(*this); 132 SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true); 133 Token rBraceToken = Tok; 134 TPA.Revert(); 135 136 if (!rBraceToken.is(tok::r_brace)) { 137 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 138 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 139 } else { 140 std::string NamespaceFix; 141 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(), 142 E = ExtraIdent.end(); I != E; ++I) { 143 NamespaceFix += " { namespace "; 144 NamespaceFix += (*I)->getName(); 145 } 146 147 std::string RBraces; 148 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i) 149 RBraces += "} "; 150 151 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 152 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(), 153 ExtraIdentLoc.back()), 154 NamespaceFix) 155 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces); 156 } 157 } 158 159 // If we're still good, complain about inline namespaces in non-C++0x now. 160 if (InlineLoc.isValid()) 161 Diag(InlineLoc, getLangOpts().CPlusPlus11 ? 162 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace); 163 164 // Enter a scope for the namespace. 165 ParseScope NamespaceScope(this, Scope::DeclScope); 166 167 Decl *NamespcDecl = 168 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc, 169 IdentLoc, Ident, T.getOpenLocation(), 170 attrs.getList()); 171 172 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc, 173 "parsing namespace"); 174 175 // Parse the contents of the namespace. This includes parsing recovery on 176 // any improperly nested namespaces. 177 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0, 178 InlineLoc, attrs, T); 179 180 // Leave the namespace scope. 181 NamespaceScope.Exit(); 182 183 DeclEnd = T.getCloseLocation(); 184 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd); 185 186 return NamespcDecl; 187} 188 189/// ParseInnerNamespace - Parse the contents of a namespace. 190void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc, 191 std::vector<IdentifierInfo*>& Ident, 192 std::vector<SourceLocation>& NamespaceLoc, 193 unsigned int index, SourceLocation& InlineLoc, 194 ParsedAttributes& attrs, 195 BalancedDelimiterTracker &Tracker) { 196 if (index == Ident.size()) { 197 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 198 ParsedAttributesWithRange attrs(AttrFactory); 199 MaybeParseCXX11Attributes(attrs); 200 MaybeParseMicrosoftAttributes(attrs); 201 ParseExternalDeclaration(attrs); 202 } 203 204 // The caller is what called check -- we are simply calling 205 // the close for it. 206 Tracker.consumeClose(); 207 208 return; 209 } 210 211 // Parse improperly nested namespaces. 212 ParseScope NamespaceScope(this, Scope::DeclScope); 213 Decl *NamespcDecl = 214 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(), 215 NamespaceLoc[index], IdentLoc[index], 216 Ident[index], Tracker.getOpenLocation(), 217 attrs.getList()); 218 219 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc, 220 attrs, Tracker); 221 222 NamespaceScope.Exit(); 223 224 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation()); 225} 226 227/// ParseNamespaceAlias - Parse the part after the '=' in a namespace 228/// alias definition. 229/// 230Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, 231 SourceLocation AliasLoc, 232 IdentifierInfo *Alias, 233 SourceLocation &DeclEnd) { 234 assert(Tok.is(tok::equal) && "Not equal token"); 235 236 ConsumeToken(); // eat the '='. 237 238 if (Tok.is(tok::code_completion)) { 239 Actions.CodeCompleteNamespaceAliasDecl(getCurScope()); 240 cutOffParsing(); 241 return 0; 242 } 243 244 CXXScopeSpec SS; 245 // Parse (optional) nested-name-specifier. 246 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 247 248 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 249 Diag(Tok, diag::err_expected_namespace_name); 250 // Skip to end of the definition and eat the ';'. 251 SkipUntil(tok::semi); 252 return 0; 253 } 254 255 // Parse identifier. 256 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 257 SourceLocation IdentLoc = ConsumeToken(); 258 259 // Eat the ';'. 260 DeclEnd = Tok.getLocation(); 261 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name, 262 "", tok::semi); 263 264 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias, 265 SS, IdentLoc, Ident); 266} 267 268/// ParseLinkage - We know that the current token is a string_literal 269/// and just before that, that extern was seen. 270/// 271/// linkage-specification: [C++ 7.5p2: dcl.link] 272/// 'extern' string-literal '{' declaration-seq[opt] '}' 273/// 'extern' string-literal declaration 274/// 275Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) { 276 assert(Tok.is(tok::string_literal) && "Not a string literal!"); 277 SmallString<8> LangBuffer; 278 bool Invalid = false; 279 StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid); 280 if (Invalid) 281 return 0; 282 283 // FIXME: This is incorrect: linkage-specifiers are parsed in translation 284 // phase 7, so string-literal concatenation is supposed to occur. 285 // extern "" "C" "" "+" "+" { } is legal. 286 if (Tok.hasUDSuffix()) 287 Diag(Tok, diag::err_invalid_string_udl); 288 SourceLocation Loc = ConsumeStringToken(); 289 290 ParseScope LinkageScope(this, Scope::DeclScope); 291 Decl *LinkageSpec 292 = Actions.ActOnStartLinkageSpecification(getCurScope(), 293 DS.getSourceRange().getBegin(), 294 Loc, Lang, 295 Tok.is(tok::l_brace) ? Tok.getLocation() 296 : SourceLocation()); 297 298 ParsedAttributesWithRange attrs(AttrFactory); 299 MaybeParseCXX11Attributes(attrs); 300 MaybeParseMicrosoftAttributes(attrs); 301 302 if (Tok.isNot(tok::l_brace)) { 303 // Reset the source range in DS, as the leading "extern" 304 // does not really belong to the inner declaration ... 305 DS.SetRangeStart(SourceLocation()); 306 DS.SetRangeEnd(SourceLocation()); 307 // ... but anyway remember that such an "extern" was seen. 308 DS.setExternInLinkageSpec(true); 309 ParseExternalDeclaration(attrs, &DS); 310 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, 311 SourceLocation()); 312 } 313 314 DS.abort(); 315 316 ProhibitAttributes(attrs); 317 318 BalancedDelimiterTracker T(*this, tok::l_brace); 319 T.consumeOpen(); 320 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 321 ParsedAttributesWithRange attrs(AttrFactory); 322 MaybeParseCXX11Attributes(attrs); 323 MaybeParseMicrosoftAttributes(attrs); 324 ParseExternalDeclaration(attrs); 325 } 326 327 T.consumeClose(); 328 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, 329 T.getCloseLocation()); 330} 331 332/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or 333/// using-directive. Assumes that current token is 'using'. 334Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context, 335 const ParsedTemplateInfo &TemplateInfo, 336 SourceLocation &DeclEnd, 337 ParsedAttributesWithRange &attrs, 338 Decl **OwnedType) { 339 assert(Tok.is(tok::kw_using) && "Not using token"); 340 ObjCDeclContextSwitch ObjCDC(*this); 341 342 // Eat 'using'. 343 SourceLocation UsingLoc = ConsumeToken(); 344 345 if (Tok.is(tok::code_completion)) { 346 Actions.CodeCompleteUsing(getCurScope()); 347 cutOffParsing(); 348 return 0; 349 } 350 351 // 'using namespace' means this is a using-directive. 352 if (Tok.is(tok::kw_namespace)) { 353 // Template parameters are always an error here. 354 if (TemplateInfo.Kind) { 355 SourceRange R = TemplateInfo.getSourceRange(); 356 Diag(UsingLoc, diag::err_templated_using_directive) 357 << R << FixItHint::CreateRemoval(R); 358 } 359 360 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs); 361 } 362 363 // Otherwise, it must be a using-declaration or an alias-declaration. 364 365 // Using declarations can't have attributes. 366 ProhibitAttributes(attrs); 367 368 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd, 369 AS_none, OwnedType); 370} 371 372/// ParseUsingDirective - Parse C++ using-directive, assumes 373/// that current token is 'namespace' and 'using' was already parsed. 374/// 375/// using-directive: [C++ 7.3.p4: namespace.udir] 376/// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 377/// namespace-name ; 378/// [GNU] using-directive: 379/// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 380/// namespace-name attributes[opt] ; 381/// 382Decl *Parser::ParseUsingDirective(unsigned Context, 383 SourceLocation UsingLoc, 384 SourceLocation &DeclEnd, 385 ParsedAttributes &attrs) { 386 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token"); 387 388 // Eat 'namespace'. 389 SourceLocation NamespcLoc = ConsumeToken(); 390 391 if (Tok.is(tok::code_completion)) { 392 Actions.CodeCompleteUsingDirective(getCurScope()); 393 cutOffParsing(); 394 return 0; 395 } 396 397 CXXScopeSpec SS; 398 // Parse (optional) nested-name-specifier. 399 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 400 401 IdentifierInfo *NamespcName = 0; 402 SourceLocation IdentLoc = SourceLocation(); 403 404 // Parse namespace-name. 405 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 406 Diag(Tok, diag::err_expected_namespace_name); 407 // If there was invalid namespace name, skip to end of decl, and eat ';'. 408 SkipUntil(tok::semi); 409 // FIXME: Are there cases, when we would like to call ActOnUsingDirective? 410 return 0; 411 } 412 413 // Parse identifier. 414 NamespcName = Tok.getIdentifierInfo(); 415 IdentLoc = ConsumeToken(); 416 417 // Parse (optional) attributes (most likely GNU strong-using extension). 418 bool GNUAttr = false; 419 if (Tok.is(tok::kw___attribute)) { 420 GNUAttr = true; 421 ParseGNUAttributes(attrs); 422 } 423 424 // Eat ';'. 425 DeclEnd = Tok.getLocation(); 426 ExpectAndConsume(tok::semi, 427 GNUAttr ? diag::err_expected_semi_after_attribute_list 428 : diag::err_expected_semi_after_namespace_name, 429 "", tok::semi); 430 431 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS, 432 IdentLoc, NamespcName, attrs.getList()); 433} 434 435/// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration. 436/// Assumes that 'using' was already seen. 437/// 438/// using-declaration: [C++ 7.3.p3: namespace.udecl] 439/// 'using' 'typename'[opt] ::[opt] nested-name-specifier 440/// unqualified-id 441/// 'using' :: unqualified-id 442/// 443/// alias-declaration: C++11 [dcl.dcl]p1 444/// 'using' identifier attribute-specifier-seq[opt] = type-id ; 445/// 446Decl *Parser::ParseUsingDeclaration(unsigned Context, 447 const ParsedTemplateInfo &TemplateInfo, 448 SourceLocation UsingLoc, 449 SourceLocation &DeclEnd, 450 AccessSpecifier AS, 451 Decl **OwnedType) { 452 CXXScopeSpec SS; 453 SourceLocation TypenameLoc; 454 bool IsTypeName = false; 455 ParsedAttributesWithRange Attrs(AttrFactory); 456 457 // FIXME: Simply skip the attributes and diagnose, don't bother parsing them. 458 MaybeParseCXX11Attributes(Attrs); 459 ProhibitAttributes(Attrs); 460 Attrs.clear(); 461 Attrs.Range = SourceRange(); 462 463 // Ignore optional 'typename'. 464 // FIXME: This is wrong; we should parse this as a typename-specifier. 465 if (Tok.is(tok::kw_typename)) { 466 TypenameLoc = ConsumeToken(); 467 IsTypeName = true; 468 } 469 470 // Parse nested-name-specifier. 471 IdentifierInfo *LastII = 0; 472 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false, 473 /*MayBePseudoDtor=*/0, /*IsTypename=*/false, 474 /*LastII=*/&LastII); 475 476 // Check nested-name specifier. 477 if (SS.isInvalid()) { 478 SkipUntil(tok::semi); 479 return 0; 480 } 481 482 SourceLocation TemplateKWLoc; 483 UnqualifiedId Name; 484 485 // Parse the unqualified-id. We allow parsing of both constructor and 486 // destructor names and allow the action module to diagnose any semantic 487 // errors. 488 // 489 // C++11 [class.qual]p2: 490 // [...] in a using-declaration that is a member-declaration, if the name 491 // specified after the nested-name-specifier is the same as the identifier 492 // or the simple-template-id's template-name in the last component of the 493 // nested-name-specifier, the name is [...] considered to name the 494 // constructor. 495 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext && 496 Tok.is(tok::identifier) && NextToken().is(tok::semi) && 497 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() && 498 !SS.getScopeRep()->getAsNamespace() && 499 !SS.getScopeRep()->getAsNamespaceAlias()) { 500 SourceLocation IdLoc = ConsumeToken(); 501 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII); 502 Name.setConstructorName(Type, IdLoc, IdLoc); 503 } else if (ParseUnqualifiedId(SS, /*EnteringContext=*/ false, 504 /*AllowDestructorName=*/ true, 505 /*AllowConstructorName=*/ true, ParsedType(), 506 TemplateKWLoc, Name)) { 507 SkipUntil(tok::semi); 508 return 0; 509 } 510 511 MaybeParseCXX11Attributes(Attrs); 512 513 // Maybe this is an alias-declaration. 514 bool IsAliasDecl = Tok.is(tok::equal); 515 TypeResult TypeAlias; 516 if (IsAliasDecl) { 517 // TODO: Can GNU attributes appear here? 518 ConsumeToken(); 519 520 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ? 521 diag::warn_cxx98_compat_alias_declaration : 522 diag::ext_alias_declaration); 523 524 // Type alias templates cannot be specialized. 525 int SpecKind = -1; 526 if (TemplateInfo.Kind == ParsedTemplateInfo::Template && 527 Name.getKind() == UnqualifiedId::IK_TemplateId) 528 SpecKind = 0; 529 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) 530 SpecKind = 1; 531 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 532 SpecKind = 2; 533 if (SpecKind != -1) { 534 SourceRange Range; 535 if (SpecKind == 0) 536 Range = SourceRange(Name.TemplateId->LAngleLoc, 537 Name.TemplateId->RAngleLoc); 538 else 539 Range = TemplateInfo.getSourceRange(); 540 Diag(Range.getBegin(), diag::err_alias_declaration_specialization) 541 << SpecKind << Range; 542 SkipUntil(tok::semi); 543 return 0; 544 } 545 546 // Name must be an identifier. 547 if (Name.getKind() != UnqualifiedId::IK_Identifier) { 548 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier); 549 // No removal fixit: can't recover from this. 550 SkipUntil(tok::semi); 551 return 0; 552 } else if (IsTypeName) 553 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier) 554 << FixItHint::CreateRemoval(SourceRange(TypenameLoc, 555 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc)); 556 else if (SS.isNotEmpty()) 557 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier) 558 << FixItHint::CreateRemoval(SS.getRange()); 559 560 TypeAlias = ParseTypeName(0, TemplateInfo.Kind ? 561 Declarator::AliasTemplateContext : 562 Declarator::AliasDeclContext, AS, OwnedType, 563 &Attrs); 564 } else { 565 // C++11 attributes are not allowed on a using-declaration, but GNU ones 566 // are. 567 ProhibitAttributes(Attrs); 568 569 // Parse (optional) attributes (most likely GNU strong-using extension). 570 MaybeParseGNUAttributes(Attrs); 571 } 572 573 // Eat ';'. 574 DeclEnd = Tok.getLocation(); 575 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 576 !Attrs.empty() ? "attributes list" : 577 IsAliasDecl ? "alias declaration" : "using declaration", 578 tok::semi); 579 580 // Diagnose an attempt to declare a templated using-declaration. 581 // In C++11, alias-declarations can be templates: 582 // template <...> using id = type; 583 if (TemplateInfo.Kind && !IsAliasDecl) { 584 SourceRange R = TemplateInfo.getSourceRange(); 585 Diag(UsingLoc, diag::err_templated_using_declaration) 586 << R << FixItHint::CreateRemoval(R); 587 588 // Unfortunately, we have to bail out instead of recovering by 589 // ignoring the parameters, just in case the nested name specifier 590 // depends on the parameters. 591 return 0; 592 } 593 594 // "typename" keyword is allowed for identifiers only, 595 // because it may be a type definition. 596 if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) { 597 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only) 598 << FixItHint::CreateRemoval(SourceRange(TypenameLoc)); 599 // Proceed parsing, but reset the IsTypeName flag. 600 IsTypeName = false; 601 } 602 603 if (IsAliasDecl) { 604 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 605 MultiTemplateParamsArg TemplateParamsArg( 606 TemplateParams ? TemplateParams->data() : 0, 607 TemplateParams ? TemplateParams->size() : 0); 608 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg, 609 UsingLoc, Name, Attrs.getList(), 610 TypeAlias); 611 } 612 613 return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS, 614 Name, Attrs.getList(), 615 IsTypeName, TypenameLoc); 616} 617 618/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration. 619/// 620/// [C++0x] static_assert-declaration: 621/// static_assert ( constant-expression , string-literal ) ; 622/// 623/// [C11] static_assert-declaration: 624/// _Static_assert ( constant-expression , string-literal ) ; 625/// 626Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ 627 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) && 628 "Not a static_assert declaration"); 629 630 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11) 631 Diag(Tok, diag::ext_c11_static_assert); 632 if (Tok.is(tok::kw_static_assert)) 633 Diag(Tok, diag::warn_cxx98_compat_static_assert); 634 635 SourceLocation StaticAssertLoc = ConsumeToken(); 636 637 BalancedDelimiterTracker T(*this, tok::l_paren); 638 if (T.consumeOpen()) { 639 Diag(Tok, diag::err_expected_lparen); 640 SkipMalformedDecl(); 641 return 0; 642 } 643 644 ExprResult AssertExpr(ParseConstantExpression()); 645 if (AssertExpr.isInvalid()) { 646 SkipMalformedDecl(); 647 return 0; 648 } 649 650 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi)) 651 return 0; 652 653 if (!isTokenStringLiteral()) { 654 Diag(Tok, diag::err_expected_string_literal) 655 << /*Source='static_assert'*/1; 656 SkipMalformedDecl(); 657 return 0; 658 } 659 660 ExprResult AssertMessage(ParseStringLiteralExpression()); 661 if (AssertMessage.isInvalid()) { 662 SkipMalformedDecl(); 663 return 0; 664 } 665 666 T.consumeClose(); 667 668 DeclEnd = Tok.getLocation(); 669 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert); 670 671 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, 672 AssertExpr.take(), 673 AssertMessage.take(), 674 T.getCloseLocation()); 675} 676 677/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier. 678/// 679/// 'decltype' ( expression ) 680/// 681SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) { 682 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) 683 && "Not a decltype specifier"); 684 685 686 ExprResult Result; 687 SourceLocation StartLoc = Tok.getLocation(); 688 SourceLocation EndLoc; 689 690 if (Tok.is(tok::annot_decltype)) { 691 Result = getExprAnnotation(Tok); 692 EndLoc = Tok.getAnnotationEndLoc(); 693 ConsumeToken(); 694 if (Result.isInvalid()) { 695 DS.SetTypeSpecError(); 696 return EndLoc; 697 } 698 } else { 699 if (Tok.getIdentifierInfo()->isStr("decltype")) 700 Diag(Tok, diag::warn_cxx98_compat_decltype); 701 702 ConsumeToken(); 703 704 BalancedDelimiterTracker T(*this, tok::l_paren); 705 if (T.expectAndConsume(diag::err_expected_lparen_after, 706 "decltype", tok::r_paren)) { 707 DS.SetTypeSpecError(); 708 return T.getOpenLocation() == Tok.getLocation() ? 709 StartLoc : T.getOpenLocation(); 710 } 711 712 // Parse the expression 713 714 // C++0x [dcl.type.simple]p4: 715 // The operand of the decltype specifier is an unevaluated operand. 716 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 717 0, /*IsDecltype=*/true); 718 Result = ParseExpression(); 719 if (Result.isInvalid()) { 720 DS.SetTypeSpecError(); 721 if (SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true)) { 722 EndLoc = ConsumeParen(); 723 } else { 724 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) { 725 // Backtrack to get the location of the last token before the semi. 726 PP.RevertCachedTokens(2); 727 ConsumeToken(); // the semi. 728 EndLoc = ConsumeAnyToken(); 729 assert(Tok.is(tok::semi)); 730 } else { 731 EndLoc = Tok.getLocation(); 732 } 733 } 734 return EndLoc; 735 } 736 737 // Match the ')' 738 T.consumeClose(); 739 if (T.getCloseLocation().isInvalid()) { 740 DS.SetTypeSpecError(); 741 // FIXME: this should return the location of the last token 742 // that was consumed (by "consumeClose()") 743 return T.getCloseLocation(); 744 } 745 746 Result = Actions.ActOnDecltypeExpression(Result.take()); 747 if (Result.isInvalid()) { 748 DS.SetTypeSpecError(); 749 return T.getCloseLocation(); 750 } 751 752 EndLoc = T.getCloseLocation(); 753 } 754 755 const char *PrevSpec = 0; 756 unsigned DiagID; 757 // Check for duplicate type specifiers (e.g. "int decltype(a)"). 758 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, 759 DiagID, Result.release())) { 760 Diag(StartLoc, DiagID) << PrevSpec; 761 DS.SetTypeSpecError(); 762 } 763 return EndLoc; 764} 765 766void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, 767 SourceLocation StartLoc, 768 SourceLocation EndLoc) { 769 // make sure we have a token we can turn into an annotation token 770 if (PP.isBacktrackEnabled()) 771 PP.RevertCachedTokens(1); 772 else 773 PP.EnterToken(Tok); 774 775 Tok.setKind(tok::annot_decltype); 776 setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ? 777 DS.getRepAsExpr() : ExprResult()); 778 Tok.setAnnotationEndLoc(EndLoc); 779 Tok.setLocation(StartLoc); 780 PP.AnnotateCachedTokens(Tok); 781} 782 783void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) { 784 assert(Tok.is(tok::kw___underlying_type) && 785 "Not an underlying type specifier"); 786 787 SourceLocation StartLoc = ConsumeToken(); 788 BalancedDelimiterTracker T(*this, tok::l_paren); 789 if (T.expectAndConsume(diag::err_expected_lparen_after, 790 "__underlying_type", tok::r_paren)) { 791 return; 792 } 793 794 TypeResult Result = ParseTypeName(); 795 if (Result.isInvalid()) { 796 SkipUntil(tok::r_paren); 797 return; 798 } 799 800 // Match the ')' 801 T.consumeClose(); 802 if (T.getCloseLocation().isInvalid()) 803 return; 804 805 const char *PrevSpec = 0; 806 unsigned DiagID; 807 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec, 808 DiagID, Result.release())) 809 Diag(StartLoc, DiagID) << PrevSpec; 810} 811 812/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a 813/// class name or decltype-specifier. Note that we only check that the result 814/// names a type; semantic analysis will need to verify that the type names a 815/// class. The result is either a type or null, depending on whether a type 816/// name was found. 817/// 818/// base-type-specifier: [C++11 class.derived] 819/// class-or-decltype 820/// class-or-decltype: [C++11 class.derived] 821/// nested-name-specifier[opt] class-name 822/// decltype-specifier 823/// class-name: [C++ class.name] 824/// identifier 825/// simple-template-id 826/// 827/// In C++98, instead of base-type-specifier, we have: 828/// 829/// ::[opt] nested-name-specifier[opt] class-name 830Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc, 831 SourceLocation &EndLocation) { 832 // Ignore attempts to use typename 833 if (Tok.is(tok::kw_typename)) { 834 Diag(Tok, diag::err_expected_class_name_not_template) 835 << FixItHint::CreateRemoval(Tok.getLocation()); 836 ConsumeToken(); 837 } 838 839 // Parse optional nested-name-specifier 840 CXXScopeSpec SS; 841 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 842 843 BaseLoc = Tok.getLocation(); 844 845 // Parse decltype-specifier 846 // tok == kw_decltype is just error recovery, it can only happen when SS 847 // isn't empty 848 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) { 849 if (SS.isNotEmpty()) 850 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype) 851 << FixItHint::CreateRemoval(SS.getRange()); 852 // Fake up a Declarator to use with ActOnTypeName. 853 DeclSpec DS(AttrFactory); 854 855 EndLocation = ParseDecltypeSpecifier(DS); 856 857 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 858 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 859 } 860 861 // Check whether we have a template-id that names a type. 862 if (Tok.is(tok::annot_template_id)) { 863 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 864 if (TemplateId->Kind == TNK_Type_template || 865 TemplateId->Kind == TNK_Dependent_template_name) { 866 AnnotateTemplateIdTokenAsType(); 867 868 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 869 ParsedType Type = getTypeAnnotation(Tok); 870 EndLocation = Tok.getAnnotationEndLoc(); 871 ConsumeToken(); 872 873 if (Type) 874 return Type; 875 return true; 876 } 877 878 // Fall through to produce an error below. 879 } 880 881 if (Tok.isNot(tok::identifier)) { 882 Diag(Tok, diag::err_expected_class_name); 883 return true; 884 } 885 886 IdentifierInfo *Id = Tok.getIdentifierInfo(); 887 SourceLocation IdLoc = ConsumeToken(); 888 889 if (Tok.is(tok::less)) { 890 // It looks the user intended to write a template-id here, but the 891 // template-name was wrong. Try to fix that. 892 TemplateNameKind TNK = TNK_Type_template; 893 TemplateTy Template; 894 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(), 895 &SS, Template, TNK)) { 896 Diag(IdLoc, diag::err_unknown_template_name) 897 << Id; 898 } 899 900 if (!Template) 901 return true; 902 903 // Form the template name 904 UnqualifiedId TemplateName; 905 TemplateName.setIdentifier(Id, IdLoc); 906 907 // Parse the full template-id, then turn it into a type. 908 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 909 TemplateName, true)) 910 return true; 911 if (TNK == TNK_Dependent_template_name) 912 AnnotateTemplateIdTokenAsType(); 913 914 // If we didn't end up with a typename token, there's nothing more we 915 // can do. 916 if (Tok.isNot(tok::annot_typename)) 917 return true; 918 919 // Retrieve the type from the annotation token, consume that token, and 920 // return. 921 EndLocation = Tok.getAnnotationEndLoc(); 922 ParsedType Type = getTypeAnnotation(Tok); 923 ConsumeToken(); 924 return Type; 925 } 926 927 // We have an identifier; check whether it is actually a type. 928 IdentifierInfo *CorrectedII = 0; 929 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true, 930 false, ParsedType(), 931 /*IsCtorOrDtorName=*/false, 932 /*NonTrivialTypeSourceInfo=*/true, 933 &CorrectedII); 934 if (!Type) { 935 Diag(IdLoc, diag::err_expected_class_name); 936 return true; 937 } 938 939 // Consume the identifier. 940 EndLocation = IdLoc; 941 942 // Fake up a Declarator to use with ActOnTypeName. 943 DeclSpec DS(AttrFactory); 944 DS.SetRangeStart(IdLoc); 945 DS.SetRangeEnd(EndLocation); 946 DS.getTypeSpecScope() = SS; 947 948 const char *PrevSpec = 0; 949 unsigned DiagID; 950 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type); 951 952 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 953 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 954} 955 956void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) { 957 while (Tok.is(tok::kw___single_inheritance) || 958 Tok.is(tok::kw___multiple_inheritance) || 959 Tok.is(tok::kw___virtual_inheritance)) { 960 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 961 SourceLocation AttrNameLoc = ConsumeToken(); 962 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 963 SourceLocation(), 0, 0, AttributeList::AS_GNU); 964 } 965} 966 967/// Determine whether the following tokens are valid after a type-specifier 968/// which could be a standalone declaration. This will conservatively return 969/// true if there's any doubt, and is appropriate for insert-';' fixits. 970bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) { 971 // This switch enumerates the valid "follow" set for type-specifiers. 972 switch (Tok.getKind()) { 973 default: break; 974 case tok::semi: // struct foo {...} ; 975 case tok::star: // struct foo {...} * P; 976 case tok::amp: // struct foo {...} & R = ... 977 case tok::ampamp: // struct foo {...} && R = ... 978 case tok::identifier: // struct foo {...} V ; 979 case tok::r_paren: //(struct foo {...} ) {4} 980 case tok::annot_cxxscope: // struct foo {...} a:: b; 981 case tok::annot_typename: // struct foo {...} a ::b; 982 case tok::annot_template_id: // struct foo {...} a<int> ::b; 983 case tok::l_paren: // struct foo {...} ( x); 984 case tok::comma: // __builtin_offsetof(struct foo{...} , 985 case tok::kw_operator: // struct foo operator ++() {...} 986 return true; 987 case tok::colon: 988 return CouldBeBitfield; // enum E { ... } : 2; 989 // Type qualifiers 990 case tok::kw_const: // struct foo {...} const x; 991 case tok::kw_volatile: // struct foo {...} volatile x; 992 case tok::kw_restrict: // struct foo {...} restrict x; 993 // Function specifiers 994 // Note, no 'explicit'. An explicit function must be either a conversion 995 // operator or a constructor. Either way, it can't have a return type. 996 case tok::kw_inline: // struct foo inline f(); 997 case tok::kw_virtual: // struct foo virtual f(); 998 case tok::kw_friend: // struct foo friend f(); 999 // Storage-class specifiers 1000 case tok::kw_static: // struct foo {...} static x; 1001 case tok::kw_extern: // struct foo {...} extern x; 1002 case tok::kw_typedef: // struct foo {...} typedef x; 1003 case tok::kw_register: // struct foo {...} register x; 1004 case tok::kw_auto: // struct foo {...} auto x; 1005 case tok::kw_mutable: // struct foo {...} mutable x; 1006 case tok::kw_thread_local: // struct foo {...} thread_local x; 1007 case tok::kw_constexpr: // struct foo {...} constexpr x; 1008 // As shown above, type qualifiers and storage class specifiers absolutely 1009 // can occur after class specifiers according to the grammar. However, 1010 // almost no one actually writes code like this. If we see one of these, 1011 // it is much more likely that someone missed a semi colon and the 1012 // type/storage class specifier we're seeing is part of the *next* 1013 // intended declaration, as in: 1014 // 1015 // struct foo { ... } 1016 // typedef int X; 1017 // 1018 // We'd really like to emit a missing semicolon error instead of emitting 1019 // an error on the 'int' saying that you can't have two type specifiers in 1020 // the same declaration of X. Because of this, we look ahead past this 1021 // token to see if it's a type specifier. If so, we know the code is 1022 // otherwise invalid, so we can produce the expected semi error. 1023 if (!isKnownToBeTypeSpecifier(NextToken())) 1024 return true; 1025 break; 1026 case tok::r_brace: // struct bar { struct foo {...} } 1027 // Missing ';' at end of struct is accepted as an extension in C mode. 1028 if (!getLangOpts().CPlusPlus) 1029 return true; 1030 break; 1031 // C++11 attributes 1032 case tok::l_square: // enum E [[]] x 1033 // Note, no tok::kw_alignas here; alignas cannot appertain to a type. 1034 return getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square); 1035 case tok::greater: 1036 // template<class T = class X> 1037 return getLangOpts().CPlusPlus; 1038 } 1039 return false; 1040} 1041 1042/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or 1043/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which 1044/// until we reach the start of a definition or see a token that 1045/// cannot start a definition. 1046/// 1047/// class-specifier: [C++ class] 1048/// class-head '{' member-specification[opt] '}' 1049/// class-head '{' member-specification[opt] '}' attributes[opt] 1050/// class-head: 1051/// class-key identifier[opt] base-clause[opt] 1052/// class-key nested-name-specifier identifier base-clause[opt] 1053/// class-key nested-name-specifier[opt] simple-template-id 1054/// base-clause[opt] 1055/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] 1056/// [GNU] class-key attributes[opt] nested-name-specifier 1057/// identifier base-clause[opt] 1058/// [GNU] class-key attributes[opt] nested-name-specifier[opt] 1059/// simple-template-id base-clause[opt] 1060/// class-key: 1061/// 'class' 1062/// 'struct' 1063/// 'union' 1064/// 1065/// elaborated-type-specifier: [C++ dcl.type.elab] 1066/// class-key ::[opt] nested-name-specifier[opt] identifier 1067/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] 1068/// simple-template-id 1069/// 1070/// Note that the C++ class-specifier and elaborated-type-specifier, 1071/// together, subsume the C99 struct-or-union-specifier: 1072/// 1073/// struct-or-union-specifier: [C99 6.7.2.1] 1074/// struct-or-union identifier[opt] '{' struct-contents '}' 1075/// struct-or-union identifier 1076/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents 1077/// '}' attributes[opt] 1078/// [GNU] struct-or-union attributes[opt] identifier 1079/// struct-or-union: 1080/// 'struct' 1081/// 'union' 1082void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, 1083 SourceLocation StartLoc, DeclSpec &DS, 1084 const ParsedTemplateInfo &TemplateInfo, 1085 AccessSpecifier AS, 1086 bool EnteringContext, DeclSpecContext DSC, 1087 ParsedAttributesWithRange &Attributes) { 1088 DeclSpec::TST TagType; 1089 if (TagTokKind == tok::kw_struct) 1090 TagType = DeclSpec::TST_struct; 1091 else if (TagTokKind == tok::kw___interface) 1092 TagType = DeclSpec::TST_interface; 1093 else if (TagTokKind == tok::kw_class) 1094 TagType = DeclSpec::TST_class; 1095 else { 1096 assert(TagTokKind == tok::kw_union && "Not a class specifier"); 1097 TagType = DeclSpec::TST_union; 1098 } 1099 1100 if (Tok.is(tok::code_completion)) { 1101 // Code completion for a struct, class, or union name. 1102 Actions.CodeCompleteTag(getCurScope(), TagType); 1103 return cutOffParsing(); 1104 } 1105 1106 // C++03 [temp.explicit] 14.7.2/8: 1107 // The usual access checking rules do not apply to names used to specify 1108 // explicit instantiations. 1109 // 1110 // As an extension we do not perform access checking on the names used to 1111 // specify explicit specializations either. This is important to allow 1112 // specializing traits classes for private types. 1113 // 1114 // Note that we don't suppress if this turns out to be an elaborated 1115 // type specifier. 1116 bool shouldDelayDiagsInTag = 1117 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 1118 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 1119 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 1120 1121 ParsedAttributesWithRange attrs(AttrFactory); 1122 // If attributes exist after tag, parse them. 1123 if (Tok.is(tok::kw___attribute)) 1124 ParseGNUAttributes(attrs); 1125 1126 // If declspecs exist after tag, parse them. 1127 while (Tok.is(tok::kw___declspec)) 1128 ParseMicrosoftDeclSpec(attrs); 1129 1130 // Parse inheritance specifiers. 1131 if (Tok.is(tok::kw___single_inheritance) || 1132 Tok.is(tok::kw___multiple_inheritance) || 1133 Tok.is(tok::kw___virtual_inheritance)) 1134 ParseMicrosoftInheritanceClassAttributes(attrs); 1135 1136 // If C++0x attributes exist here, parse them. 1137 // FIXME: Are we consistent with the ordering of parsing of different 1138 // styles of attributes? 1139 MaybeParseCXX11Attributes(attrs); 1140 1141 // Source location used by FIXIT to insert misplaced 1142 // C++11 attributes 1143 SourceLocation AttrFixitLoc = Tok.getLocation(); 1144 1145 if (TagType == DeclSpec::TST_struct && 1146 !Tok.is(tok::identifier) && 1147 Tok.getIdentifierInfo() && 1148 (Tok.is(tok::kw___is_arithmetic) || 1149 Tok.is(tok::kw___is_convertible) || 1150 Tok.is(tok::kw___is_empty) || 1151 Tok.is(tok::kw___is_floating_point) || 1152 Tok.is(tok::kw___is_function) || 1153 Tok.is(tok::kw___is_fundamental) || 1154 Tok.is(tok::kw___is_integral) || 1155 Tok.is(tok::kw___is_member_function_pointer) || 1156 Tok.is(tok::kw___is_member_pointer) || 1157 Tok.is(tok::kw___is_pod) || 1158 Tok.is(tok::kw___is_pointer) || 1159 Tok.is(tok::kw___is_same) || 1160 Tok.is(tok::kw___is_scalar) || 1161 Tok.is(tok::kw___is_signed) || 1162 Tok.is(tok::kw___is_unsigned) || 1163 Tok.is(tok::kw___is_void))) { 1164 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the 1165 // name of struct templates, but some are keywords in GCC >= 4.3 1166 // and Clang. Therefore, when we see the token sequence "struct 1167 // X", make X into a normal identifier rather than a keyword, to 1168 // allow libstdc++ 4.2 and libc++ to work properly. 1169 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 1170 Tok.setKind(tok::identifier); 1171 } 1172 1173 // Parse the (optional) nested-name-specifier. 1174 CXXScopeSpec &SS = DS.getTypeSpecScope(); 1175 if (getLangOpts().CPlusPlus) { 1176 // "FOO : BAR" is not a potential typo for "FOO::BAR". 1177 ColonProtectionRAIIObject X(*this); 1178 1179 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1180 DS.SetTypeSpecError(); 1181 if (SS.isSet()) 1182 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 1183 Diag(Tok, diag::err_expected_ident); 1184 } 1185 1186 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 1187 1188 // Parse the (optional) class name or simple-template-id. 1189 IdentifierInfo *Name = 0; 1190 SourceLocation NameLoc; 1191 TemplateIdAnnotation *TemplateId = 0; 1192 if (Tok.is(tok::identifier)) { 1193 Name = Tok.getIdentifierInfo(); 1194 NameLoc = ConsumeToken(); 1195 1196 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) { 1197 // The name was supposed to refer to a template, but didn't. 1198 // Eat the template argument list and try to continue parsing this as 1199 // a class (or template thereof). 1200 TemplateArgList TemplateArgs; 1201 SourceLocation LAngleLoc, RAngleLoc; 1202 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS, 1203 true, LAngleLoc, 1204 TemplateArgs, RAngleLoc)) { 1205 // We couldn't parse the template argument list at all, so don't 1206 // try to give any location information for the list. 1207 LAngleLoc = RAngleLoc = SourceLocation(); 1208 } 1209 1210 Diag(NameLoc, diag::err_explicit_spec_non_template) 1211 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 1212 << (TagType == DeclSpec::TST_class? 0 1213 : TagType == DeclSpec::TST_struct? 1 1214 : TagType == DeclSpec::TST_interface? 2 1215 : 3) 1216 << Name 1217 << SourceRange(LAngleLoc, RAngleLoc); 1218 1219 // Strip off the last template parameter list if it was empty, since 1220 // we've removed its template argument list. 1221 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) { 1222 if (TemplateParams && TemplateParams->size() > 1) { 1223 TemplateParams->pop_back(); 1224 } else { 1225 TemplateParams = 0; 1226 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 1227 = ParsedTemplateInfo::NonTemplate; 1228 } 1229 } else if (TemplateInfo.Kind 1230 == ParsedTemplateInfo::ExplicitInstantiation) { 1231 // Pretend this is just a forward declaration. 1232 TemplateParams = 0; 1233 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 1234 = ParsedTemplateInfo::NonTemplate; 1235 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc 1236 = SourceLocation(); 1237 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc 1238 = SourceLocation(); 1239 } 1240 } 1241 } else if (Tok.is(tok::annot_template_id)) { 1242 TemplateId = takeTemplateIdAnnotation(Tok); 1243 NameLoc = ConsumeToken(); 1244 1245 if (TemplateId->Kind != TNK_Type_template && 1246 TemplateId->Kind != TNK_Dependent_template_name) { 1247 // The template-name in the simple-template-id refers to 1248 // something other than a class template. Give an appropriate 1249 // error message and skip to the ';'. 1250 SourceRange Range(NameLoc); 1251 if (SS.isNotEmpty()) 1252 Range.setBegin(SS.getBeginLoc()); 1253 1254 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) 1255 << Name << static_cast<int>(TemplateId->Kind) << Range; 1256 1257 DS.SetTypeSpecError(); 1258 SkipUntil(tok::semi, false, true); 1259 return; 1260 } 1261 } 1262 1263 // There are four options here. 1264 // - If we are in a trailing return type, this is always just a reference, 1265 // and we must not try to parse a definition. For instance, 1266 // [] () -> struct S { }; 1267 // does not define a type. 1268 // - If we have 'struct foo {...', 'struct foo :...', 1269 // 'struct foo final :' or 'struct foo final {', then this is a definition. 1270 // - If we have 'struct foo;', then this is either a forward declaration 1271 // or a friend declaration, which have to be treated differently. 1272 // - Otherwise we have something like 'struct foo xyz', a reference. 1273 // 1274 // We also detect these erroneous cases to provide better diagnostic for 1275 // C++11 attributes parsing. 1276 // - attributes follow class name: 1277 // struct foo [[]] {}; 1278 // - attributes appear before or after 'final': 1279 // struct foo [[]] final [[]] {}; 1280 // 1281 // However, in type-specifier-seq's, things look like declarations but are 1282 // just references, e.g. 1283 // new struct s; 1284 // or 1285 // &T::operator struct s; 1286 // For these, DSC is DSC_type_specifier. 1287 1288 // If there are attributes after class name, parse them. 1289 MaybeParseCXX11Attributes(Attributes); 1290 1291 Sema::TagUseKind TUK; 1292 if (DSC == DSC_trailing) 1293 TUK = Sema::TUK_Reference; 1294 else if (Tok.is(tok::l_brace) || 1295 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) || 1296 (isCXX11FinalKeyword() && 1297 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) { 1298 if (DS.isFriendSpecified()) { 1299 // C++ [class.friend]p2: 1300 // A class shall not be defined in a friend declaration. 1301 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 1302 << SourceRange(DS.getFriendSpecLoc()); 1303 1304 // Skip everything up to the semicolon, so that this looks like a proper 1305 // friend class (or template thereof) declaration. 1306 SkipUntil(tok::semi, true, true); 1307 TUK = Sema::TUK_Friend; 1308 } else { 1309 // Okay, this is a class definition. 1310 TUK = Sema::TUK_Definition; 1311 } 1312 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) || 1313 NextToken().is(tok::kw_alignas))) { 1314 // We can't tell if this is a definition or reference 1315 // until we skipped the 'final' and C++11 attribute specifiers. 1316 TentativeParsingAction PA(*this); 1317 1318 // Skip the 'final' keyword. 1319 ConsumeToken(); 1320 1321 // Skip C++11 attribute specifiers. 1322 while (true) { 1323 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) { 1324 ConsumeBracket(); 1325 if (!SkipUntil(tok::r_square)) 1326 break; 1327 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) { 1328 ConsumeToken(); 1329 ConsumeParen(); 1330 if (!SkipUntil(tok::r_paren)) 1331 break; 1332 } else { 1333 break; 1334 } 1335 } 1336 1337 if (Tok.is(tok::l_brace) || Tok.is(tok::colon)) 1338 TUK = Sema::TUK_Definition; 1339 else 1340 TUK = Sema::TUK_Reference; 1341 1342 PA.Revert(); 1343 } else if (DSC != DSC_type_specifier && 1344 (Tok.is(tok::semi) || 1345 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) { 1346 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 1347 if (Tok.isNot(tok::semi)) { 1348 // A semicolon was missing after this declaration. Diagnose and recover. 1349 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 1350 DeclSpec::getSpecifierName(TagType)); 1351 PP.EnterToken(Tok); 1352 Tok.setKind(tok::semi); 1353 } 1354 } else 1355 TUK = Sema::TUK_Reference; 1356 1357 // Forbid misplaced attributes. In cases of a reference, we pass attributes 1358 // to caller to handle. 1359 if (TUK != Sema::TUK_Reference) { 1360 // If this is not a reference, then the only possible 1361 // valid place for C++11 attributes to appear here 1362 // is between class-key and class-name. If there are 1363 // any attributes after class-name, we try a fixit to move 1364 // them to the right place. 1365 SourceRange AttrRange = Attributes.Range; 1366 if (AttrRange.isValid()) { 1367 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed) 1368 << AttrRange 1369 << FixItHint::CreateInsertionFromRange(AttrFixitLoc, 1370 CharSourceRange(AttrRange, true)) 1371 << FixItHint::CreateRemoval(AttrRange); 1372 1373 // Recover by adding misplaced attributes to the attribute list 1374 // of the class so they can be applied on the class later. 1375 attrs.takeAllFrom(Attributes); 1376 } 1377 } 1378 1379 // If this is an elaborated type specifier, and we delayed 1380 // diagnostics before, just merge them into the current pool. 1381 if (shouldDelayDiagsInTag) { 1382 diagsFromTag.done(); 1383 if (TUK == Sema::TUK_Reference) 1384 diagsFromTag.redelay(); 1385 } 1386 1387 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error || 1388 TUK != Sema::TUK_Definition)) { 1389 if (DS.getTypeSpecType() != DeclSpec::TST_error) { 1390 // We have a declaration or reference to an anonymous class. 1391 Diag(StartLoc, diag::err_anon_type_definition) 1392 << DeclSpec::getSpecifierName(TagType); 1393 } 1394 1395 SkipUntil(tok::comma, true); 1396 return; 1397 } 1398 1399 // Create the tag portion of the class or class template. 1400 DeclResult TagOrTempResult = true; // invalid 1401 TypeResult TypeResult = true; // invalid 1402 1403 bool Owned = false; 1404 if (TemplateId) { 1405 // Explicit specialization, class template partial specialization, 1406 // or explicit instantiation. 1407 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1408 TemplateId->NumArgs); 1409 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 1410 TUK == Sema::TUK_Declaration) { 1411 // This is an explicit instantiation of a class template. 1412 ProhibitAttributes(attrs); 1413 1414 TagOrTempResult 1415 = Actions.ActOnExplicitInstantiation(getCurScope(), 1416 TemplateInfo.ExternLoc, 1417 TemplateInfo.TemplateLoc, 1418 TagType, 1419 StartLoc, 1420 SS, 1421 TemplateId->Template, 1422 TemplateId->TemplateNameLoc, 1423 TemplateId->LAngleLoc, 1424 TemplateArgsPtr, 1425 TemplateId->RAngleLoc, 1426 attrs.getList()); 1427 1428 // Friend template-ids are treated as references unless 1429 // they have template headers, in which case they're ill-formed 1430 // (FIXME: "template <class T> friend class A<T>::B<int>;"). 1431 // We diagnose this error in ActOnClassTemplateSpecialization. 1432 } else if (TUK == Sema::TUK_Reference || 1433 (TUK == Sema::TUK_Friend && 1434 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) { 1435 ProhibitAttributes(attrs); 1436 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc, 1437 TemplateId->SS, 1438 TemplateId->TemplateKWLoc, 1439 TemplateId->Template, 1440 TemplateId->TemplateNameLoc, 1441 TemplateId->LAngleLoc, 1442 TemplateArgsPtr, 1443 TemplateId->RAngleLoc); 1444 } else { 1445 // This is an explicit specialization or a class template 1446 // partial specialization. 1447 TemplateParameterLists FakedParamLists; 1448 1449 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 1450 // This looks like an explicit instantiation, because we have 1451 // something like 1452 // 1453 // template class Foo<X> 1454 // 1455 // but it actually has a definition. Most likely, this was 1456 // meant to be an explicit specialization, but the user forgot 1457 // the '<>' after 'template'. 1458 assert(TUK == Sema::TUK_Definition && "Expected a definition here"); 1459 1460 SourceLocation LAngleLoc 1461 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 1462 Diag(TemplateId->TemplateNameLoc, 1463 diag::err_explicit_instantiation_with_definition) 1464 << SourceRange(TemplateInfo.TemplateLoc) 1465 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 1466 1467 // Create a fake template parameter list that contains only 1468 // "template<>", so that we treat this construct as a class 1469 // template specialization. 1470 FakedParamLists.push_back( 1471 Actions.ActOnTemplateParameterList(0, SourceLocation(), 1472 TemplateInfo.TemplateLoc, 1473 LAngleLoc, 1474 0, 0, 1475 LAngleLoc)); 1476 TemplateParams = &FakedParamLists; 1477 } 1478 1479 // Build the class template specialization. 1480 TagOrTempResult 1481 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK, 1482 StartLoc, DS.getModulePrivateSpecLoc(), SS, 1483 TemplateId->Template, 1484 TemplateId->TemplateNameLoc, 1485 TemplateId->LAngleLoc, 1486 TemplateArgsPtr, 1487 TemplateId->RAngleLoc, 1488 attrs.getList(), 1489 MultiTemplateParamsArg( 1490 TemplateParams? &(*TemplateParams)[0] : 0, 1491 TemplateParams? TemplateParams->size() : 0)); 1492 } 1493 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 1494 TUK == Sema::TUK_Declaration) { 1495 // Explicit instantiation of a member of a class template 1496 // specialization, e.g., 1497 // 1498 // template struct Outer<int>::Inner; 1499 // 1500 ProhibitAttributes(attrs); 1501 1502 TagOrTempResult 1503 = Actions.ActOnExplicitInstantiation(getCurScope(), 1504 TemplateInfo.ExternLoc, 1505 TemplateInfo.TemplateLoc, 1506 TagType, StartLoc, SS, Name, 1507 NameLoc, attrs.getList()); 1508 } else if (TUK == Sema::TUK_Friend && 1509 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) { 1510 ProhibitAttributes(attrs); 1511 1512 TagOrTempResult = 1513 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(), 1514 TagType, StartLoc, SS, 1515 Name, NameLoc, attrs.getList(), 1516 MultiTemplateParamsArg( 1517 TemplateParams? &(*TemplateParams)[0] : 0, 1518 TemplateParams? TemplateParams->size() : 0)); 1519 } else { 1520 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition) 1521 ProhibitAttributes(attrs); 1522 1523 bool IsDependent = false; 1524 1525 // Don't pass down template parameter lists if this is just a tag 1526 // reference. For example, we don't need the template parameters here: 1527 // template <class T> class A *makeA(T t); 1528 MultiTemplateParamsArg TParams; 1529 if (TUK != Sema::TUK_Reference && TemplateParams) 1530 TParams = 1531 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size()); 1532 1533 // Declaration or definition of a class type 1534 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc, 1535 SS, Name, NameLoc, attrs.getList(), AS, 1536 DS.getModulePrivateSpecLoc(), 1537 TParams, Owned, IsDependent, 1538 SourceLocation(), false, 1539 clang::TypeResult()); 1540 1541 // If ActOnTag said the type was dependent, try again with the 1542 // less common call. 1543 if (IsDependent) { 1544 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend); 1545 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, 1546 SS, Name, StartLoc, NameLoc); 1547 } 1548 } 1549 1550 // If there is a body, parse it and inform the actions module. 1551 if (TUK == Sema::TUK_Definition) { 1552 assert(Tok.is(tok::l_brace) || 1553 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) || 1554 isCXX11FinalKeyword()); 1555 if (getLangOpts().CPlusPlus) 1556 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType, 1557 TagOrTempResult.get()); 1558 else 1559 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); 1560 } 1561 1562 const char *PrevSpec = 0; 1563 unsigned DiagID; 1564 bool Result; 1565 if (!TypeResult.isInvalid()) { 1566 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 1567 NameLoc.isValid() ? NameLoc : StartLoc, 1568 PrevSpec, DiagID, TypeResult.get()); 1569 } else if (!TagOrTempResult.isInvalid()) { 1570 Result = DS.SetTypeSpecType(TagType, StartLoc, 1571 NameLoc.isValid() ? NameLoc : StartLoc, 1572 PrevSpec, DiagID, TagOrTempResult.get(), Owned); 1573 } else { 1574 DS.SetTypeSpecError(); 1575 return; 1576 } 1577 1578 if (Result) 1579 Diag(StartLoc, DiagID) << PrevSpec; 1580 1581 // At this point, we've successfully parsed a class-specifier in 'definition' 1582 // form (e.g. "struct foo { int x; }". While we could just return here, we're 1583 // going to look at what comes after it to improve error recovery. If an 1584 // impossible token occurs next, we assume that the programmer forgot a ; at 1585 // the end of the declaration and recover that way. 1586 // 1587 // Also enforce C++ [temp]p3: 1588 // In a template-declaration which defines a class, no declarator 1589 // is permitted. 1590 if (TUK == Sema::TUK_Definition && 1591 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) { 1592 if (Tok.isNot(tok::semi)) { 1593 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 1594 DeclSpec::getSpecifierName(TagType)); 1595 // Push this token back into the preprocessor and change our current token 1596 // to ';' so that the rest of the code recovers as though there were an 1597 // ';' after the definition. 1598 PP.EnterToken(Tok); 1599 Tok.setKind(tok::semi); 1600 } 1601 } 1602} 1603 1604/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 1605/// 1606/// base-clause : [C++ class.derived] 1607/// ':' base-specifier-list 1608/// base-specifier-list: 1609/// base-specifier '...'[opt] 1610/// base-specifier-list ',' base-specifier '...'[opt] 1611void Parser::ParseBaseClause(Decl *ClassDecl) { 1612 assert(Tok.is(tok::colon) && "Not a base clause"); 1613 ConsumeToken(); 1614 1615 // Build up an array of parsed base specifiers. 1616 SmallVector<CXXBaseSpecifier *, 8> BaseInfo; 1617 1618 while (true) { 1619 // Parse a base-specifier. 1620 BaseResult Result = ParseBaseSpecifier(ClassDecl); 1621 if (Result.isInvalid()) { 1622 // Skip the rest of this base specifier, up until the comma or 1623 // opening brace. 1624 SkipUntil(tok::comma, tok::l_brace, true, true); 1625 } else { 1626 // Add this to our array of base specifiers. 1627 BaseInfo.push_back(Result.get()); 1628 } 1629 1630 // If the next token is a comma, consume it and keep reading 1631 // base-specifiers. 1632 if (Tok.isNot(tok::comma)) break; 1633 1634 // Consume the comma. 1635 ConsumeToken(); 1636 } 1637 1638 // Attach the base specifiers 1639 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); 1640} 1641 1642/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 1643/// one entry in the base class list of a class specifier, for example: 1644/// class foo : public bar, virtual private baz { 1645/// 'public bar' and 'virtual private baz' are each base-specifiers. 1646/// 1647/// base-specifier: [C++ class.derived] 1648/// attribute-specifier-seq[opt] base-type-specifier 1649/// attribute-specifier-seq[opt] 'virtual' access-specifier[opt] 1650/// base-type-specifier 1651/// attribute-specifier-seq[opt] access-specifier 'virtual'[opt] 1652/// base-type-specifier 1653Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) { 1654 bool IsVirtual = false; 1655 SourceLocation StartLoc = Tok.getLocation(); 1656 1657 ParsedAttributesWithRange Attributes(AttrFactory); 1658 MaybeParseCXX11Attributes(Attributes); 1659 1660 // Parse the 'virtual' keyword. 1661 if (Tok.is(tok::kw_virtual)) { 1662 ConsumeToken(); 1663 IsVirtual = true; 1664 } 1665 1666 CheckMisplacedCXX11Attribute(Attributes, StartLoc); 1667 1668 // Parse an (optional) access specifier. 1669 AccessSpecifier Access = getAccessSpecifierIfPresent(); 1670 if (Access != AS_none) 1671 ConsumeToken(); 1672 1673 CheckMisplacedCXX11Attribute(Attributes, StartLoc); 1674 1675 // Parse the 'virtual' keyword (again!), in case it came after the 1676 // access specifier. 1677 if (Tok.is(tok::kw_virtual)) { 1678 SourceLocation VirtualLoc = ConsumeToken(); 1679 if (IsVirtual) { 1680 // Complain about duplicate 'virtual' 1681 Diag(VirtualLoc, diag::err_dup_virtual) 1682 << FixItHint::CreateRemoval(VirtualLoc); 1683 } 1684 1685 IsVirtual = true; 1686 } 1687 1688 CheckMisplacedCXX11Attribute(Attributes, StartLoc); 1689 1690 // Parse the class-name. 1691 SourceLocation EndLocation; 1692 SourceLocation BaseLoc; 1693 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation); 1694 if (BaseType.isInvalid()) 1695 return true; 1696 1697 // Parse the optional ellipsis (for a pack expansion). The ellipsis is 1698 // actually part of the base-specifier-list grammar productions, but we 1699 // parse it here for convenience. 1700 SourceLocation EllipsisLoc; 1701 if (Tok.is(tok::ellipsis)) 1702 EllipsisLoc = ConsumeToken(); 1703 1704 // Find the complete source range for the base-specifier. 1705 SourceRange Range(StartLoc, EndLocation); 1706 1707 // Notify semantic analysis that we have parsed a complete 1708 // base-specifier. 1709 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual, 1710 Access, BaseType.get(), BaseLoc, 1711 EllipsisLoc); 1712} 1713 1714/// getAccessSpecifierIfPresent - Determine whether the next token is 1715/// a C++ access-specifier. 1716/// 1717/// access-specifier: [C++ class.derived] 1718/// 'private' 1719/// 'protected' 1720/// 'public' 1721AccessSpecifier Parser::getAccessSpecifierIfPresent() const { 1722 switch (Tok.getKind()) { 1723 default: return AS_none; 1724 case tok::kw_private: return AS_private; 1725 case tok::kw_protected: return AS_protected; 1726 case tok::kw_public: return AS_public; 1727 } 1728} 1729 1730/// \brief If the given declarator has any parts for which parsing has to be 1731/// delayed, e.g., default arguments, create a late-parsed method declaration 1732/// record to handle the parsing at the end of the class definition. 1733void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, 1734 Decl *ThisDecl) { 1735 // We just declared a member function. If this member function 1736 // has any default arguments, we'll need to parse them later. 1737 LateParsedMethodDeclaration *LateMethod = 0; 1738 DeclaratorChunk::FunctionTypeInfo &FTI 1739 = DeclaratorInfo.getFunctionTypeInfo(); 1740 1741 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { 1742 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { 1743 if (!LateMethod) { 1744 // Push this method onto the stack of late-parsed method 1745 // declarations. 1746 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl); 1747 getCurrentClass().LateParsedDeclarations.push_back(LateMethod); 1748 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope(); 1749 1750 // Add all of the parameters prior to this one (they don't 1751 // have default arguments). 1752 LateMethod->DefaultArgs.reserve(FTI.NumArgs); 1753 for (unsigned I = 0; I < ParamIdx; ++I) 1754 LateMethod->DefaultArgs.push_back( 1755 LateParsedDefaultArgument(FTI.ArgInfo[I].Param)); 1756 } 1757 1758 // Add this parameter to the list of parameters (it may or may 1759 // not have a default argument). 1760 LateMethod->DefaultArgs.push_back( 1761 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param, 1762 FTI.ArgInfo[ParamIdx].DefaultArgTokens)); 1763 } 1764 } 1765} 1766 1767/// isCXX11VirtSpecifier - Determine whether the given token is a C++11 1768/// virt-specifier. 1769/// 1770/// virt-specifier: 1771/// override 1772/// final 1773VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const { 1774 if (!getLangOpts().CPlusPlus) 1775 return VirtSpecifiers::VS_None; 1776 1777 if (Tok.is(tok::identifier)) { 1778 IdentifierInfo *II = Tok.getIdentifierInfo(); 1779 1780 // Initialize the contextual keywords. 1781 if (!Ident_final) { 1782 Ident_final = &PP.getIdentifierTable().get("final"); 1783 Ident_override = &PP.getIdentifierTable().get("override"); 1784 } 1785 1786 if (II == Ident_override) 1787 return VirtSpecifiers::VS_Override; 1788 1789 if (II == Ident_final) 1790 return VirtSpecifiers::VS_Final; 1791 } 1792 1793 return VirtSpecifiers::VS_None; 1794} 1795 1796/// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq. 1797/// 1798/// virt-specifier-seq: 1799/// virt-specifier 1800/// virt-specifier-seq virt-specifier 1801void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, 1802 bool IsInterface) { 1803 while (true) { 1804 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(); 1805 if (Specifier == VirtSpecifiers::VS_None) 1806 return; 1807 1808 // C++ [class.mem]p8: 1809 // A virt-specifier-seq shall contain at most one of each virt-specifier. 1810 const char *PrevSpec = 0; 1811 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec)) 1812 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier) 1813 << PrevSpec 1814 << FixItHint::CreateRemoval(Tok.getLocation()); 1815 1816 if (IsInterface && Specifier == VirtSpecifiers::VS_Final) { 1817 Diag(Tok.getLocation(), diag::err_override_control_interface) 1818 << VirtSpecifiers::getSpecifierName(Specifier); 1819 } else { 1820 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ? 1821 diag::warn_cxx98_compat_override_control_keyword : 1822 diag::ext_override_control_keyword) 1823 << VirtSpecifiers::getSpecifierName(Specifier); 1824 } 1825 ConsumeToken(); 1826 } 1827} 1828 1829/// isCXX11FinalKeyword - Determine whether the next token is a C++11 1830/// contextual 'final' keyword. 1831bool Parser::isCXX11FinalKeyword() const { 1832 if (!getLangOpts().CPlusPlus) 1833 return false; 1834 1835 if (!Tok.is(tok::identifier)) 1836 return false; 1837 1838 // Initialize the contextual keywords. 1839 if (!Ident_final) { 1840 Ident_final = &PP.getIdentifierTable().get("final"); 1841 Ident_override = &PP.getIdentifierTable().get("override"); 1842 } 1843 1844 return Tok.getIdentifierInfo() == Ident_final; 1845} 1846 1847/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 1848/// 1849/// member-declaration: 1850/// decl-specifier-seq[opt] member-declarator-list[opt] ';' 1851/// function-definition ';'[opt] 1852/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 1853/// using-declaration [TODO] 1854/// [C++0x] static_assert-declaration 1855/// template-declaration 1856/// [GNU] '__extension__' member-declaration 1857/// 1858/// member-declarator-list: 1859/// member-declarator 1860/// member-declarator-list ',' member-declarator 1861/// 1862/// member-declarator: 1863/// declarator virt-specifier-seq[opt] pure-specifier[opt] 1864/// declarator constant-initializer[opt] 1865/// [C++11] declarator brace-or-equal-initializer[opt] 1866/// identifier[opt] ':' constant-expression 1867/// 1868/// virt-specifier-seq: 1869/// virt-specifier 1870/// virt-specifier-seq virt-specifier 1871/// 1872/// virt-specifier: 1873/// override 1874/// final 1875/// 1876/// pure-specifier: 1877/// '= 0' 1878/// 1879/// constant-initializer: 1880/// '=' constant-expression 1881/// 1882void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, 1883 AttributeList *AccessAttrs, 1884 const ParsedTemplateInfo &TemplateInfo, 1885 ParsingDeclRAIIObject *TemplateDiags) { 1886 if (Tok.is(tok::at)) { 1887 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs)) 1888 Diag(Tok, diag::err_at_defs_cxx); 1889 else 1890 Diag(Tok, diag::err_at_in_class); 1891 1892 ConsumeToken(); 1893 SkipUntil(tok::r_brace); 1894 return; 1895 } 1896 1897 // Access declarations. 1898 bool MalformedTypeSpec = false; 1899 if (!TemplateInfo.Kind && 1900 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) { 1901 if (TryAnnotateCXXScopeToken()) 1902 MalformedTypeSpec = true; 1903 1904 bool isAccessDecl; 1905 if (Tok.isNot(tok::annot_cxxscope)) 1906 isAccessDecl = false; 1907 else if (NextToken().is(tok::identifier)) 1908 isAccessDecl = GetLookAheadToken(2).is(tok::semi); 1909 else 1910 isAccessDecl = NextToken().is(tok::kw_operator); 1911 1912 if (isAccessDecl) { 1913 // Collect the scope specifier token we annotated earlier. 1914 CXXScopeSpec SS; 1915 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 1916 /*EnteringContext=*/false); 1917 1918 // Try to parse an unqualified-id. 1919 SourceLocation TemplateKWLoc; 1920 UnqualifiedId Name; 1921 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), 1922 TemplateKWLoc, Name)) { 1923 SkipUntil(tok::semi); 1924 return; 1925 } 1926 1927 // TODO: recover from mistakenly-qualified operator declarations. 1928 if (ExpectAndConsume(tok::semi, 1929 diag::err_expected_semi_after, 1930 "access declaration", 1931 tok::semi)) 1932 return; 1933 1934 Actions.ActOnUsingDeclaration(getCurScope(), AS, 1935 false, SourceLocation(), 1936 SS, Name, 1937 /* AttrList */ 0, 1938 /* IsTypeName */ false, 1939 SourceLocation()); 1940 return; 1941 } 1942 } 1943 1944 // static_assert-declaration 1945 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) { 1946 // FIXME: Check for templates 1947 SourceLocation DeclEnd; 1948 ParseStaticAssertDeclaration(DeclEnd); 1949 return; 1950 } 1951 1952 if (Tok.is(tok::kw_template)) { 1953 assert(!TemplateInfo.TemplateParams && 1954 "Nested template improperly parsed?"); 1955 SourceLocation DeclEnd; 1956 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, 1957 AS, AccessAttrs); 1958 return; 1959 } 1960 1961 // Handle: member-declaration ::= '__extension__' member-declaration 1962 if (Tok.is(tok::kw___extension__)) { 1963 // __extension__ silences extension warnings in the subexpression. 1964 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1965 ConsumeToken(); 1966 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, 1967 TemplateInfo, TemplateDiags); 1968 } 1969 1970 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it 1971 // is a bitfield. 1972 ColonProtectionRAIIObject X(*this); 1973 1974 ParsedAttributesWithRange attrs(AttrFactory); 1975 ParsedAttributesWithRange FnAttrs(AttrFactory); 1976 // Optional C++11 attribute-specifier 1977 MaybeParseCXX11Attributes(attrs); 1978 // We need to keep these attributes for future diagnostic 1979 // before they are taken over by declaration specifier. 1980 FnAttrs.addAll(attrs.getList()); 1981 FnAttrs.Range = attrs.Range; 1982 1983 MaybeParseMicrosoftAttributes(attrs); 1984 1985 if (Tok.is(tok::kw_using)) { 1986 ProhibitAttributes(attrs); 1987 1988 // Eat 'using'. 1989 SourceLocation UsingLoc = ConsumeToken(); 1990 1991 if (Tok.is(tok::kw_namespace)) { 1992 Diag(UsingLoc, diag::err_using_namespace_in_class); 1993 SkipUntil(tok::semi, true, true); 1994 } else { 1995 SourceLocation DeclEnd; 1996 // Otherwise, it must be a using-declaration or an alias-declaration. 1997 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo, 1998 UsingLoc, DeclEnd, AS); 1999 } 2000 return; 2001 } 2002 2003 // Hold late-parsed attributes so we can attach a Decl to them later. 2004 LateParsedAttrList CommonLateParsedAttrs; 2005 2006 // decl-specifier-seq: 2007 // Parse the common declaration-specifiers piece. 2008 ParsingDeclSpec DS(*this, TemplateDiags); 2009 DS.takeAttributesFrom(attrs); 2010 if (MalformedTypeSpec) 2011 DS.SetTypeSpecError(); 2012 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class, 2013 &CommonLateParsedAttrs); 2014 2015 MultiTemplateParamsArg TemplateParams( 2016 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0, 2017 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0); 2018 2019 if (Tok.is(tok::semi)) { 2020 ConsumeToken(); 2021 2022 if (DS.isFriendSpecified()) 2023 ProhibitAttributes(FnAttrs); 2024 2025 Decl *TheDecl = 2026 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams); 2027 DS.complete(TheDecl); 2028 return; 2029 } 2030 2031 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext); 2032 VirtSpecifiers VS; 2033 2034 // Hold late-parsed attributes so we can attach a Decl to them later. 2035 LateParsedAttrList LateParsedAttrs; 2036 2037 SourceLocation EqualLoc; 2038 bool HasInitializer = false; 2039 ExprResult Init; 2040 if (Tok.isNot(tok::colon)) { 2041 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 2042 ColonProtectionRAIIObject X(*this); 2043 2044 // Parse the first declarator. 2045 ParseDeclarator(DeclaratorInfo); 2046 // Error parsing the declarator? 2047 if (!DeclaratorInfo.hasName()) { 2048 // If so, skip until the semi-colon or a }. 2049 SkipUntil(tok::r_brace, true, true); 2050 if (Tok.is(tok::semi)) 2051 ConsumeToken(); 2052 return; 2053 } 2054 2055 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface); 2056 2057 // If attributes exist after the declarator, but before an '{', parse them. 2058 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); 2059 2060 // MSVC permits pure specifier on inline functions declared at class scope. 2061 // Hence check for =0 before checking for function definition. 2062 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) && 2063 DeclaratorInfo.isFunctionDeclarator() && 2064 NextToken().is(tok::numeric_constant)) { 2065 EqualLoc = ConsumeToken(); 2066 Init = ParseInitializer(); 2067 if (Init.isInvalid()) 2068 SkipUntil(tok::comma, true, true); 2069 else 2070 HasInitializer = true; 2071 } 2072 2073 FunctionDefinitionKind DefinitionKind = FDK_Declaration; 2074 // function-definition: 2075 // 2076 // In C++11, a non-function declarator followed by an open brace is a 2077 // braced-init-list for an in-class member initialization, not an 2078 // erroneous function definition. 2079 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) { 2080 DefinitionKind = FDK_Definition; 2081 } else if (DeclaratorInfo.isFunctionDeclarator()) { 2082 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) { 2083 DefinitionKind = FDK_Definition; 2084 } else if (Tok.is(tok::equal)) { 2085 const Token &KW = NextToken(); 2086 if (KW.is(tok::kw_default)) 2087 DefinitionKind = FDK_Defaulted; 2088 else if (KW.is(tok::kw_delete)) 2089 DefinitionKind = FDK_Deleted; 2090 } 2091 } 2092 2093 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains 2094 // to a friend declaration, that declaration shall be a definition. 2095 if (DeclaratorInfo.isFunctionDeclarator() && 2096 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) { 2097 // Diagnose attributes that appear before decl specifier: 2098 // [[]] friend int foo(); 2099 ProhibitAttributes(FnAttrs); 2100 } 2101 2102 if (DefinitionKind) { 2103 if (!DeclaratorInfo.isFunctionDeclarator()) { 2104 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params); 2105 ConsumeBrace(); 2106 SkipUntil(tok::r_brace, /*StopAtSemi*/false); 2107 2108 // Consume the optional ';' 2109 if (Tok.is(tok::semi)) 2110 ConsumeToken(); 2111 return; 2112 } 2113 2114 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 2115 Diag(DeclaratorInfo.getIdentifierLoc(), 2116 diag::err_function_declared_typedef); 2117 2118 // Recover by treating the 'typedef' as spurious. 2119 DS.ClearStorageClassSpecs(); 2120 } 2121 2122 Decl *FunDecl = 2123 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo, 2124 VS, DefinitionKind, Init); 2125 2126 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) { 2127 CommonLateParsedAttrs[i]->addDecl(FunDecl); 2128 } 2129 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) { 2130 LateParsedAttrs[i]->addDecl(FunDecl); 2131 } 2132 LateParsedAttrs.clear(); 2133 2134 // Consume the ';' - it's optional unless we have a delete or default 2135 if (Tok.is(tok::semi)) 2136 ConsumeExtraSemi(AfterMemberFunctionDefinition); 2137 2138 return; 2139 } 2140 } 2141 2142 // member-declarator-list: 2143 // member-declarator 2144 // member-declarator-list ',' member-declarator 2145 2146 SmallVector<Decl *, 8> DeclsInGroup; 2147 ExprResult BitfieldSize; 2148 bool ExpectSemi = true; 2149 2150 while (1) { 2151 // member-declarator: 2152 // declarator pure-specifier[opt] 2153 // declarator brace-or-equal-initializer[opt] 2154 // identifier[opt] ':' constant-expression 2155 if (Tok.is(tok::colon)) { 2156 ConsumeToken(); 2157 BitfieldSize = ParseConstantExpression(); 2158 if (BitfieldSize.isInvalid()) 2159 SkipUntil(tok::comma, true, true); 2160 } 2161 2162 // If a simple-asm-expr is present, parse it. 2163 if (Tok.is(tok::kw_asm)) { 2164 SourceLocation Loc; 2165 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 2166 if (AsmLabel.isInvalid()) 2167 SkipUntil(tok::comma, true, true); 2168 2169 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 2170 DeclaratorInfo.SetRangeEnd(Loc); 2171 } 2172 2173 // If attributes exist after the declarator, parse them. 2174 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); 2175 2176 // FIXME: When g++ adds support for this, we'll need to check whether it 2177 // goes before or after the GNU attributes and __asm__. 2178 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface); 2179 2180 InClassInitStyle HasInClassInit = ICIS_NoInit; 2181 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) { 2182 if (BitfieldSize.get()) { 2183 Diag(Tok, diag::err_bitfield_member_init); 2184 SkipUntil(tok::comma, true, true); 2185 } else { 2186 HasInitializer = true; 2187 if (!DeclaratorInfo.isDeclarationOfFunction() && 2188 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 2189 != DeclSpec::SCS_typedef) 2190 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit; 2191 } 2192 } 2193 2194 // NOTE: If Sema is the Action module and declarator is an instance field, 2195 // this call will *not* return the created decl; It will return null. 2196 // See Sema::ActOnCXXMemberDeclarator for details. 2197 2198 NamedDecl *ThisDecl = 0; 2199 if (DS.isFriendSpecified()) { 2200 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains 2201 // to a friend declaration, that declaration shall be a definition. 2202 // 2203 // Diagnose attributes appear after friend member function declarator: 2204 // foo [[]] (); 2205 SmallVector<SourceRange, 4> Ranges; 2206 DeclaratorInfo.getCXX11AttributeRanges(Ranges); 2207 if (!Ranges.empty()) { 2208 for (SmallVector<SourceRange, 4>::iterator I = Ranges.begin(), 2209 E = Ranges.end(); I != E; ++I) { 2210 Diag((*I).getBegin(), diag::err_attributes_not_allowed) 2211 << *I; 2212 } 2213 } 2214 2215 // TODO: handle initializers, bitfields, 'delete' 2216 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, 2217 TemplateParams); 2218 } else { 2219 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, 2220 DeclaratorInfo, 2221 TemplateParams, 2222 BitfieldSize.release(), 2223 VS, HasInClassInit); 2224 if (AccessAttrs) 2225 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs, 2226 false, true); 2227 } 2228 2229 // Set the Decl for any late parsed attributes 2230 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) { 2231 CommonLateParsedAttrs[i]->addDecl(ThisDecl); 2232 } 2233 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) { 2234 LateParsedAttrs[i]->addDecl(ThisDecl); 2235 } 2236 LateParsedAttrs.clear(); 2237 2238 // Handle the initializer. 2239 if (HasInClassInit != ICIS_NoInit && 2240 DeclaratorInfo.getDeclSpec().getStorageClassSpec() != 2241 DeclSpec::SCS_static) { 2242 // The initializer was deferred; parse it and cache the tokens. 2243 Diag(Tok, getLangOpts().CPlusPlus11 ? 2244 diag::warn_cxx98_compat_nonstatic_member_init : 2245 diag::ext_nonstatic_member_init); 2246 2247 if (DeclaratorInfo.isArrayOfUnknownBound()) { 2248 // C++11 [dcl.array]p3: An array bound may also be omitted when the 2249 // declarator is followed by an initializer. 2250 // 2251 // A brace-or-equal-initializer for a member-declarator is not an 2252 // initializer in the grammar, so this is ill-formed. 2253 Diag(Tok, diag::err_incomplete_array_member_init); 2254 SkipUntil(tok::comma, true, true); 2255 if (ThisDecl) 2256 // Avoid later warnings about a class member of incomplete type. 2257 ThisDecl->setInvalidDecl(); 2258 } else 2259 ParseCXXNonStaticMemberInitializer(ThisDecl); 2260 } else if (HasInitializer) { 2261 // Normal initializer. 2262 if (!Init.isUsable()) 2263 Init = ParseCXXMemberInitializer(ThisDecl, 2264 DeclaratorInfo.isDeclarationOfFunction(), EqualLoc); 2265 2266 if (Init.isInvalid()) 2267 SkipUntil(tok::comma, true, true); 2268 else if (ThisDecl) 2269 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(), 2270 DS.getTypeSpecType() == DeclSpec::TST_auto); 2271 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) { 2272 // No initializer. 2273 Actions.ActOnUninitializedDecl(ThisDecl, 2274 DS.getTypeSpecType() == DeclSpec::TST_auto); 2275 } 2276 2277 if (ThisDecl) { 2278 Actions.FinalizeDeclaration(ThisDecl); 2279 DeclsInGroup.push_back(ThisDecl); 2280 } 2281 2282 if (ThisDecl && DeclaratorInfo.isFunctionDeclarator() && 2283 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 2284 != DeclSpec::SCS_typedef) { 2285 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl); 2286 } 2287 2288 DeclaratorInfo.complete(ThisDecl); 2289 2290 // If we don't have a comma, it is either the end of the list (a ';') 2291 // or an error, bail out. 2292 if (Tok.isNot(tok::comma)) 2293 break; 2294 2295 // Consume the comma. 2296 SourceLocation CommaLoc = ConsumeToken(); 2297 2298 if (Tok.isAtStartOfLine() && 2299 !MightBeDeclarator(Declarator::MemberContext)) { 2300 // This comma was followed by a line-break and something which can't be 2301 // the start of a declarator. The comma was probably a typo for a 2302 // semicolon. 2303 Diag(CommaLoc, diag::err_expected_semi_declaration) 2304 << FixItHint::CreateReplacement(CommaLoc, ";"); 2305 ExpectSemi = false; 2306 break; 2307 } 2308 2309 // Parse the next declarator. 2310 DeclaratorInfo.clear(); 2311 VS.clear(); 2312 BitfieldSize = true; 2313 Init = true; 2314 HasInitializer = false; 2315 DeclaratorInfo.setCommaLoc(CommaLoc); 2316 2317 // Attributes are only allowed on the second declarator. 2318 MaybeParseGNUAttributes(DeclaratorInfo); 2319 2320 if (Tok.isNot(tok::colon)) 2321 ParseDeclarator(DeclaratorInfo); 2322 } 2323 2324 if (ExpectSemi && 2325 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { 2326 // Skip to end of block or statement. 2327 SkipUntil(tok::r_brace, true, true); 2328 // If we stopped at a ';', eat it. 2329 if (Tok.is(tok::semi)) ConsumeToken(); 2330 return; 2331 } 2332 2333 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(), 2334 DeclsInGroup.size()); 2335} 2336 2337/// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or 2338/// pure-specifier. Also detect and reject any attempted defaulted/deleted 2339/// function definition. The location of the '=', if any, will be placed in 2340/// EqualLoc. 2341/// 2342/// pure-specifier: 2343/// '= 0' 2344/// 2345/// brace-or-equal-initializer: 2346/// '=' initializer-expression 2347/// braced-init-list 2348/// 2349/// initializer-clause: 2350/// assignment-expression 2351/// braced-init-list 2352/// 2353/// defaulted/deleted function-definition: 2354/// '=' 'default' 2355/// '=' 'delete' 2356/// 2357/// Prior to C++0x, the assignment-expression in an initializer-clause must 2358/// be a constant-expression. 2359ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction, 2360 SourceLocation &EqualLoc) { 2361 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace)) 2362 && "Data member initializer not starting with '=' or '{'"); 2363 2364 EnterExpressionEvaluationContext Context(Actions, 2365 Sema::PotentiallyEvaluated, 2366 D); 2367 if (Tok.is(tok::equal)) { 2368 EqualLoc = ConsumeToken(); 2369 if (Tok.is(tok::kw_delete)) { 2370 // In principle, an initializer of '= delete p;' is legal, but it will 2371 // never type-check. It's better to diagnose it as an ill-formed expression 2372 // than as an ill-formed deleted non-function member. 2373 // An initializer of '= delete p, foo' will never be parsed, because 2374 // a top-level comma always ends the initializer expression. 2375 const Token &Next = NextToken(); 2376 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) || 2377 Next.is(tok::eof)) { 2378 if (IsFunction) 2379 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 2380 << 1 /* delete */; 2381 else 2382 Diag(ConsumeToken(), diag::err_deleted_non_function); 2383 return ExprResult(); 2384 } 2385 } else if (Tok.is(tok::kw_default)) { 2386 if (IsFunction) 2387 Diag(Tok, diag::err_default_delete_in_multiple_declaration) 2388 << 0 /* default */; 2389 else 2390 Diag(ConsumeToken(), diag::err_default_special_members); 2391 return ExprResult(); 2392 } 2393 2394 } 2395 return ParseInitializer(); 2396} 2397 2398/// ParseCXXMemberSpecification - Parse the class definition. 2399/// 2400/// member-specification: 2401/// member-declaration member-specification[opt] 2402/// access-specifier ':' member-specification[opt] 2403/// 2404void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 2405 SourceLocation AttrFixitLoc, 2406 ParsedAttributesWithRange &Attrs, 2407 unsigned TagType, Decl *TagDecl) { 2408 assert((TagType == DeclSpec::TST_struct || 2409 TagType == DeclSpec::TST_interface || 2410 TagType == DeclSpec::TST_union || 2411 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 2412 2413 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 2414 "parsing struct/union/class body"); 2415 2416 // Determine whether this is a non-nested class. Note that local 2417 // classes are *not* considered to be nested classes. 2418 bool NonNestedClass = true; 2419 if (!ClassStack.empty()) { 2420 for (const Scope *S = getCurScope(); S; S = S->getParent()) { 2421 if (S->isClassScope()) { 2422 // We're inside a class scope, so this is a nested class. 2423 NonNestedClass = false; 2424 2425 // The Microsoft extension __interface does not permit nested classes. 2426 if (getCurrentClass().IsInterface) { 2427 Diag(RecordLoc, diag::err_invalid_member_in_interface) 2428 << /*ErrorType=*/6 2429 << (isa<NamedDecl>(TagDecl) 2430 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString() 2431 : "<anonymous>"); 2432 } 2433 break; 2434 } 2435 2436 if ((S->getFlags() & Scope::FnScope)) { 2437 // If we're in a function or function template declared in the 2438 // body of a class, then this is a local class rather than a 2439 // nested class. 2440 const Scope *Parent = S->getParent(); 2441 if (Parent->isTemplateParamScope()) 2442 Parent = Parent->getParent(); 2443 if (Parent->isClassScope()) 2444 break; 2445 } 2446 } 2447 } 2448 2449 // Enter a scope for the class. 2450 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 2451 2452 // Note that we are parsing a new (potentially-nested) class definition. 2453 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass, 2454 TagType == DeclSpec::TST_interface); 2455 2456 if (TagDecl) 2457 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 2458 2459 SourceLocation FinalLoc; 2460 2461 // Parse the optional 'final' keyword. 2462 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { 2463 assert(isCXX11FinalKeyword() && "not a class definition"); 2464 FinalLoc = ConsumeToken(); 2465 2466 if (TagType == DeclSpec::TST_interface) { 2467 Diag(FinalLoc, diag::err_override_control_interface) 2468 << "final"; 2469 } else { 2470 Diag(FinalLoc, getLangOpts().CPlusPlus11 ? 2471 diag::warn_cxx98_compat_override_control_keyword : 2472 diag::ext_override_control_keyword) << "final"; 2473 } 2474 2475 // Parse any C++11 attributes after 'final' keyword. 2476 // These attributes are not allowed to appear here, 2477 // and the only possible place for them to appertain 2478 // to the class would be between class-key and class-name. 2479 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc); 2480 } 2481 2482 if (Tok.is(tok::colon)) { 2483 ParseBaseClause(TagDecl); 2484 2485 if (!Tok.is(tok::l_brace)) { 2486 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers); 2487 2488 if (TagDecl) 2489 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 2490 return; 2491 } 2492 } 2493 2494 assert(Tok.is(tok::l_brace)); 2495 BalancedDelimiterTracker T(*this, tok::l_brace); 2496 T.consumeOpen(); 2497 2498 if (TagDecl) 2499 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc, 2500 T.getOpenLocation()); 2501 2502 // C++ 11p3: Members of a class defined with the keyword class are private 2503 // by default. Members of a class defined with the keywords struct or union 2504 // are public by default. 2505 AccessSpecifier CurAS; 2506 if (TagType == DeclSpec::TST_class) 2507 CurAS = AS_private; 2508 else 2509 CurAS = AS_public; 2510 ParsedAttributes AccessAttrs(AttrFactory); 2511 2512 if (TagDecl) { 2513 // While we still have something to read, read the member-declarations. 2514 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 2515 // Each iteration of this loop reads one member-declaration. 2516 2517 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) || 2518 Tok.is(tok::kw___if_not_exists))) { 2519 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS); 2520 continue; 2521 } 2522 2523 // Check for extraneous top-level semicolon. 2524 if (Tok.is(tok::semi)) { 2525 ConsumeExtraSemi(InsideStruct, TagType); 2526 continue; 2527 } 2528 2529 if (Tok.is(tok::annot_pragma_vis)) { 2530 HandlePragmaVisibility(); 2531 continue; 2532 } 2533 2534 if (Tok.is(tok::annot_pragma_pack)) { 2535 HandlePragmaPack(); 2536 continue; 2537 } 2538 2539 if (Tok.is(tok::annot_pragma_align)) { 2540 HandlePragmaAlign(); 2541 continue; 2542 } 2543 2544 if (Tok.is(tok::annot_pragma_openmp)) { 2545 ParseOpenMPDeclarativeDirective(); 2546 continue; 2547 } 2548 2549 AccessSpecifier AS = getAccessSpecifierIfPresent(); 2550 if (AS != AS_none) { 2551 // Current token is a C++ access specifier. 2552 CurAS = AS; 2553 SourceLocation ASLoc = Tok.getLocation(); 2554 unsigned TokLength = Tok.getLength(); 2555 ConsumeToken(); 2556 AccessAttrs.clear(); 2557 MaybeParseGNUAttributes(AccessAttrs); 2558 2559 SourceLocation EndLoc; 2560 if (Tok.is(tok::colon)) { 2561 EndLoc = Tok.getLocation(); 2562 ConsumeToken(); 2563 } else if (Tok.is(tok::semi)) { 2564 EndLoc = Tok.getLocation(); 2565 ConsumeToken(); 2566 Diag(EndLoc, diag::err_expected_colon) 2567 << FixItHint::CreateReplacement(EndLoc, ":"); 2568 } else { 2569 EndLoc = ASLoc.getLocWithOffset(TokLength); 2570 Diag(EndLoc, diag::err_expected_colon) 2571 << FixItHint::CreateInsertion(EndLoc, ":"); 2572 } 2573 2574 // The Microsoft extension __interface does not permit non-public 2575 // access specifiers. 2576 if (TagType == DeclSpec::TST_interface && CurAS != AS_public) { 2577 Diag(ASLoc, diag::err_access_specifier_interface) 2578 << (CurAS == AS_protected); 2579 } 2580 2581 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc, 2582 AccessAttrs.getList())) { 2583 // found another attribute than only annotations 2584 AccessAttrs.clear(); 2585 } 2586 2587 continue; 2588 } 2589 2590 // FIXME: Make sure we don't have a template here. 2591 2592 // Parse all the comma separated declarators. 2593 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList()); 2594 } 2595 2596 T.consumeClose(); 2597 } else { 2598 SkipUntil(tok::r_brace, false, false); 2599 } 2600 2601 // If attributes exist after class contents, parse them. 2602 ParsedAttributes attrs(AttrFactory); 2603 MaybeParseGNUAttributes(attrs); 2604 2605 if (TagDecl) 2606 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, 2607 T.getOpenLocation(), 2608 T.getCloseLocation(), 2609 attrs.getList()); 2610 2611 // C++11 [class.mem]p2: 2612 // Within the class member-specification, the class is regarded as complete 2613 // within function bodies, default arguments, and 2614 // brace-or-equal-initializers for non-static data members (including such 2615 // things in nested classes). 2616 if (TagDecl && NonNestedClass) { 2617 // We are not inside a nested class. This class and its nested classes 2618 // are complete and we can parse the delayed portions of method 2619 // declarations and the lexed inline method definitions, along with any 2620 // delayed attributes. 2621 SourceLocation SavedPrevTokLocation = PrevTokLocation; 2622 ParseLexedAttributes(getCurrentClass()); 2623 ParseLexedMethodDeclarations(getCurrentClass()); 2624 2625 // We've finished with all pending member declarations. 2626 Actions.ActOnFinishCXXMemberDecls(); 2627 2628 ParseLexedMemberInitializers(getCurrentClass()); 2629 ParseLexedMethodDefs(getCurrentClass()); 2630 PrevTokLocation = SavedPrevTokLocation; 2631 } 2632 2633 if (TagDecl) 2634 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 2635 T.getCloseLocation()); 2636 2637 // Leave the class scope. 2638 ParsingDef.Pop(); 2639 ClassScope.Exit(); 2640} 2641 2642/// ParseConstructorInitializer - Parse a C++ constructor initializer, 2643/// which explicitly initializes the members or base classes of a 2644/// class (C++ [class.base.init]). For example, the three initializers 2645/// after the ':' in the Derived constructor below: 2646/// 2647/// @code 2648/// class Base { }; 2649/// class Derived : Base { 2650/// int x; 2651/// float f; 2652/// public: 2653/// Derived(float f) : Base(), x(17), f(f) { } 2654/// }; 2655/// @endcode 2656/// 2657/// [C++] ctor-initializer: 2658/// ':' mem-initializer-list 2659/// 2660/// [C++] mem-initializer-list: 2661/// mem-initializer ...[opt] 2662/// mem-initializer ...[opt] , mem-initializer-list 2663void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) { 2664 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 2665 2666 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers 2667 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 2668 SourceLocation ColonLoc = ConsumeToken(); 2669 2670 SmallVector<CXXCtorInitializer*, 4> MemInitializers; 2671 bool AnyErrors = false; 2672 2673 do { 2674 if (Tok.is(tok::code_completion)) { 2675 Actions.CodeCompleteConstructorInitializer(ConstructorDecl, 2676 MemInitializers.data(), 2677 MemInitializers.size()); 2678 return cutOffParsing(); 2679 } else { 2680 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 2681 if (!MemInit.isInvalid()) 2682 MemInitializers.push_back(MemInit.get()); 2683 else 2684 AnyErrors = true; 2685 } 2686 2687 if (Tok.is(tok::comma)) 2688 ConsumeToken(); 2689 else if (Tok.is(tok::l_brace)) 2690 break; 2691 // If the next token looks like a base or member initializer, assume that 2692 // we're just missing a comma. 2693 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) { 2694 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 2695 Diag(Loc, diag::err_ctor_init_missing_comma) 2696 << FixItHint::CreateInsertion(Loc, ", "); 2697 } else { 2698 // Skip over garbage, until we get to '{'. Don't eat the '{'. 2699 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 2700 SkipUntil(tok::l_brace, true, true); 2701 break; 2702 } 2703 } while (true); 2704 2705 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers, 2706 AnyErrors); 2707} 2708 2709/// ParseMemInitializer - Parse a C++ member initializer, which is 2710/// part of a constructor initializer that explicitly initializes one 2711/// member or base class (C++ [class.base.init]). See 2712/// ParseConstructorInitializer for an example. 2713/// 2714/// [C++] mem-initializer: 2715/// mem-initializer-id '(' expression-list[opt] ')' 2716/// [C++0x] mem-initializer-id braced-init-list 2717/// 2718/// [C++] mem-initializer-id: 2719/// '::'[opt] nested-name-specifier[opt] class-name 2720/// identifier 2721Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { 2722 // parse '::'[opt] nested-name-specifier[opt] 2723 CXXScopeSpec SS; 2724 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 2725 ParsedType TemplateTypeTy; 2726 if (Tok.is(tok::annot_template_id)) { 2727 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2728 if (TemplateId->Kind == TNK_Type_template || 2729 TemplateId->Kind == TNK_Dependent_template_name) { 2730 AnnotateTemplateIdTokenAsType(); 2731 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 2732 TemplateTypeTy = getTypeAnnotation(Tok); 2733 } 2734 } 2735 // Uses of decltype will already have been converted to annot_decltype by 2736 // ParseOptionalCXXScopeSpecifier at this point. 2737 if (!TemplateTypeTy && Tok.isNot(tok::identifier) 2738 && Tok.isNot(tok::annot_decltype)) { 2739 Diag(Tok, diag::err_expected_member_or_base_name); 2740 return true; 2741 } 2742 2743 IdentifierInfo *II = 0; 2744 DeclSpec DS(AttrFactory); 2745 SourceLocation IdLoc = Tok.getLocation(); 2746 if (Tok.is(tok::annot_decltype)) { 2747 // Get the decltype expression, if there is one. 2748 ParseDecltypeSpecifier(DS); 2749 } else { 2750 if (Tok.is(tok::identifier)) 2751 // Get the identifier. This may be a member name or a class name, 2752 // but we'll let the semantic analysis determine which it is. 2753 II = Tok.getIdentifierInfo(); 2754 ConsumeToken(); 2755 } 2756 2757 2758 // Parse the '('. 2759 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 2760 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 2761 2762 ExprResult InitList = ParseBraceInitializer(); 2763 if (InitList.isInvalid()) 2764 return true; 2765 2766 SourceLocation EllipsisLoc; 2767 if (Tok.is(tok::ellipsis)) 2768 EllipsisLoc = ConsumeToken(); 2769 2770 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 2771 TemplateTypeTy, DS, IdLoc, 2772 InitList.take(), EllipsisLoc); 2773 } else if(Tok.is(tok::l_paren)) { 2774 BalancedDelimiterTracker T(*this, tok::l_paren); 2775 T.consumeOpen(); 2776 2777 // Parse the optional expression-list. 2778 ExprVector ArgExprs; 2779 CommaLocsTy CommaLocs; 2780 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 2781 SkipUntil(tok::r_paren); 2782 return true; 2783 } 2784 2785 T.consumeClose(); 2786 2787 SourceLocation EllipsisLoc; 2788 if (Tok.is(tok::ellipsis)) 2789 EllipsisLoc = ConsumeToken(); 2790 2791 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 2792 TemplateTypeTy, DS, IdLoc, 2793 T.getOpenLocation(), ArgExprs.data(), 2794 ArgExprs.size(), T.getCloseLocation(), 2795 EllipsisLoc); 2796 } 2797 2798 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::err_expected_lparen_or_lbrace 2799 : diag::err_expected_lparen); 2800 return true; 2801} 2802 2803/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]). 2804/// 2805/// exception-specification: 2806/// dynamic-exception-specification 2807/// noexcept-specification 2808/// 2809/// noexcept-specification: 2810/// 'noexcept' 2811/// 'noexcept' '(' constant-expression ')' 2812ExceptionSpecificationType 2813Parser::tryParseExceptionSpecification( 2814 SourceRange &SpecificationRange, 2815 SmallVectorImpl<ParsedType> &DynamicExceptions, 2816 SmallVectorImpl<SourceRange> &DynamicExceptionRanges, 2817 ExprResult &NoexceptExpr) { 2818 ExceptionSpecificationType Result = EST_None; 2819 2820 // See if there's a dynamic specification. 2821 if (Tok.is(tok::kw_throw)) { 2822 Result = ParseDynamicExceptionSpecification(SpecificationRange, 2823 DynamicExceptions, 2824 DynamicExceptionRanges); 2825 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() && 2826 "Produced different number of exception types and ranges."); 2827 } 2828 2829 // If there's no noexcept specification, we're done. 2830 if (Tok.isNot(tok::kw_noexcept)) 2831 return Result; 2832 2833 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl); 2834 2835 // If we already had a dynamic specification, parse the noexcept for, 2836 // recovery, but emit a diagnostic and don't store the results. 2837 SourceRange NoexceptRange; 2838 ExceptionSpecificationType NoexceptType = EST_None; 2839 2840 SourceLocation KeywordLoc = ConsumeToken(); 2841 if (Tok.is(tok::l_paren)) { 2842 // There is an argument. 2843 BalancedDelimiterTracker T(*this, tok::l_paren); 2844 T.consumeOpen(); 2845 NoexceptType = EST_ComputedNoexcept; 2846 NoexceptExpr = ParseConstantExpression(); 2847 // The argument must be contextually convertible to bool. We use 2848 // ActOnBooleanCondition for this purpose. 2849 if (!NoexceptExpr.isInvalid()) 2850 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc, 2851 NoexceptExpr.get()); 2852 T.consumeClose(); 2853 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation()); 2854 } else { 2855 // There is no argument. 2856 NoexceptType = EST_BasicNoexcept; 2857 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc); 2858 } 2859 2860 if (Result == EST_None) { 2861 SpecificationRange = NoexceptRange; 2862 Result = NoexceptType; 2863 2864 // If there's a dynamic specification after a noexcept specification, 2865 // parse that and ignore the results. 2866 if (Tok.is(tok::kw_throw)) { 2867 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 2868 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions, 2869 DynamicExceptionRanges); 2870 } 2871 } else { 2872 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 2873 } 2874 2875 return Result; 2876} 2877 2878/// ParseDynamicExceptionSpecification - Parse a C++ 2879/// dynamic-exception-specification (C++ [except.spec]). 2880/// 2881/// dynamic-exception-specification: 2882/// 'throw' '(' type-id-list [opt] ')' 2883/// [MS] 'throw' '(' '...' ')' 2884/// 2885/// type-id-list: 2886/// type-id ... [opt] 2887/// type-id-list ',' type-id ... [opt] 2888/// 2889ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification( 2890 SourceRange &SpecificationRange, 2891 SmallVectorImpl<ParsedType> &Exceptions, 2892 SmallVectorImpl<SourceRange> &Ranges) { 2893 assert(Tok.is(tok::kw_throw) && "expected throw"); 2894 2895 SpecificationRange.setBegin(ConsumeToken()); 2896 BalancedDelimiterTracker T(*this, tok::l_paren); 2897 if (T.consumeOpen()) { 2898 Diag(Tok, diag::err_expected_lparen_after) << "throw"; 2899 SpecificationRange.setEnd(SpecificationRange.getBegin()); 2900 return EST_DynamicNone; 2901 } 2902 2903 // Parse throw(...), a Microsoft extension that means "this function 2904 // can throw anything". 2905 if (Tok.is(tok::ellipsis)) { 2906 SourceLocation EllipsisLoc = ConsumeToken(); 2907 if (!getLangOpts().MicrosoftExt) 2908 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 2909 T.consumeClose(); 2910 SpecificationRange.setEnd(T.getCloseLocation()); 2911 return EST_MSAny; 2912 } 2913 2914 // Parse the sequence of type-ids. 2915 SourceRange Range; 2916 while (Tok.isNot(tok::r_paren)) { 2917 TypeResult Res(ParseTypeName(&Range)); 2918 2919 if (Tok.is(tok::ellipsis)) { 2920 // C++0x [temp.variadic]p5: 2921 // - In a dynamic-exception-specification (15.4); the pattern is a 2922 // type-id. 2923 SourceLocation Ellipsis = ConsumeToken(); 2924 Range.setEnd(Ellipsis); 2925 if (!Res.isInvalid()) 2926 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis); 2927 } 2928 2929 if (!Res.isInvalid()) { 2930 Exceptions.push_back(Res.get()); 2931 Ranges.push_back(Range); 2932 } 2933 2934 if (Tok.is(tok::comma)) 2935 ConsumeToken(); 2936 else 2937 break; 2938 } 2939 2940 T.consumeClose(); 2941 SpecificationRange.setEnd(T.getCloseLocation()); 2942 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic; 2943} 2944 2945/// ParseTrailingReturnType - Parse a trailing return type on a new-style 2946/// function declaration. 2947TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) { 2948 assert(Tok.is(tok::arrow) && "expected arrow"); 2949 2950 ConsumeToken(); 2951 2952 return ParseTypeName(&Range, Declarator::TrailingReturnContext); 2953} 2954 2955/// \brief We have just started parsing the definition of a new class, 2956/// so push that class onto our stack of classes that is currently 2957/// being parsed. 2958Sema::ParsingClassState 2959Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass, 2960 bool IsInterface) { 2961 assert((NonNestedClass || !ClassStack.empty()) && 2962 "Nested class without outer class"); 2963 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface)); 2964 return Actions.PushParsingClass(); 2965} 2966 2967/// \brief Deallocate the given parsed class and all of its nested 2968/// classes. 2969void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 2970 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I) 2971 delete Class->LateParsedDeclarations[I]; 2972 delete Class; 2973} 2974 2975/// \brief Pop the top class of the stack of classes that are 2976/// currently being parsed. 2977/// 2978/// This routine should be called when we have finished parsing the 2979/// definition of a class, but have not yet popped the Scope 2980/// associated with the class's definition. 2981void Parser::PopParsingClass(Sema::ParsingClassState state) { 2982 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 2983 2984 Actions.PopParsingClass(state); 2985 2986 ParsingClass *Victim = ClassStack.top(); 2987 ClassStack.pop(); 2988 if (Victim->TopLevelClass) { 2989 // Deallocate all of the nested classes of this class, 2990 // recursively: we don't need to keep any of this information. 2991 DeallocateParsedClasses(Victim); 2992 return; 2993 } 2994 assert(!ClassStack.empty() && "Missing top-level class?"); 2995 2996 if (Victim->LateParsedDeclarations.empty()) { 2997 // The victim is a nested class, but we will not need to perform 2998 // any processing after the definition of this class since it has 2999 // no members whose handling was delayed. Therefore, we can just 3000 // remove this nested class. 3001 DeallocateParsedClasses(Victim); 3002 return; 3003 } 3004 3005 // This nested class has some members that will need to be processed 3006 // after the top-level class is completely defined. Therefore, add 3007 // it to the list of nested classes within its parent. 3008 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?"); 3009 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim)); 3010 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope(); 3011} 3012 3013/// \brief Try to parse an 'identifier' which appears within an attribute-token. 3014/// 3015/// \return the parsed identifier on success, and 0 if the next token is not an 3016/// attribute-token. 3017/// 3018/// C++11 [dcl.attr.grammar]p3: 3019/// If a keyword or an alternative token that satisfies the syntactic 3020/// requirements of an identifier is contained in an attribute-token, 3021/// it is considered an identifier. 3022IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) { 3023 switch (Tok.getKind()) { 3024 default: 3025 // Identifiers and keywords have identifier info attached. 3026 if (IdentifierInfo *II = Tok.getIdentifierInfo()) { 3027 Loc = ConsumeToken(); 3028 return II; 3029 } 3030 return 0; 3031 3032 case tok::ampamp: // 'and' 3033 case tok::pipe: // 'bitor' 3034 case tok::pipepipe: // 'or' 3035 case tok::caret: // 'xor' 3036 case tok::tilde: // 'compl' 3037 case tok::amp: // 'bitand' 3038 case tok::ampequal: // 'and_eq' 3039 case tok::pipeequal: // 'or_eq' 3040 case tok::caretequal: // 'xor_eq' 3041 case tok::exclaim: // 'not' 3042 case tok::exclaimequal: // 'not_eq' 3043 // Alternative tokens do not have identifier info, but their spelling 3044 // starts with an alphabetical character. 3045 SmallString<8> SpellingBuf; 3046 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf); 3047 if (isLetter(Spelling[0])) { 3048 Loc = ConsumeToken(); 3049 return &PP.getIdentifierTable().get(Spelling); 3050 } 3051 return 0; 3052 } 3053} 3054 3055static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName, 3056 IdentifierInfo *ScopeName) { 3057 switch (AttributeList::getKind(AttrName, ScopeName, 3058 AttributeList::AS_CXX11)) { 3059 case AttributeList::AT_CarriesDependency: 3060 case AttributeList::AT_FallThrough: 3061 case AttributeList::AT_CXX11NoReturn: { 3062 return true; 3063 } 3064 3065 default: 3066 return false; 3067 } 3068} 3069 3070/// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently 3071/// only parses standard attributes. 3072/// 3073/// [C++11] attribute-specifier: 3074/// '[' '[' attribute-list ']' ']' 3075/// alignment-specifier 3076/// 3077/// [C++11] attribute-list: 3078/// attribute[opt] 3079/// attribute-list ',' attribute[opt] 3080/// attribute '...' 3081/// attribute-list ',' attribute '...' 3082/// 3083/// [C++11] attribute: 3084/// attribute-token attribute-argument-clause[opt] 3085/// 3086/// [C++11] attribute-token: 3087/// identifier 3088/// attribute-scoped-token 3089/// 3090/// [C++11] attribute-scoped-token: 3091/// attribute-namespace '::' identifier 3092/// 3093/// [C++11] attribute-namespace: 3094/// identifier 3095/// 3096/// [C++11] attribute-argument-clause: 3097/// '(' balanced-token-seq ')' 3098/// 3099/// [C++11] balanced-token-seq: 3100/// balanced-token 3101/// balanced-token-seq balanced-token 3102/// 3103/// [C++11] balanced-token: 3104/// '(' balanced-token-seq ')' 3105/// '[' balanced-token-seq ']' 3106/// '{' balanced-token-seq '}' 3107/// any token but '(', ')', '[', ']', '{', or '}' 3108void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, 3109 SourceLocation *endLoc) { 3110 if (Tok.is(tok::kw_alignas)) { 3111 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas); 3112 ParseAlignmentSpecifier(attrs, endLoc); 3113 return; 3114 } 3115 3116 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) 3117 && "Not a C++11 attribute list"); 3118 3119 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute); 3120 3121 ConsumeBracket(); 3122 ConsumeBracket(); 3123 3124 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs; 3125 3126 while (Tok.isNot(tok::r_square)) { 3127 // attribute not present 3128 if (Tok.is(tok::comma)) { 3129 ConsumeToken(); 3130 continue; 3131 } 3132 3133 SourceLocation ScopeLoc, AttrLoc; 3134 IdentifierInfo *ScopeName = 0, *AttrName = 0; 3135 3136 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); 3137 if (!AttrName) 3138 // Break out to the "expected ']'" diagnostic. 3139 break; 3140 3141 // scoped attribute 3142 if (Tok.is(tok::coloncolon)) { 3143 ConsumeToken(); 3144 3145 ScopeName = AttrName; 3146 ScopeLoc = AttrLoc; 3147 3148 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); 3149 if (!AttrName) { 3150 Diag(Tok.getLocation(), diag::err_expected_ident); 3151 SkipUntil(tok::r_square, tok::comma, true, true); 3152 continue; 3153 } 3154 } 3155 3156 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName,ScopeName); 3157 bool AttrParsed = false; 3158 3159 if (StandardAttr && 3160 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second) 3161 Diag(AttrLoc, diag::err_cxx11_attribute_repeated) 3162 << AttrName << SourceRange(SeenAttrs[AttrName]); 3163 3164 // Parse attribute arguments 3165 if (Tok.is(tok::l_paren)) { 3166 if (ScopeName && ScopeName->getName() == "gnu") { 3167 ParseGNUAttributeArgs(AttrName, AttrLoc, attrs, endLoc, 3168 ScopeName, ScopeLoc, AttributeList::AS_CXX11); 3169 AttrParsed = true; 3170 } else { 3171 if (StandardAttr) 3172 Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments) 3173 << AttrName->getName(); 3174 3175 // FIXME: handle other formats of c++11 attribute arguments 3176 ConsumeParen(); 3177 SkipUntil(tok::r_paren, false); 3178 } 3179 } 3180 3181 if (!AttrParsed) 3182 attrs.addNew(AttrName, 3183 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, 3184 AttrLoc), 3185 ScopeName, ScopeLoc, 0, 3186 SourceLocation(), 0, 0, AttributeList::AS_CXX11); 3187 3188 if (Tok.is(tok::ellipsis)) { 3189 ConsumeToken(); 3190 3191 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis) 3192 << AttrName->getName(); 3193 } 3194 } 3195 3196 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 3197 SkipUntil(tok::r_square, false); 3198 if (endLoc) 3199 *endLoc = Tok.getLocation(); 3200 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 3201 SkipUntil(tok::r_square, false); 3202} 3203 3204/// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq. 3205/// 3206/// attribute-specifier-seq: 3207/// attribute-specifier-seq[opt] attribute-specifier 3208void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs, 3209 SourceLocation *endLoc) { 3210 assert(getLangOpts().CPlusPlus11); 3211 3212 SourceLocation StartLoc = Tok.getLocation(), Loc; 3213 if (!endLoc) 3214 endLoc = &Loc; 3215 3216 do { 3217 ParseCXX11AttributeSpecifier(attrs, endLoc); 3218 } while (isCXX11AttributeSpecifier()); 3219 3220 attrs.Range = SourceRange(StartLoc, *endLoc); 3221} 3222 3223/// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr] 3224/// 3225/// [MS] ms-attribute: 3226/// '[' token-seq ']' 3227/// 3228/// [MS] ms-attribute-seq: 3229/// ms-attribute[opt] 3230/// ms-attribute ms-attribute-seq 3231void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs, 3232 SourceLocation *endLoc) { 3233 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list"); 3234 3235 while (Tok.is(tok::l_square)) { 3236 // FIXME: If this is actually a C++11 attribute, parse it as one. 3237 ConsumeBracket(); 3238 SkipUntil(tok::r_square, true, true); 3239 if (endLoc) *endLoc = Tok.getLocation(); 3240 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); 3241 } 3242} 3243 3244void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, 3245 AccessSpecifier& CurAS) { 3246 IfExistsCondition Result; 3247 if (ParseMicrosoftIfExistsCondition(Result)) 3248 return; 3249 3250 BalancedDelimiterTracker Braces(*this, tok::l_brace); 3251 if (Braces.consumeOpen()) { 3252 Diag(Tok, diag::err_expected_lbrace); 3253 return; 3254 } 3255 3256 switch (Result.Behavior) { 3257 case IEB_Parse: 3258 // Parse the declarations below. 3259 break; 3260 3261 case IEB_Dependent: 3262 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) 3263 << Result.IsIfExists; 3264 // Fall through to skip. 3265 3266 case IEB_Skip: 3267 Braces.skipToEnd(); 3268 return; 3269 } 3270 3271 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 3272 // __if_exists, __if_not_exists can nest. 3273 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) { 3274 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS); 3275 continue; 3276 } 3277 3278 // Check for extraneous top-level semicolon. 3279 if (Tok.is(tok::semi)) { 3280 ConsumeExtraSemi(InsideStruct, TagType); 3281 continue; 3282 } 3283 3284 AccessSpecifier AS = getAccessSpecifierIfPresent(); 3285 if (AS != AS_none) { 3286 // Current token is a C++ access specifier. 3287 CurAS = AS; 3288 SourceLocation ASLoc = Tok.getLocation(); 3289 ConsumeToken(); 3290 if (Tok.is(tok::colon)) 3291 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation()); 3292 else 3293 Diag(Tok, diag::err_expected_colon); 3294 ConsumeToken(); 3295 continue; 3296 } 3297 3298 // Parse all the comma separated declarators. 3299 ParseCXXClassMemberDeclaration(CurAS, 0); 3300 } 3301 3302 Braces.consumeClose(); 3303} 3304