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