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