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