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