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 30 using 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 /// 58 Parser::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. 209 void 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 /// 254 Decl *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 /// 299 Decl *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'. 380 Decl *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 /// 428 Decl *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 /// 492 Decl *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 /// 695 Decl *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 /// 763 SourceLocation 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 868 void 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 887 void 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 936 TypeResult 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 1068 void 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. 1082 bool 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' 1198 void 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, nullptr, 1666 0, 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] 1821 void 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.data(), BaseInfo.size()); 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 1861 BaseResult 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' 1935 AccessSpecifier 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. 1948 void 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 1993 VirtSpecifiers::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 2024 void 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. 2068 bool 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. 2076 bool 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. 2147 void 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 /// 2243 Parser::DeclGroupPtrTy 2244 Parser::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. 2727 ExprResult 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 2767 void 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 2822 Parser::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::<