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