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