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