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