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