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