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