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