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 if (Tok.is(tok::at)) { 2683 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs)) 2684 Diag(Tok, diag::err_at_defs_cxx); 2685 else 2686 Diag(Tok, diag::err_at_in_class); 2687 2688 ConsumeToken(); 2689 SkipUntil(tok::r_brace, StopAtSemi); 2690 return nullptr; 2691 } 2692 2693 // Turn on colon protection early, while parsing declspec, although there is 2694 // nothing to protect there. It prevents from false errors if error recovery 2695 // incorrectly determines where the declspec ends, as in the example: 2696 // struct A { enum class B { C }; }; 2697 // const int C = 4; 2698 // struct D { A::B : C; }; 2699 ColonProtectionRAIIObject X(*this); 2700 2701 // Access declarations. 2702 bool MalformedTypeSpec = false; 2703 if (!TemplateInfo.Kind && 2704 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) { 2705 if (TryAnnotateCXXScopeToken()) 2706 MalformedTypeSpec = true; 2707 2708 bool isAccessDecl; 2709 if (Tok.isNot(tok::annot_cxxscope)) 2710 isAccessDecl = false; 2711 else if (NextToken().is(tok::identifier)) 2712 isAccessDecl = GetLookAheadToken(2).is(tok::semi); 2713 else 2714 isAccessDecl = NextToken().is(tok::kw_operator); 2715 2716 if (isAccessDecl) { 2717 // Collect the scope specifier token we annotated earlier. 2718 CXXScopeSpec SS; 2719 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 2720 /*ObjectHasErrors=*/false, 2721 /*EnteringContext=*/false); 2722 2723 if (SS.isInvalid()) { 2724 SkipUntil(tok::semi); 2725 return nullptr; 2726 } 2727 2728 // Try to parse an unqualified-id. 2729 SourceLocation TemplateKWLoc; 2730 UnqualifiedId Name; 2731 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr, 2732 /*ObjectHadErrors=*/false, false, true, true, 2733 false, &TemplateKWLoc, Name)) { 2734 SkipUntil(tok::semi); 2735 return nullptr; 2736 } 2737 2738 // TODO: recover from mistakenly-qualified operator declarations. 2739 if (ExpectAndConsume(tok::semi, diag::err_expected_after, 2740 "access declaration")) { 2741 SkipUntil(tok::semi); 2742 return nullptr; 2743 } 2744 2745 // FIXME: We should do something with the 'template' keyword here. 2746 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration( 2747 getCurScope(), AS, /*UsingLoc*/ SourceLocation(), 2748 /*TypenameLoc*/ SourceLocation(), SS, Name, 2749 /*EllipsisLoc*/ SourceLocation(), 2750 /*AttrList*/ ParsedAttributesView()))); 2751 } 2752 } 2753 2754 // static_assert-declaration. A templated static_assert declaration is 2755 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate. 2756 if (!TemplateInfo.Kind && 2757 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) { 2758 SourceLocation DeclEnd; 2759 return DeclGroupPtrTy::make( 2760 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd))); 2761 } 2762 2763 if (Tok.is(tok::kw_template)) { 2764 assert(!TemplateInfo.TemplateParams && 2765 "Nested template improperly parsed?"); 2766 ObjCDeclContextSwitch ObjCDC(*this); 2767 SourceLocation DeclEnd; 2768 return DeclGroupPtrTy::make( 2769 DeclGroupRef(ParseTemplateDeclarationOrSpecialization( 2770 DeclaratorContext::Member, DeclEnd, AccessAttrs, AS))); 2771 } 2772 2773 // Handle: member-declaration ::= '__extension__' member-declaration 2774 if (Tok.is(tok::kw___extension__)) { 2775 // __extension__ silences extension warnings in the subexpression. 2776 ExtensionRAIIObject O(Diags); // Use RAII to do this. 2777 ConsumeToken(); 2778 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo, 2779 TemplateDiags); 2780 } 2781 2782 ParsedAttributes DeclAttrs(AttrFactory); 2783 // Optional C++11 attribute-specifier 2784 MaybeParseCXX11Attributes(DeclAttrs); 2785 2786 // The next token may be an OpenMP pragma annotation token. That would 2787 // normally be handled from ParseCXXClassMemberDeclarationWithPragmas, but in 2788 // this case, it came from an *attribute* rather than a pragma. Handle it now. 2789 if (Tok.is(tok::annot_attr_openmp)) 2790 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, DeclAttrs); 2791 2792 if (Tok.is(tok::kw_using)) { 2793 // Eat 'using'. 2794 SourceLocation UsingLoc = ConsumeToken(); 2795 2796 // Consume unexpected 'template' keywords. 2797 while (Tok.is(tok::kw_template)) { 2798 SourceLocation TemplateLoc = ConsumeToken(); 2799 Diag(TemplateLoc, diag::err_unexpected_template_after_using) 2800 << FixItHint::CreateRemoval(TemplateLoc); 2801 } 2802 2803 if (Tok.is(tok::kw_namespace)) { 2804 Diag(UsingLoc, diag::err_using_namespace_in_class); 2805 SkipUntil(tok::semi, StopBeforeMatch); 2806 return nullptr; 2807 } 2808 SourceLocation DeclEnd; 2809 // Otherwise, it must be a using-declaration or an alias-declaration. 2810 return ParseUsingDeclaration(DeclaratorContext::Member, TemplateInfo, 2811 UsingLoc, DeclEnd, DeclAttrs, AS); 2812 } 2813 2814 ParsedAttributes DeclSpecAttrs(AttrFactory); 2815 MaybeParseMicrosoftAttributes(DeclSpecAttrs); 2816 2817 // Hold late-parsed attributes so we can attach a Decl to them later. 2818 LateParsedAttrList CommonLateParsedAttrs; 2819 2820 // decl-specifier-seq: 2821 // Parse the common declaration-specifiers piece. 2822 ParsingDeclSpec DS(*this, TemplateDiags); 2823 DS.takeAttributesFrom(DeclSpecAttrs); 2824 2825 if (MalformedTypeSpec) 2826 DS.SetTypeSpecError(); 2827 2828 // Turn off usual access checking for templates explicit specialization 2829 // and instantiation. 2830 // C++20 [temp.spec] 13.9/6. 2831 // This disables the access checking rules for member function template 2832 // explicit instantiation and explicit specialization. 2833 bool IsTemplateSpecOrInst = 2834 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 2835 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 2836 SuppressAccessChecks diagsFromTag(*this, IsTemplateSpecOrInst); 2837 2838 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class, 2839 &CommonLateParsedAttrs); 2840 2841 if (IsTemplateSpecOrInst) 2842 diagsFromTag.done(); 2843 2844 // Turn off colon protection that was set for declspec. 2845 X.restore(); 2846 2847 // If we had a free-standing type definition with a missing semicolon, we 2848 // may get this far before the problem becomes obvious. 2849 if (DS.hasTagDefinition() && 2850 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate && 2851 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class, 2852 &CommonLateParsedAttrs)) 2853 return nullptr; 2854 2855 MultiTemplateParamsArg TemplateParams( 2856 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() 2857 : nullptr, 2858 TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0); 2859 2860 if (TryConsumeToken(tok::semi)) { 2861 if (DS.isFriendSpecified()) 2862 ProhibitAttributes(DeclAttrs); 2863 2864 RecordDecl *AnonRecord = nullptr; 2865 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec( 2866 getCurScope(), AS, DS, DeclAttrs, TemplateParams, false, AnonRecord); 2867 Actions.ActOnDefinedDeclarationSpecifier(TheDecl); 2868 DS.complete(TheDecl); 2869 if (AnonRecord) { 2870 Decl *decls[] = {AnonRecord, TheDecl}; 2871 return Actions.BuildDeclaratorGroup(decls); 2872 } 2873 return Actions.ConvertDeclToDeclGroup(TheDecl); 2874 } 2875 2876 if (DS.hasTagDefinition()) 2877 Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl()); 2878 2879 ParsingDeclarator DeclaratorInfo(*this, DS, DeclAttrs, 2880 DeclaratorContext::Member); 2881 if (TemplateInfo.TemplateParams) 2882 DeclaratorInfo.setTemplateParameterLists(TemplateParams); 2883 VirtSpecifiers VS; 2884 2885 // Hold late-parsed attributes so we can attach a Decl to them later. 2886 LateParsedAttrList LateParsedAttrs; 2887 2888 SourceLocation EqualLoc; 2889 SourceLocation PureSpecLoc; 2890 2891 auto TryConsumePureSpecifier = [&](bool AllowDefinition) { 2892 if (Tok.isNot(tok::equal)) 2893 return false; 2894 2895 auto &Zero = NextToken(); 2896 SmallString<8> Buffer; 2897 if (Zero.isNot(tok::numeric_constant) || 2898 PP.getSpelling(Zero, Buffer) != "0") 2899 return false; 2900 2901 auto &After = GetLookAheadToken(2); 2902 if (!After.isOneOf(tok::semi, tok::comma) && 2903 !(AllowDefinition && 2904 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try))) 2905 return false; 2906 2907 EqualLoc = ConsumeToken(); 2908 PureSpecLoc = ConsumeToken(); 2909 return true; 2910 }; 2911 2912 SmallVector<Decl *, 8> DeclsInGroup; 2913 ExprResult BitfieldSize; 2914 ExprResult TrailingRequiresClause; 2915 bool ExpectSemi = true; 2916 2917 // C++20 [temp.spec] 13.9/6. 2918 // This disables the access checking rules for member function template 2919 // explicit instantiation and explicit specialization. 2920 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst); 2921 2922 // Parse the first declarator. 2923 if (ParseCXXMemberDeclaratorBeforeInitializer( 2924 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) { 2925 TryConsumeToken(tok::semi); 2926 return nullptr; 2927 } 2928 2929 if (IsTemplateSpecOrInst) 2930 SAC.done(); 2931 2932 // Check for a member function definition. 2933 if (BitfieldSize.isUnset()) { 2934 // MSVC permits pure specifier on inline functions defined at class scope. 2935 // Hence check for =0 before checking for function definition. 2936 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction()) 2937 TryConsumePureSpecifier(/*AllowDefinition*/ true); 2938 2939 FunctionDefinitionKind DefinitionKind = FunctionDefinitionKind::Declaration; 2940 // function-definition: 2941 // 2942 // In C++11, a non-function declarator followed by an open brace is a 2943 // braced-init-list for an in-class member initialization, not an 2944 // erroneous function definition. 2945 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) { 2946 DefinitionKind = FunctionDefinitionKind::Definition; 2947 } else if (DeclaratorInfo.isFunctionDeclarator()) { 2948 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) { 2949 DefinitionKind = FunctionDefinitionKind::Definition; 2950 } else if (Tok.is(tok::equal)) { 2951 const Token &KW = NextToken(); 2952 if (KW.is(tok::kw_default)) 2953 DefinitionKind = FunctionDefinitionKind::Defaulted; 2954 else if (KW.is(tok::kw_delete)) 2955 DefinitionKind = FunctionDefinitionKind::Deleted; 2956 else if (KW.is(tok::code_completion)) { 2957 cutOffParsing(); 2958 Actions.CodeCompleteAfterFunctionEquals(DeclaratorInfo); 2959 return nullptr; 2960 } 2961 } 2962 } 2963 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind); 2964 2965 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains 2966 // to a friend declaration, that declaration shall be a definition. 2967 if (DeclaratorInfo.isFunctionDeclarator() && 2968 DefinitionKind == FunctionDefinitionKind::Declaration && 2969 DS.isFriendSpecified()) { 2970 // Diagnose attributes that appear before decl specifier: 2971 // [[]] friend int foo(); 2972 ProhibitAttributes(DeclAttrs); 2973 } 2974 2975 if (DefinitionKind != FunctionDefinitionKind::Declaration) { 2976 if (!DeclaratorInfo.isFunctionDeclarator()) { 2977 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params); 2978 ConsumeBrace(); 2979 SkipUntil(tok::r_brace); 2980 2981 // Consume the optional ';' 2982 TryConsumeToken(tok::semi); 2983 2984 return nullptr; 2985 } 2986 2987 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 2988 Diag(DeclaratorInfo.getIdentifierLoc(), 2989 diag::err_function_declared_typedef); 2990 2991 // Recover by treating the 'typedef' as spurious. 2992 DS.ClearStorageClassSpecs(); 2993 } 2994 2995 Decl *FunDecl = ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, 2996 TemplateInfo, VS, PureSpecLoc); 2997 2998 if (FunDecl) { 2999 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) { 3000 CommonLateParsedAttrs[i]->addDecl(FunDecl); 3001 } 3002 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) { 3003 LateParsedAttrs[i]->addDecl(FunDecl); 3004 } 3005 } 3006 LateParsedAttrs.clear(); 3007 3008 // Consume the ';' - it's optional unless we have a delete or default 3009 if (Tok.is(tok::semi)) 3010 ConsumeExtraSemi(AfterMemberFunctionDefinition); 3011 3012 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl)); 3013 } 3014 } 3015 3016 // member-declarator-list: 3017 // member-declarator 3018 // member-declarator-list ',' member-declarator 3019 3020 while (true) { 3021 InClassInitStyle HasInClassInit = ICIS_NoInit; 3022 bool HasStaticInitializer = false; 3023 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) { 3024 // DRXXXX: Anonymous bit-fields cannot have a brace-or-equal-initializer. 3025 if (BitfieldSize.isUsable() && !DeclaratorInfo.hasName()) { 3026 // Diagnose the error and pretend there is no in-class initializer. 3027 Diag(Tok, diag::err_anon_bitfield_member_init); 3028 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); 3029 } else if (DeclaratorInfo.isDeclarationOfFunction()) { 3030 // It's a pure-specifier. 3031 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false)) 3032 // Parse it as an expression so that Sema can diagnose it. 3033 HasStaticInitializer = true; 3034 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() != 3035 DeclSpec::SCS_static && 3036 DeclaratorInfo.getDeclSpec().getStorageClassSpec() != 3037 DeclSpec::SCS_typedef && 3038 !DS.isFriendSpecified()) { 3039 // It's a default member initializer. 3040 if (BitfieldSize.get()) 3041 Diag(Tok, getLangOpts().CPlusPlus20 3042 ? diag::warn_cxx17_compat_bitfield_member_init 3043 : diag::ext_bitfield_member_init); 3044 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit; 3045 } else { 3046 HasStaticInitializer = true; 3047 } 3048 } 3049 3050 // NOTE: If Sema is the Action module and declarator is an instance field, 3051 // this call will *not* return the created decl; It will return null. 3052 // See Sema::ActOnCXXMemberDeclarator for details. 3053 3054 NamedDecl *ThisDecl = nullptr; 3055 if (DS.isFriendSpecified()) { 3056 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains 3057 // to a friend declaration, that declaration shall be a definition. 3058 // 3059 // Diagnose attributes that appear in a friend member function declarator: 3060 // friend int foo [[]] (); 3061 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes()) 3062 if (AL.isCXX11Attribute() || AL.isRegularKeywordAttribute()) { 3063 auto Loc = AL.getRange().getBegin(); 3064 (AL.isRegularKeywordAttribute() 3065 ? Diag(Loc, diag::err_keyword_not_allowed) << AL 3066 : Diag(Loc, diag::err_attributes_not_allowed)) 3067 << AL.getRange(); 3068 } 3069 3070 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, 3071 TemplateParams); 3072 } else { 3073 ThisDecl = Actions.ActOnCXXMemberDeclarator( 3074 getCurScope(), AS, DeclaratorInfo, TemplateParams, BitfieldSize.get(), 3075 VS, HasInClassInit); 3076 3077 if (VarTemplateDecl *VT = 3078 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr) 3079 // Re-direct this decl to refer to the templated decl so that we can 3080 // initialize it. 3081 ThisDecl = VT->getTemplatedDecl(); 3082 3083 if (ThisDecl) 3084 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs); 3085 } 3086 3087 // Error recovery might have converted a non-static member into a static 3088 // member. 3089 if (HasInClassInit != ICIS_NoInit && 3090 DeclaratorInfo.getDeclSpec().getStorageClassSpec() == 3091 DeclSpec::SCS_static) { 3092 HasInClassInit = ICIS_NoInit; 3093 HasStaticInitializer = true; 3094 } 3095 3096 if (PureSpecLoc.isValid() && VS.getAbstractLoc().isValid()) { 3097 Diag(PureSpecLoc, diag::err_duplicate_virt_specifier) << "abstract"; 3098 } 3099 if (ThisDecl && PureSpecLoc.isValid()) 3100 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc); 3101 else if (ThisDecl && VS.getAbstractLoc().isValid()) 3102 Actions.ActOnPureSpecifier(ThisDecl, VS.getAbstractLoc()); 3103 3104 // Handle the initializer. 3105 if (HasInClassInit != ICIS_NoInit) { 3106 // The initializer was deferred; parse it and cache the tokens. 3107 Diag(Tok, getLangOpts().CPlusPlus11 3108 ? diag::warn_cxx98_compat_nonstatic_member_init 3109 : diag::ext_nonstatic_member_init); 3110 3111 if (DeclaratorInfo.isArrayOfUnknownBound()) { 3112 // C++11 [dcl.array]p3: An array bound may also be omitted when the 3113 // declarator is followed by an initializer. 3114 // 3115 // A brace-or-equal-initializer for a member-declarator is not an 3116 // initializer in the grammar, so this is ill-formed. 3117 Diag(Tok, diag::err_incomplete_array_member_init); 3118 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); 3119 3120 // Avoid later warnings about a class member of incomplete type. 3121 if (ThisDecl) 3122 ThisDecl->setInvalidDecl(); 3123 } else 3124 ParseCXXNonStaticMemberInitializer(ThisDecl); 3125 } else if (HasStaticInitializer) { 3126 // Normal initializer. 3127 ExprResult Init = ParseCXXMemberInitializer( 3128 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc); 3129 3130 if (Init.isInvalid()) { 3131 if (ThisDecl) 3132 Actions.ActOnUninitializedDecl(ThisDecl); 3133 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); 3134 } else if (ThisDecl) 3135 Actions.AddInitializerToDecl(ThisDecl, Init.get(), 3136 EqualLoc.isInvalid()); 3137 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) 3138 // No initializer. 3139 Actions.ActOnUninitializedDecl(ThisDecl); 3140 3141 if (ThisDecl) { 3142 if (!ThisDecl->isInvalidDecl()) { 3143 // Set the Decl for any late parsed attributes 3144 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) 3145 CommonLateParsedAttrs[i]->addDecl(ThisDecl); 3146 3147 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) 3148 LateParsedAttrs[i]->addDecl(ThisDecl); 3149 } 3150 Actions.FinalizeDeclaration(ThisDecl); 3151 DeclsInGroup.push_back(ThisDecl); 3152 3153 if (DeclaratorInfo.isFunctionDeclarator() && 3154 DeclaratorInfo.getDeclSpec().getStorageClassSpec() != 3155 DeclSpec::SCS_typedef) 3156 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl); 3157 } 3158 LateParsedAttrs.clear(); 3159 3160 DeclaratorInfo.complete(ThisDecl); 3161 3162 // If we don't have a comma, it is either the end of the list (a ';') 3163 // or an error, bail out. 3164 SourceLocation CommaLoc; 3165 if (!TryConsumeToken(tok::comma, CommaLoc)) 3166 break; 3167 3168 if (Tok.isAtStartOfLine() && 3169 !MightBeDeclarator(DeclaratorContext::Member)) { 3170 // This comma was followed by a line-break and something which can't be 3171 // the start of a declarator. The comma was probably a typo for a 3172 // semicolon. 3173 Diag(CommaLoc, diag::err_expected_semi_declaration) 3174 << FixItHint::CreateReplacement(CommaLoc, ";"); 3175 ExpectSemi = false; 3176 break; 3177 } 3178 3179 // Parse the next declarator. 3180 DeclaratorInfo.clear(); 3181 VS.clear(); 3182 BitfieldSize = ExprResult(/*Invalid=*/false); 3183 EqualLoc = PureSpecLoc = SourceLocation(); 3184 DeclaratorInfo.setCommaLoc(CommaLoc); 3185 3186 // GNU attributes are allowed before the second and subsequent declarator. 3187 // However, this does not apply for [[]] attributes (which could show up 3188 // before or after the __attribute__ attributes). 3189 DiagnoseAndSkipCXX11Attributes(); 3190 MaybeParseGNUAttributes(DeclaratorInfo); 3191 DiagnoseAndSkipCXX11Attributes(); 3192 3193 if (ParseCXXMemberDeclaratorBeforeInitializer( 3194 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) 3195 break; 3196 } 3197 3198 if (ExpectSemi && 3199 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { 3200 // Skip to end of block or statement. 3201 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); 3202 // If we stopped at a ';', eat it. 3203 TryConsumeToken(tok::semi); 3204 return nullptr; 3205 } 3206 3207 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); 3208 } 3209 3210 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer. 3211 /// Also detect and reject any attempted defaulted/deleted function definition. 3212 /// The location of the '=', if any, will be placed in EqualLoc. 3213 /// 3214 /// This does not check for a pure-specifier; that's handled elsewhere. 3215 /// 3216 /// brace-or-equal-initializer: 3217 /// '=' initializer-expression 3218 /// braced-init-list 3219 /// 3220 /// initializer-clause: 3221 /// assignment-expression 3222 /// braced-init-list 3223 /// 3224 /// defaulted/deleted function-definition: 3225 /// '=' 'default' 3226 /// '=' 'delete' 3227 /// 3228 /// Prior to C++0x, the assignment-expression in an initializer-clause must 3229 /// be a constant-expression. 3230 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction, 3231 SourceLocation &EqualLoc) { 3232 assert(Tok.isOneOf(tok::equal, tok::l_brace) && 3233 "Data member initializer not starting with '=' or '{'"); 3234 3235 bool IsFieldInitialization = isa_and_present<FieldDecl>(D); 3236 3237 EnterExpressionEvaluationContext Context( 3238 Actions, 3239 IsFieldInitialization 3240 ? Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed 3241 : Sema::ExpressionEvaluationContext::PotentiallyEvaluated, 3242 D); 3243 3244 // CWG2760 3245 // Default member initializers used to initialize a base or member subobject 3246 // [...] are considered to be part of the function body 3247 Actions.ExprEvalContexts.back().InImmediateEscalatingFunctionContext = 3248 IsFieldInitialization; 3249 3250 if (TryConsumeToken(tok::equal, EqualLoc)) { 3251 if (Tok.is(tok::kw_delete)) { 3252 // In principle, an initializer of '= delete p;' is legal, but it will 3253 // never type-check. It's better to diagnose it as an ill-formed 3254 // expression than as an ill-formed deleted non-function member. An 3255 // initializer of '= delete p, foo' will never be parsed, because a 3256 // top-level comma always ends the initializer expression. 3257 const Token &Next = NextToken(); 3258 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) { 3259 if (IsFunction) 3260 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 3261 << 1 /* delete */; 3262 else 3263 Diag(ConsumeToken(), diag::err_deleted_non_function); 3264 return ExprError(); 3265 } 3266 } else if (Tok.is(tok::kw_default)) { 3267 if (IsFunction) 3268 Diag(Tok, diag::err_default_delete_in_multiple_declaration) 3269 << 0 /* default */; 3270 else 3271 Diag(ConsumeToken(), diag::err_default_special_members) 3272 << getLangOpts().CPlusPlus20; 3273 return ExprError(); 3274 } 3275 } 3276 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) { 3277 Diag(Tok, diag::err_ms_property_initializer) << PD; 3278 return ExprError(); 3279 } 3280 return ParseInitializer(); 3281 } 3282 3283 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc, 3284 SourceLocation AttrFixitLoc, 3285 unsigned TagType, Decl *TagDecl) { 3286 // Skip the optional 'final' keyword. 3287 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { 3288 assert(isCXX11FinalKeyword() && "not a class definition"); 3289 ConsumeToken(); 3290 3291 // Diagnose any C++11 attributes after 'final' keyword. 3292 // We deliberately discard these attributes. 3293 ParsedAttributes Attrs(AttrFactory); 3294 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc); 3295 3296 // This can only happen if we had malformed misplaced attributes; 3297 // we only get called if there is a colon or left-brace after the 3298 // attributes. 3299 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace)) 3300 return; 3301 } 3302 3303 // Skip the base clauses. This requires actually parsing them, because 3304 // otherwise we can't be sure where they end (a left brace may appear 3305 // within a template argument). 3306 if (Tok.is(tok::colon)) { 3307 // Enter the scope of the class so that we can correctly parse its bases. 3308 ParseScope ClassScope(this, Scope::ClassScope | Scope::DeclScope); 3309 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true, 3310 TagType == DeclSpec::TST_interface); 3311 auto OldContext = 3312 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl); 3313 3314 // Parse the bases but don't attach them to the class. 3315 ParseBaseClause(nullptr); 3316 3317 Actions.ActOnTagFinishSkippedDefinition(OldContext); 3318 3319 if (!Tok.is(tok::l_brace)) { 3320 Diag(PP.getLocForEndOfToken(PrevTokLocation), 3321 diag::err_expected_lbrace_after_base_specifiers); 3322 return; 3323 } 3324 } 3325 3326 // Skip the body. 3327 assert(Tok.is(tok::l_brace)); 3328 BalancedDelimiterTracker T(*this, tok::l_brace); 3329 T.consumeOpen(); 3330 T.skipToEnd(); 3331 3332 // Parse and discard any trailing attributes. 3333 if (Tok.is(tok::kw___attribute)) { 3334 ParsedAttributes Attrs(AttrFactory); 3335 MaybeParseGNUAttributes(Attrs); 3336 } 3337 } 3338 3339 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas( 3340 AccessSpecifier &AS, ParsedAttributes &AccessAttrs, DeclSpec::TST TagType, 3341 Decl *TagDecl) { 3342 ParenBraceBracketBalancer BalancerRAIIObj(*this); 3343 3344 switch (Tok.getKind()) { 3345 case tok::kw___if_exists: 3346 case tok::kw___if_not_exists: 3347 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS); 3348 return nullptr; 3349 3350 case tok::semi: 3351 // Check for extraneous top-level semicolon. 3352 ConsumeExtraSemi(InsideStruct, TagType); 3353 return nullptr; 3354 3355 // Handle pragmas that can appear as member declarations. 3356 case tok::annot_pragma_vis: 3357 HandlePragmaVisibility(); 3358 return nullptr; 3359 case tok::annot_pragma_pack: 3360 HandlePragmaPack(); 3361 return nullptr; 3362 case tok::annot_pragma_align: 3363 HandlePragmaAlign(); 3364 return nullptr; 3365 case tok::annot_pragma_ms_pointers_to_members: 3366 HandlePragmaMSPointersToMembers(); 3367 return nullptr; 3368 case tok::annot_pragma_ms_pragma: 3369 HandlePragmaMSPragma(); 3370 return nullptr; 3371 case tok::annot_pragma_ms_vtordisp: 3372 HandlePragmaMSVtorDisp(); 3373 return nullptr; 3374 case tok::annot_pragma_dump: 3375 HandlePragmaDump(); 3376 return nullptr; 3377 3378 case tok::kw_namespace: 3379 // If we see a namespace here, a close brace was missing somewhere. 3380 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl)); 3381 return nullptr; 3382 3383 case tok::kw_private: 3384 // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode 3385 // yet. 3386 if (getLangOpts().OpenCL && !NextToken().is(tok::colon)) 3387 return ParseCXXClassMemberDeclaration(AS, AccessAttrs); 3388 [[fallthrough]]; 3389 case tok::kw_public: 3390 case tok::kw_protected: { 3391 if (getLangOpts().HLSL) 3392 Diag(Tok.getLocation(), diag::ext_hlsl_access_specifiers); 3393 AccessSpecifier NewAS = getAccessSpecifierIfPresent(); 3394 assert(NewAS != AS_none); 3395 // Current token is a C++ access specifier. 3396 AS = NewAS; 3397 SourceLocation ASLoc = Tok.getLocation(); 3398 unsigned TokLength = Tok.getLength(); 3399 ConsumeToken(); 3400 AccessAttrs.clear(); 3401 MaybeParseGNUAttributes(AccessAttrs); 3402 3403 SourceLocation EndLoc; 3404 if (TryConsumeToken(tok::colon, EndLoc)) { 3405 } else if (TryConsumeToken(tok::semi, EndLoc)) { 3406 Diag(EndLoc, diag::err_expected) 3407 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":"); 3408 } else { 3409 EndLoc = ASLoc.getLocWithOffset(TokLength); 3410 Diag(EndLoc, diag::err_expected) 3411 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":"); 3412 } 3413 3414 // The Microsoft extension __interface does not permit non-public 3415 // access specifiers. 3416 if (TagType == DeclSpec::TST_interface && AS != AS_public) { 3417 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected); 3418 } 3419 3420 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) { 3421 // found another attribute than only annotations 3422 AccessAttrs.clear(); 3423 } 3424 3425 return nullptr; 3426 } 3427 3428 case tok::annot_attr_openmp: 3429 case tok::annot_pragma_openmp: 3430 return ParseOpenMPDeclarativeDirectiveWithExtDecl( 3431 AS, AccessAttrs, /*Delayed=*/true, TagType, TagDecl); 3432 case tok::annot_pragma_openacc: 3433 return ParseOpenACCDirectiveDecl(); 3434 3435 default: 3436 if (tok::isPragmaAnnotation(Tok.getKind())) { 3437 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl) 3438 << DeclSpec::getSpecifierName( 3439 TagType, Actions.getASTContext().getPrintingPolicy()); 3440 ConsumeAnnotationToken(); 3441 return nullptr; 3442 } 3443 return ParseCXXClassMemberDeclaration(AS, AccessAttrs); 3444 } 3445 } 3446 3447 /// ParseCXXMemberSpecification - Parse the class definition. 3448 /// 3449 /// member-specification: 3450 /// member-declaration member-specification[opt] 3451 /// access-specifier ':' member-specification[opt] 3452 /// 3453 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 3454 SourceLocation AttrFixitLoc, 3455 ParsedAttributes &Attrs, 3456 unsigned TagType, Decl *TagDecl) { 3457 assert((TagType == DeclSpec::TST_struct || 3458 TagType == DeclSpec::TST_interface || 3459 TagType == DeclSpec::TST_union || TagType == DeclSpec::TST_class) && 3460 "Invalid TagType!"); 3461 3462 llvm::TimeTraceScope TimeScope("ParseClass", [&]() { 3463 if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl)) 3464 return TD->getQualifiedNameAsString(); 3465 return std::string("<anonymous>"); 3466 }); 3467 3468 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc, 3469 "parsing struct/union/class body"); 3470 3471 // Determine whether this is a non-nested class. Note that local 3472 // classes are *not* considered to be nested classes. 3473 bool NonNestedClass = true; 3474 if (!ClassStack.empty()) { 3475 for (const Scope *S = getCurScope(); S; S = S->getParent()) { 3476 if (S->isClassScope()) { 3477 // We're inside a class scope, so this is a nested class. 3478 NonNestedClass = false; 3479 3480 // The Microsoft extension __interface does not permit nested classes. 3481 if (getCurrentClass().IsInterface) { 3482 Diag(RecordLoc, diag::err_invalid_member_in_interface) 3483 << /*ErrorType=*/6 3484 << (isa<NamedDecl>(TagDecl) 3485 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString() 3486 : "(anonymous)"); 3487 } 3488 break; 3489 } 3490 3491 if (S->isFunctionScope()) 3492 // If we're in a function or function template then this is a local 3493 // class rather than a nested class. 3494 break; 3495 } 3496 } 3497 3498 // Enter a scope for the class. 3499 ParseScope ClassScope(this, Scope::ClassScope | Scope::DeclScope); 3500 3501 // Note that we are parsing a new (potentially-nested) class definition. 3502 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass, 3503 TagType == DeclSpec::TST_interface); 3504 3505 if (TagDecl) 3506 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 3507 3508 SourceLocation FinalLoc; 3509 SourceLocation AbstractLoc; 3510 bool IsFinalSpelledSealed = false; 3511 bool IsAbstract = false; 3512 3513 // Parse the optional 'final' keyword. 3514 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { 3515 while (true) { 3516 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok); 3517 if (Specifier == VirtSpecifiers::VS_None) 3518 break; 3519 if (isCXX11FinalKeyword()) { 3520 if (FinalLoc.isValid()) { 3521 auto Skipped = ConsumeToken(); 3522 Diag(Skipped, diag::err_duplicate_class_virt_specifier) 3523 << VirtSpecifiers::getSpecifierName(Specifier); 3524 } else { 3525 FinalLoc = ConsumeToken(); 3526 if (Specifier == VirtSpecifiers::VS_Sealed) 3527 IsFinalSpelledSealed = true; 3528 } 3529 } else { 3530 if (AbstractLoc.isValid()) { 3531 auto Skipped = ConsumeToken(); 3532 Diag(Skipped, diag::err_duplicate_class_virt_specifier) 3533 << VirtSpecifiers::getSpecifierName(Specifier); 3534 } else { 3535 AbstractLoc = ConsumeToken(); 3536 IsAbstract = true; 3537 } 3538 } 3539 if (TagType == DeclSpec::TST_interface) 3540 Diag(FinalLoc, diag::err_override_control_interface) 3541 << VirtSpecifiers::getSpecifierName(Specifier); 3542 else if (Specifier == VirtSpecifiers::VS_Final) 3543 Diag(FinalLoc, getLangOpts().CPlusPlus11 3544 ? diag::warn_cxx98_compat_override_control_keyword 3545 : diag::ext_override_control_keyword) 3546 << VirtSpecifiers::getSpecifierName(Specifier); 3547 else if (Specifier == VirtSpecifiers::VS_Sealed) 3548 Diag(FinalLoc, diag::ext_ms_sealed_keyword); 3549 else if (Specifier == VirtSpecifiers::VS_Abstract) 3550 Diag(AbstractLoc, diag::ext_ms_abstract_keyword); 3551 else if (Specifier == VirtSpecifiers::VS_GNU_Final) 3552 Diag(FinalLoc, diag::ext_warn_gnu_final); 3553 } 3554 assert((FinalLoc.isValid() || AbstractLoc.isValid()) && 3555 "not a class definition"); 3556 3557 // Parse any C++11 attributes after 'final' keyword. 3558 // These attributes are not allowed to appear here, 3559 // and the only possible place for them to appertain 3560 // to the class would be between class-key and class-name. 3561 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc); 3562 3563 // ParseClassSpecifier() does only a superficial check for attributes before 3564 // deciding to call this method. For example, for 3565 // `class C final alignas ([l) {` it will decide that this looks like a 3566 // misplaced attribute since it sees `alignas '(' ')'`. But the actual 3567 // attribute parsing code will try to parse the '[' as a constexpr lambda 3568 // and consume enough tokens that the alignas parsing code will eat the 3569 // opening '{'. So bail out if the next token isn't one we expect. 3570 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) { 3571 if (TagDecl) 3572 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 3573 return; 3574 } 3575 } 3576 3577 if (Tok.is(tok::colon)) { 3578 ParseScope InheritanceScope(this, getCurScope()->getFlags() | 3579 Scope::ClassInheritanceScope); 3580 3581 ParseBaseClause(TagDecl); 3582 if (!Tok.is(tok::l_brace)) { 3583 bool SuggestFixIt = false; 3584 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation); 3585 if (Tok.isAtStartOfLine()) { 3586 switch (Tok.getKind()) { 3587 case tok::kw_private: 3588 case tok::kw_protected: 3589 case tok::kw_public: 3590 SuggestFixIt = NextToken().getKind() == tok::colon; 3591 break; 3592 case tok::kw_static_assert: 3593 case tok::r_brace: 3594 case tok::kw_using: 3595 // base-clause can have simple-template-id; 'template' can't be there 3596 case tok::kw_template: 3597 SuggestFixIt = true; 3598 break; 3599 case tok::identifier: 3600 SuggestFixIt = isConstructorDeclarator(true); 3601 break; 3602 default: 3603 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false); 3604 break; 3605 } 3606 } 3607 DiagnosticBuilder LBraceDiag = 3608 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers); 3609 if (SuggestFixIt) { 3610 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {"); 3611 // Try recovering from missing { after base-clause. 3612 PP.EnterToken(Tok, /*IsReinject*/ true); 3613 Tok.setKind(tok::l_brace); 3614 } else { 3615 if (TagDecl) 3616 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 3617 return; 3618 } 3619 } 3620 } 3621 3622 assert(Tok.is(tok::l_brace)); 3623 BalancedDelimiterTracker T(*this, tok::l_brace); 3624 T.consumeOpen(); 3625 3626 if (TagDecl) 3627 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc, 3628 IsFinalSpelledSealed, IsAbstract, 3629 T.getOpenLocation()); 3630 3631 // C++ 11p3: Members of a class defined with the keyword class are private 3632 // by default. Members of a class defined with the keywords struct or union 3633 // are public by default. 3634 // HLSL: In HLSL members of a class are public by default. 3635 AccessSpecifier CurAS; 3636 if (TagType == DeclSpec::TST_class && !getLangOpts().HLSL) 3637 CurAS = AS_private; 3638 else 3639 CurAS = AS_public; 3640 ParsedAttributes AccessAttrs(AttrFactory); 3641 3642 if (TagDecl) { 3643 // While we still have something to read, read the member-declarations. 3644 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) && 3645 Tok.isNot(tok::eof)) { 3646 // Each iteration of this loop reads one member-declaration. 3647 ParseCXXClassMemberDeclarationWithPragmas( 3648 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl); 3649 MaybeDestroyTemplateIds(); 3650 } 3651 T.consumeClose(); 3652 } else { 3653 SkipUntil(tok::r_brace); 3654 } 3655 3656 // If attributes exist after class contents, parse them. 3657 ParsedAttributes attrs(AttrFactory); 3658 MaybeParseGNUAttributes(attrs); 3659 3660 if (TagDecl) 3661 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, 3662 T.getOpenLocation(), 3663 T.getCloseLocation(), attrs); 3664 3665 // C++11 [class.mem]p2: 3666 // Within the class member-specification, the class is regarded as complete 3667 // within function bodies, default arguments, exception-specifications, and 3668 // brace-or-equal-initializers for non-static data members (including such 3669 // things in nested classes). 3670 if (TagDecl && NonNestedClass) { 3671 // We are not inside a nested class. This class and its nested classes 3672 // are complete and we can parse the delayed portions of method 3673 // declarations and the lexed inline method definitions, along with any 3674 // delayed attributes. 3675 3676 SourceLocation SavedPrevTokLocation = PrevTokLocation; 3677 ParseLexedPragmas(getCurrentClass()); 3678 ParseLexedAttributes(getCurrentClass()); 3679 ParseLexedMethodDeclarations(getCurrentClass()); 3680 3681 // We've finished with all pending member declarations. 3682 Actions.ActOnFinishCXXMemberDecls(); 3683 3684 ParseLexedMemberInitializers(getCurrentClass()); 3685 ParseLexedMethodDefs(getCurrentClass()); 3686 PrevTokLocation = SavedPrevTokLocation; 3687 3688 // We've finished parsing everything, including default argument 3689 // initializers. 3690 Actions.ActOnFinishCXXNonNestedClass(); 3691 } 3692 3693 if (TagDecl) 3694 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange()); 3695 3696 // Leave the class scope. 3697 ParsingDef.Pop(); 3698 ClassScope.Exit(); 3699 } 3700 3701 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) { 3702 assert(Tok.is(tok::kw_namespace)); 3703 3704 // FIXME: Suggest where the close brace should have gone by looking 3705 // at indentation changes within the definition body. 3706 Diag(D->getLocation(), diag::err_missing_end_of_definition) << D; 3707 Diag(Tok.getLocation(), diag::note_missing_end_of_definition_before) << D; 3708 3709 // Push '};' onto the token stream to recover. 3710 PP.EnterToken(Tok, /*IsReinject*/ true); 3711 3712 Tok.startToken(); 3713 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation)); 3714 Tok.setKind(tok::semi); 3715 PP.EnterToken(Tok, /*IsReinject*/ true); 3716 3717 Tok.setKind(tok::r_brace); 3718 } 3719 3720 /// ParseConstructorInitializer - Parse a C++ constructor initializer, 3721 /// which explicitly initializes the members or base classes of a 3722 /// class (C++ [class.base.init]). For example, the three initializers 3723 /// after the ':' in the Derived constructor below: 3724 /// 3725 /// @code 3726 /// class Base { }; 3727 /// class Derived : Base { 3728 /// int x; 3729 /// float f; 3730 /// public: 3731 /// Derived(float f) : Base(), x(17), f(f) { } 3732 /// }; 3733 /// @endcode 3734 /// 3735 /// [C++] ctor-initializer: 3736 /// ':' mem-initializer-list 3737 /// 3738 /// [C++] mem-initializer-list: 3739 /// mem-initializer ...[opt] 3740 /// mem-initializer ...[opt] , mem-initializer-list 3741 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) { 3742 assert(Tok.is(tok::colon) && 3743 "Constructor initializer always starts with ':'"); 3744 3745 // Poison the SEH identifiers so they are flagged as illegal in constructor 3746 // initializers. 3747 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 3748 SourceLocation ColonLoc = ConsumeToken(); 3749 3750 SmallVector<CXXCtorInitializer *, 4> MemInitializers; 3751 bool AnyErrors = false; 3752 3753 do { 3754 if (Tok.is(tok::code_completion)) { 3755 cutOffParsing(); 3756 Actions.CodeCompleteConstructorInitializer(ConstructorDecl, 3757 MemInitializers); 3758 return; 3759 } 3760 3761 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 3762 if (!MemInit.isInvalid()) 3763 MemInitializers.push_back(MemInit.get()); 3764 else 3765 AnyErrors = true; 3766 3767 if (Tok.is(tok::comma)) 3768 ConsumeToken(); 3769 else if (Tok.is(tok::l_brace)) 3770 break; 3771 // If the previous initializer was valid and the next token looks like a 3772 // base or member initializer, assume that we're just missing a comma. 3773 else if (!MemInit.isInvalid() && 3774 Tok.isOneOf(tok::identifier, tok::coloncolon)) { 3775 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 3776 Diag(Loc, diag::err_ctor_init_missing_comma) 3777 << FixItHint::CreateInsertion(Loc, ", "); 3778 } else { 3779 // Skip over garbage, until we get to '{'. Don't eat the '{'. 3780 if (!MemInit.isInvalid()) 3781 Diag(Tok.getLocation(), diag::err_expected_either) 3782 << tok::l_brace << tok::comma; 3783 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); 3784 break; 3785 } 3786 } while (true); 3787 3788 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers, 3789 AnyErrors); 3790 } 3791 3792 /// ParseMemInitializer - Parse a C++ member initializer, which is 3793 /// part of a constructor initializer that explicitly initializes one 3794 /// member or base class (C++ [class.base.init]). See 3795 /// ParseConstructorInitializer for an example. 3796 /// 3797 /// [C++] mem-initializer: 3798 /// mem-initializer-id '(' expression-list[opt] ')' 3799 /// [C++0x] mem-initializer-id braced-init-list 3800 /// 3801 /// [C++] mem-initializer-id: 3802 /// '::'[opt] nested-name-specifier[opt] class-name 3803 /// identifier 3804 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { 3805 // parse '::'[opt] nested-name-specifier[opt] 3806 CXXScopeSpec SS; 3807 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 3808 /*ObjectHasErrors=*/false, 3809 /*EnteringContext=*/false)) 3810 return true; 3811 3812 // : identifier 3813 IdentifierInfo *II = nullptr; 3814 SourceLocation IdLoc = Tok.getLocation(); 3815 // : declype(...) 3816 DeclSpec DS(AttrFactory); 3817 // : template_name<...> 3818 TypeResult TemplateTypeTy; 3819 3820 if (Tok.is(tok::identifier)) { 3821 // Get the identifier. This may be a member name or a class name, 3822 // but we'll let the semantic analysis determine which it is. 3823 II = Tok.getIdentifierInfo(); 3824 ConsumeToken(); 3825 } else if (Tok.is(tok::annot_decltype)) { 3826 // Get the decltype expression, if there is one. 3827 // Uses of decltype will already have been converted to annot_decltype by 3828 // ParseOptionalCXXScopeSpecifier at this point. 3829 // FIXME: Can we get here with a scope specifier? 3830 ParseDecltypeSpecifier(DS); 3831 } else { 3832 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id) 3833 ? takeTemplateIdAnnotation(Tok) 3834 : nullptr; 3835 if (TemplateId && TemplateId->mightBeType()) { 3836 AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::No, 3837 /*IsClassName=*/true); 3838 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 3839 TemplateTypeTy = getTypeAnnotation(Tok); 3840 ConsumeAnnotationToken(); 3841 } else { 3842 Diag(Tok, diag::err_expected_member_or_base_name); 3843 return true; 3844 } 3845 } 3846 3847 // Parse the '('. 3848 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 3849 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 3850 3851 // FIXME: Add support for signature help inside initializer lists. 3852 ExprResult InitList = ParseBraceInitializer(); 3853 if (InitList.isInvalid()) 3854 return true; 3855 3856 SourceLocation EllipsisLoc; 3857 TryConsumeToken(tok::ellipsis, EllipsisLoc); 3858 3859 if (TemplateTypeTy.isInvalid()) 3860 return true; 3861 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 3862 TemplateTypeTy.get(), DS, IdLoc, 3863 InitList.get(), EllipsisLoc); 3864 } else if (Tok.is(tok::l_paren)) { 3865 BalancedDelimiterTracker T(*this, tok::l_paren); 3866 T.consumeOpen(); 3867 3868 // Parse the optional expression-list. 3869 ExprVector ArgExprs; 3870 auto RunSignatureHelp = [&] { 3871 if (TemplateTypeTy.isInvalid()) 3872 return QualType(); 3873 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp( 3874 ConstructorDecl, SS, TemplateTypeTy.get(), ArgExprs, II, 3875 T.getOpenLocation(), /*Braced=*/false); 3876 CalledSignatureHelp = true; 3877 return PreferredType; 3878 }; 3879 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, [&] { 3880 PreferredType.enterFunctionArgument(Tok.getLocation(), 3881 RunSignatureHelp); 3882 })) { 3883 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) 3884 RunSignatureHelp(); 3885 SkipUntil(tok::r_paren, StopAtSemi); 3886 return true; 3887 } 3888 3889 T.consumeClose(); 3890 3891 SourceLocation EllipsisLoc; 3892 TryConsumeToken(tok::ellipsis, EllipsisLoc); 3893 3894 if (TemplateTypeTy.isInvalid()) 3895 return true; 3896 return Actions.ActOnMemInitializer( 3897 ConstructorDecl, getCurScope(), SS, II, TemplateTypeTy.get(), DS, IdLoc, 3898 T.getOpenLocation(), ArgExprs, T.getCloseLocation(), EllipsisLoc); 3899 } 3900 3901 if (TemplateTypeTy.isInvalid()) 3902 return true; 3903 3904 if (getLangOpts().CPlusPlus11) 3905 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace; 3906 else 3907 return Diag(Tok, diag::err_expected) << tok::l_paren; 3908 } 3909 3910 /// Parse a C++ exception-specification if present (C++0x [except.spec]). 3911 /// 3912 /// exception-specification: 3913 /// dynamic-exception-specification 3914 /// noexcept-specification 3915 /// 3916 /// noexcept-specification: 3917 /// 'noexcept' 3918 /// 'noexcept' '(' constant-expression ')' 3919 ExceptionSpecificationType Parser::tryParseExceptionSpecification( 3920 bool Delayed, SourceRange &SpecificationRange, 3921 SmallVectorImpl<ParsedType> &DynamicExceptions, 3922 SmallVectorImpl<SourceRange> &DynamicExceptionRanges, 3923 ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens) { 3924 ExceptionSpecificationType Result = EST_None; 3925 ExceptionSpecTokens = nullptr; 3926 3927 // Handle delayed parsing of exception-specifications. 3928 if (Delayed) { 3929 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept)) 3930 return EST_None; 3931 3932 // Consume and cache the starting token. 3933 bool IsNoexcept = Tok.is(tok::kw_noexcept); 3934 Token StartTok = Tok; 3935 SpecificationRange = SourceRange(ConsumeToken()); 3936 3937 // Check for a '('. 3938 if (!Tok.is(tok::l_paren)) { 3939 // If this is a bare 'noexcept', we're done. 3940 if (IsNoexcept) { 3941 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl); 3942 NoexceptExpr = nullptr; 3943 return EST_BasicNoexcept; 3944 } 3945 3946 Diag(Tok, diag::err_expected_lparen_after) << "throw"; 3947 return EST_DynamicNone; 3948 } 3949 3950 // Cache the tokens for the exception-specification. 3951 ExceptionSpecTokens = new CachedTokens; 3952 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept' 3953 ExceptionSpecTokens->push_back(Tok); // '(' 3954 SpecificationRange.setEnd(ConsumeParen()); // '(' 3955 3956 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens, 3957 /*StopAtSemi=*/true, 3958 /*ConsumeFinalToken=*/true); 3959 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation()); 3960 3961 return EST_Unparsed; 3962 } 3963 3964 // See if there's a dynamic specification. 3965 if (Tok.is(tok::kw_throw)) { 3966 Result = ParseDynamicExceptionSpecification( 3967 SpecificationRange, DynamicExceptions, DynamicExceptionRanges); 3968 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() && 3969 "Produced different number of exception types and ranges."); 3970 } 3971 3972 // If there's no noexcept specification, we're done. 3973 if (Tok.isNot(tok::kw_noexcept)) 3974 return Result; 3975 3976 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl); 3977 3978 // If we already had a dynamic specification, parse the noexcept for, 3979 // recovery, but emit a diagnostic and don't store the results. 3980 SourceRange NoexceptRange; 3981 ExceptionSpecificationType NoexceptType = EST_None; 3982 3983 SourceLocation KeywordLoc = ConsumeToken(); 3984 if (Tok.is(tok::l_paren)) { 3985 // There is an argument. 3986 BalancedDelimiterTracker T(*this, tok::l_paren); 3987 T.consumeOpen(); 3988 3989 EnterExpressionEvaluationContext ConstantEvaluated( 3990 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated); 3991 NoexceptExpr = ParseConstantExpressionInExprEvalContext(); 3992 3993 T.consumeClose(); 3994 if (!NoexceptExpr.isInvalid()) { 3995 NoexceptExpr = 3996 Actions.ActOnNoexceptSpec(NoexceptExpr.get(), NoexceptType); 3997 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation()); 3998 } else { 3999 NoexceptType = EST_BasicNoexcept; 4000 } 4001 } else { 4002 // There is no argument. 4003 NoexceptType = EST_BasicNoexcept; 4004 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc); 4005 } 4006 4007 if (Result == EST_None) { 4008 SpecificationRange = NoexceptRange; 4009 Result = NoexceptType; 4010 4011 // If there's a dynamic specification after a noexcept specification, 4012 // parse that and ignore the results. 4013 if (Tok.is(tok::kw_throw)) { 4014 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 4015 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions, 4016 DynamicExceptionRanges); 4017 } 4018 } else { 4019 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 4020 } 4021 4022 return Result; 4023 } 4024 4025 static void diagnoseDynamicExceptionSpecification(Parser &P, SourceRange Range, 4026 bool IsNoexcept) { 4027 if (P.getLangOpts().CPlusPlus11) { 4028 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)"; 4029 P.Diag(Range.getBegin(), P.getLangOpts().CPlusPlus17 && !IsNoexcept 4030 ? diag::ext_dynamic_exception_spec 4031 : diag::warn_exception_spec_deprecated) 4032 << Range; 4033 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated) 4034 << Replacement << FixItHint::CreateReplacement(Range, Replacement); 4035 } 4036 } 4037 4038 /// ParseDynamicExceptionSpecification - Parse a C++ 4039 /// dynamic-exception-specification (C++ [except.spec]). 4040 /// 4041 /// dynamic-exception-specification: 4042 /// 'throw' '(' type-id-list [opt] ')' 4043 /// [MS] 'throw' '(' '...' ')' 4044 /// 4045 /// type-id-list: 4046 /// type-id ... [opt] 4047 /// type-id-list ',' type-id ... [opt] 4048 /// 4049 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification( 4050 SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, 4051 SmallVectorImpl<SourceRange> &Ranges) { 4052 assert(Tok.is(tok::kw_throw) && "expected throw"); 4053 4054 SpecificationRange.setBegin(ConsumeToken()); 4055 BalancedDelimiterTracker T(*this, tok::l_paren); 4056 if (T.consumeOpen()) { 4057 Diag(Tok, diag::err_expected_lparen_after) << "throw"; 4058 SpecificationRange.setEnd(SpecificationRange.getBegin()); 4059 return EST_DynamicNone; 4060 } 4061 4062 // Parse throw(...), a Microsoft extension that means "this function 4063 // can throw anything". 4064 if (Tok.is(tok::ellipsis)) { 4065 SourceLocation EllipsisLoc = ConsumeToken(); 4066 if (!getLangOpts().MicrosoftExt) 4067 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 4068 T.consumeClose(); 4069 SpecificationRange.setEnd(T.getCloseLocation()); 4070 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false); 4071 return EST_MSAny; 4072 } 4073 4074 // Parse the sequence of type-ids. 4075 SourceRange Range; 4076 while (Tok.isNot(tok::r_paren)) { 4077 TypeResult Res(ParseTypeName(&Range)); 4078 4079 if (Tok.is(tok::ellipsis)) { 4080 // C++0x [temp.variadic]p5: 4081 // - In a dynamic-exception-specification (15.4); the pattern is a 4082 // type-id. 4083 SourceLocation Ellipsis = ConsumeToken(); 4084 Range.setEnd(Ellipsis); 4085 if (!Res.isInvalid()) 4086 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis); 4087 } 4088 4089 if (!Res.isInvalid()) { 4090 Exceptions.push_back(Res.get()); 4091 Ranges.push_back(Range); 4092 } 4093 4094 if (!TryConsumeToken(tok::comma)) 4095 break; 4096 } 4097 4098 T.consumeClose(); 4099 SpecificationRange.setEnd(T.getCloseLocation()); 4100 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, 4101 Exceptions.empty()); 4102 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic; 4103 } 4104 4105 /// ParseTrailingReturnType - Parse a trailing return type on a new-style 4106 /// function declaration. 4107 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range, 4108 bool MayBeFollowedByDirectInit) { 4109 assert(Tok.is(tok::arrow) && "expected arrow"); 4110 4111 ConsumeToken(); 4112 4113 return ParseTypeName(&Range, MayBeFollowedByDirectInit 4114 ? DeclaratorContext::TrailingReturnVar 4115 : DeclaratorContext::TrailingReturn); 4116 } 4117 4118 /// Parse a requires-clause as part of a function declaration. 4119 void Parser::ParseTrailingRequiresClause(Declarator &D) { 4120 assert(Tok.is(tok::kw_requires) && "expected requires"); 4121 4122 SourceLocation RequiresKWLoc = ConsumeToken(); 4123 4124 ExprResult TrailingRequiresClause; 4125 ParseScope ParamScope(this, Scope::DeclScope | 4126 Scope::FunctionDeclarationScope | 4127 Scope::FunctionPrototypeScope); 4128 4129 Actions.ActOnStartTrailingRequiresClause(getCurScope(), D); 4130 4131 std::optional<Sema::CXXThisScopeRAII> ThisScope; 4132 InitCXXThisScopeForDeclaratorIfRelevant(D, D.getDeclSpec(), ThisScope); 4133 4134 TrailingRequiresClause = 4135 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true); 4136 4137 TrailingRequiresClause = 4138 Actions.ActOnFinishTrailingRequiresClause(TrailingRequiresClause); 4139 4140 if (!D.isDeclarationOfFunction()) { 4141 Diag(RequiresKWLoc, 4142 diag::err_requires_clause_on_declarator_not_declaring_a_function); 4143 return; 4144 } 4145 4146 if (TrailingRequiresClause.isInvalid()) 4147 SkipUntil({tok::l_brace, tok::arrow, tok::kw_try, tok::comma, tok::colon}, 4148 StopAtSemi | StopBeforeMatch); 4149 else 4150 D.setTrailingRequiresClause(TrailingRequiresClause.get()); 4151 4152 // Did the user swap the trailing return type and requires clause? 4153 if (D.isFunctionDeclarator() && Tok.is(tok::arrow) && 4154 D.getDeclSpec().getTypeSpecType() == TST_auto) { 4155 SourceLocation ArrowLoc = Tok.getLocation(); 4156 SourceRange Range; 4157 TypeResult TrailingReturnType = 4158 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false); 4159 4160 if (!TrailingReturnType.isInvalid()) { 4161 Diag(ArrowLoc, 4162 diag::err_requires_clause_must_appear_after_trailing_return) 4163 << Range; 4164 auto &FunctionChunk = D.getFunctionTypeInfo(); 4165 FunctionChunk.HasTrailingReturnType = TrailingReturnType.isUsable(); 4166 FunctionChunk.TrailingReturnType = TrailingReturnType.get(); 4167 FunctionChunk.TrailingReturnTypeLoc = Range.getBegin(); 4168 } else 4169 SkipUntil({tok::equal, tok::l_brace, tok::arrow, tok::kw_try, tok::comma}, 4170 StopAtSemi | StopBeforeMatch); 4171 } 4172 } 4173 4174 /// We have just started parsing the definition of a new class, 4175 /// so push that class onto our stack of classes that is currently 4176 /// being parsed. 4177 Sema::ParsingClassState Parser::PushParsingClass(Decl *ClassDecl, 4178 bool NonNestedClass, 4179 bool IsInterface) { 4180 assert((NonNestedClass || !ClassStack.empty()) && 4181 "Nested class without outer class"); 4182 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface)); 4183 return Actions.PushParsingClass(); 4184 } 4185 4186 /// Deallocate the given parsed class and all of its nested 4187 /// classes. 4188 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 4189 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I) 4190 delete Class->LateParsedDeclarations[I]; 4191 delete Class; 4192 } 4193 4194 /// Pop the top class of the stack of classes that are 4195 /// currently being parsed. 4196 /// 4197 /// This routine should be called when we have finished parsing the 4198 /// definition of a class, but have not yet popped the Scope 4199 /// associated with the class's definition. 4200 void Parser::PopParsingClass(Sema::ParsingClassState state) { 4201 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 4202 4203 Actions.PopParsingClass(state); 4204 4205 ParsingClass *Victim = ClassStack.top(); 4206 ClassStack.pop(); 4207 if (Victim->TopLevelClass) { 4208 // Deallocate all of the nested classes of this class, 4209 // recursively: we don't need to keep any of this information. 4210 DeallocateParsedClasses(Victim); 4211 return; 4212 } 4213 assert(!ClassStack.empty() && "Missing top-level class?"); 4214 4215 if (Victim->LateParsedDeclarations.empty()) { 4216 // The victim is a nested class, but we will not need to perform 4217 // any processing after the definition of this class since it has 4218 // no members whose handling was delayed. Therefore, we can just 4219 // remove this nested class. 4220 DeallocateParsedClasses(Victim); 4221 return; 4222 } 4223 4224 // This nested class has some members that will need to be processed 4225 // after the top-level class is completely defined. Therefore, add 4226 // it to the list of nested classes within its parent. 4227 assert(getCurScope()->isClassScope() && 4228 "Nested class outside of class scope?"); 4229 ClassStack.top()->LateParsedDeclarations.push_back( 4230 new LateParsedClass(this, Victim)); 4231 } 4232 4233 /// Try to parse an 'identifier' which appears within an attribute-token. 4234 /// 4235 /// \return the parsed identifier on success, and 0 if the next token is not an 4236 /// attribute-token. 4237 /// 4238 /// C++11 [dcl.attr.grammar]p3: 4239 /// If a keyword or an alternative token that satisfies the syntactic 4240 /// requirements of an identifier is contained in an attribute-token, 4241 /// it is considered an identifier. 4242 IdentifierInfo * 4243 Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc, 4244 Sema::AttributeCompletion Completion, 4245 const IdentifierInfo *Scope) { 4246 switch (Tok.getKind()) { 4247 default: 4248 // Identifiers and keywords have identifier info attached. 4249 if (!Tok.isAnnotation()) { 4250 if (IdentifierInfo *II = Tok.getIdentifierInfo()) { 4251 Loc = ConsumeToken(); 4252 return II; 4253 } 4254 } 4255 return nullptr; 4256 4257 case tok::code_completion: 4258 cutOffParsing(); 4259 Actions.CodeCompleteAttribute(getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 4260 : ParsedAttr::AS_C23, 4261 Completion, Scope); 4262 return nullptr; 4263 4264 case tok::numeric_constant: { 4265 // If we got a numeric constant, check to see if it comes from a macro that 4266 // corresponds to the predefined __clang__ macro. If it does, warn the user 4267 // and recover by pretending they said _Clang instead. 4268 if (Tok.getLocation().isMacroID()) { 4269 SmallString<8> ExpansionBuf; 4270 SourceLocation ExpansionLoc = 4271 PP.getSourceManager().getExpansionLoc(Tok.getLocation()); 4272 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf); 4273 if (Spelling == "__clang__") { 4274 SourceRange TokRange( 4275 ExpansionLoc, 4276 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc())); 4277 Diag(Tok, diag::warn_wrong_clang_attr_namespace) 4278 << FixItHint::CreateReplacement(TokRange, "_Clang"); 4279 Loc = ConsumeToken(); 4280 return &PP.getIdentifierTable().get("_Clang"); 4281 } 4282 } 4283 return nullptr; 4284 } 4285 4286 case tok::ampamp: // 'and' 4287 case tok::pipe: // 'bitor' 4288 case tok::pipepipe: // 'or' 4289 case tok::caret: // 'xor' 4290 case tok::tilde: // 'compl' 4291 case tok::amp: // 'bitand' 4292 case tok::ampequal: // 'and_eq' 4293 case tok::pipeequal: // 'or_eq' 4294 case tok::caretequal: // 'xor_eq' 4295 case tok::exclaim: // 'not' 4296 case tok::exclaimequal: // 'not_eq' 4297 // Alternative tokens do not have identifier info, but their spelling 4298 // starts with an alphabetical character. 4299 SmallString<8> SpellingBuf; 4300 SourceLocation SpellingLoc = 4301 PP.getSourceManager().getSpellingLoc(Tok.getLocation()); 4302 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf); 4303 if (isLetter(Spelling[0])) { 4304 Loc = ConsumeToken(); 4305 return &PP.getIdentifierTable().get(Spelling); 4306 } 4307 return nullptr; 4308 } 4309 } 4310 4311 void Parser::ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName, 4312 CachedTokens &OpenMPTokens) { 4313 // Both 'sequence' and 'directive' attributes require arguments, so parse the 4314 // open paren for the argument list. 4315 BalancedDelimiterTracker T(*this, tok::l_paren); 4316 if (T.consumeOpen()) { 4317 Diag(Tok, diag::err_expected) << tok::l_paren; 4318 return; 4319 } 4320 4321 if (AttrName->isStr("directive")) { 4322 // If the attribute is named `directive`, we can consume its argument list 4323 // and push the tokens from it into the cached token stream for a new OpenMP 4324 // pragma directive. 4325 Token OMPBeginTok; 4326 OMPBeginTok.startToken(); 4327 OMPBeginTok.setKind(tok::annot_attr_openmp); 4328 OMPBeginTok.setLocation(Tok.getLocation()); 4329 OpenMPTokens.push_back(OMPBeginTok); 4330 4331 ConsumeAndStoreUntil(tok::r_paren, OpenMPTokens, /*StopAtSemi=*/false, 4332 /*ConsumeFinalToken*/ false); 4333 Token OMPEndTok; 4334 OMPEndTok.startToken(); 4335 OMPEndTok.setKind(tok::annot_pragma_openmp_end); 4336 OMPEndTok.setLocation(Tok.getLocation()); 4337 OpenMPTokens.push_back(OMPEndTok); 4338 } else { 4339 assert(AttrName->isStr("sequence") && 4340 "Expected either 'directive' or 'sequence'"); 4341 // If the attribute is named 'sequence', its argument is a list of one or 4342 // more OpenMP attributes (either 'omp::directive' or 'omp::sequence', 4343 // where the 'omp::' is optional). 4344 do { 4345 // We expect to see one of the following: 4346 // * An identifier (omp) for the attribute namespace followed by :: 4347 // * An identifier (directive) or an identifier (sequence). 4348 SourceLocation IdentLoc; 4349 const IdentifierInfo *Ident = TryParseCXX11AttributeIdentifier(IdentLoc); 4350 4351 // If there is an identifier and it is 'omp', a double colon is required 4352 // followed by the actual identifier we're after. 4353 if (Ident && Ident->isStr("omp") && !ExpectAndConsume(tok::coloncolon)) 4354 Ident = TryParseCXX11AttributeIdentifier(IdentLoc); 4355 4356 // If we failed to find an identifier (scoped or otherwise), or we found 4357 // an unexpected identifier, diagnose. 4358 if (!Ident || (!Ident->isStr("directive") && !Ident->isStr("sequence"))) { 4359 Diag(Tok.getLocation(), diag::err_expected_sequence_or_directive); 4360 SkipUntil(tok::r_paren, StopBeforeMatch); 4361 continue; 4362 } 4363 // We read an identifier. If the identifier is one of the ones we 4364 // expected, we can recurse to parse the args. 4365 ParseOpenMPAttributeArgs(Ident, OpenMPTokens); 4366 4367 // There may be a comma to signal that we expect another directive in the 4368 // sequence. 4369 } while (TryConsumeToken(tok::comma)); 4370 } 4371 // Parse the closing paren for the argument list. 4372 T.consumeClose(); 4373 } 4374 4375 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName, 4376 IdentifierInfo *ScopeName) { 4377 switch ( 4378 ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) { 4379 case ParsedAttr::AT_CarriesDependency: 4380 case ParsedAttr::AT_Deprecated: 4381 case ParsedAttr::AT_FallThrough: 4382 case ParsedAttr::AT_CXX11NoReturn: 4383 case ParsedAttr::AT_NoUniqueAddress: 4384 case ParsedAttr::AT_Likely: 4385 case ParsedAttr::AT_Unlikely: 4386 return true; 4387 case ParsedAttr::AT_WarnUnusedResult: 4388 return !ScopeName && AttrName->getName().equals("nodiscard"); 4389 case ParsedAttr::AT_Unused: 4390 return !ScopeName && AttrName->getName().equals("maybe_unused"); 4391 default: 4392 return false; 4393 } 4394 } 4395 4396 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause. 4397 /// 4398 /// [C++11] attribute-argument-clause: 4399 /// '(' balanced-token-seq ')' 4400 /// 4401 /// [C++11] balanced-token-seq: 4402 /// balanced-token 4403 /// balanced-token-seq balanced-token 4404 /// 4405 /// [C++11] balanced-token: 4406 /// '(' balanced-token-seq ')' 4407 /// '[' balanced-token-seq ']' 4408 /// '{' balanced-token-seq '}' 4409 /// any token but '(', ')', '[', ']', '{', or '}' 4410 bool Parser::ParseCXX11AttributeArgs( 4411 IdentifierInfo *AttrName, SourceLocation AttrNameLoc, 4412 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, 4413 SourceLocation ScopeLoc, CachedTokens &OpenMPTokens) { 4414 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list"); 4415 SourceLocation LParenLoc = Tok.getLocation(); 4416 const LangOptions &LO = getLangOpts(); 4417 ParsedAttr::Form Form = 4418 LO.CPlusPlus ? ParsedAttr::Form::CXX11() : ParsedAttr::Form::C23(); 4419 4420 // Try parsing microsoft attributes 4421 if (getLangOpts().MicrosoftExt || getLangOpts().HLSL) { 4422 if (hasAttribute(AttributeCommonInfo::Syntax::AS_Microsoft, ScopeName, 4423 AttrName, getTargetInfo(), getLangOpts())) 4424 Form = ParsedAttr::Form::Microsoft(); 4425 } 4426 4427 // If the attribute isn't known, we will not attempt to parse any 4428 // arguments. 4429 if (Form.getSyntax() != ParsedAttr::AS_Microsoft && 4430 !hasAttribute(LO.CPlusPlus ? AttributeCommonInfo::Syntax::AS_CXX11 4431 : AttributeCommonInfo::Syntax::AS_C23, 4432 ScopeName, AttrName, getTargetInfo(), getLangOpts())) { 4433 // Eat the left paren, then skip to the ending right paren. 4434 ConsumeParen(); 4435 SkipUntil(tok::r_paren); 4436 return false; 4437 } 4438 4439 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) { 4440 // GNU-scoped attributes have some special cases to handle GNU-specific 4441 // behaviors. 4442 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, 4443 ScopeLoc, Form, nullptr); 4444 return true; 4445 } 4446 4447 if (ScopeName && ScopeName->isStr("omp")) { 4448 Diag(AttrNameLoc, getLangOpts().OpenMP >= 51 4449 ? diag::warn_omp51_compat_attributes 4450 : diag::ext_omp_attributes); 4451 4452 ParseOpenMPAttributeArgs(AttrName, OpenMPTokens); 4453 4454 // We claim that an attribute was parsed and added so that one is not 4455 // created for us by the caller. 4456 return true; 4457 } 4458 4459 unsigned NumArgs; 4460 // Some Clang-scoped attributes have some special parsing behavior. 4461 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang"))) 4462 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, 4463 ScopeName, ScopeLoc, Form); 4464 else 4465 NumArgs = ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, 4466 ScopeName, ScopeLoc, Form); 4467 4468 if (!Attrs.empty() && 4469 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) { 4470 ParsedAttr &Attr = Attrs.back(); 4471 4472 // Ignore attributes that don't exist for the target. 4473 if (!Attr.existsInTarget(getTargetInfo())) { 4474 Diag(LParenLoc, diag::warn_unknown_attribute_ignored) << AttrName; 4475 Attr.setInvalid(true); 4476 return true; 4477 } 4478 4479 // If the attribute is a standard or built-in attribute and we are 4480 // parsing an argument list, we need to determine whether this attribute 4481 // was allowed to have an argument list (such as [[deprecated]]), and how 4482 // many arguments were parsed (so we can diagnose on [[deprecated()]]). 4483 if (Attr.getMaxArgs() && !NumArgs) { 4484 // The attribute was allowed to have arguments, but none were provided 4485 // even though the attribute parsed successfully. This is an error. 4486 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName; 4487 Attr.setInvalid(true); 4488 } else if (!Attr.getMaxArgs()) { 4489 // The attribute parsed successfully, but was not allowed to have any 4490 // arguments. It doesn't matter whether any were provided -- the 4491 // presence of the argument list (even if empty) is diagnosed. 4492 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments) 4493 << AttrName 4494 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc)); 4495 Attr.setInvalid(true); 4496 } 4497 } 4498 return true; 4499 } 4500 4501 /// Parse a C++11 or C23 attribute-specifier. 4502 /// 4503 /// [C++11] attribute-specifier: 4504 /// '[' '[' attribute-list ']' ']' 4505 /// alignment-specifier 4506 /// 4507 /// [C++11] attribute-list: 4508 /// attribute[opt] 4509 /// attribute-list ',' attribute[opt] 4510 /// attribute '...' 4511 /// attribute-list ',' attribute '...' 4512 /// 4513 /// [C++11] attribute: 4514 /// attribute-token attribute-argument-clause[opt] 4515 /// 4516 /// [C++11] attribute-token: 4517 /// identifier 4518 /// attribute-scoped-token 4519 /// 4520 /// [C++11] attribute-scoped-token: 4521 /// attribute-namespace '::' identifier 4522 /// 4523 /// [C++11] attribute-namespace: 4524 /// identifier 4525 void Parser::ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs, 4526 CachedTokens &OpenMPTokens, 4527 SourceLocation *EndLoc) { 4528 if (Tok.is(tok::kw_alignas)) { 4529 if (getLangOpts().C23) 4530 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName(); 4531 else 4532 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas); 4533 ParseAlignmentSpecifier(Attrs, EndLoc); 4534 return; 4535 } 4536 4537 if (Tok.isRegularKeywordAttribute()) { 4538 SourceLocation Loc = Tok.getLocation(); 4539 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 4540 Attrs.addNew(AttrName, Loc, nullptr, Loc, nullptr, 0, Tok.getKind()); 4541 ConsumeToken(); 4542 return; 4543 } 4544 4545 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) && 4546 "Not a double square bracket attribute list"); 4547 4548 SourceLocation OpenLoc = Tok.getLocation(); 4549 if (getLangOpts().CPlusPlus) { 4550 Diag(OpenLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_attribute 4551 : diag::warn_ext_cxx11_attributes); 4552 } else { 4553 Diag(OpenLoc, getLangOpts().C23 ? diag::warn_pre_c23_compat_attributes 4554 : diag::warn_ext_c23_attributes); 4555 } 4556 4557 ConsumeBracket(); 4558 checkCompoundToken(OpenLoc, tok::l_square, CompoundToken::AttrBegin); 4559 ConsumeBracket(); 4560 4561 SourceLocation CommonScopeLoc; 4562 IdentifierInfo *CommonScopeName = nullptr; 4563 if (Tok.is(tok::kw_using)) { 4564 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 4565 ? diag::warn_cxx14_compat_using_attribute_ns 4566 : diag::ext_using_attribute_ns); 4567 ConsumeToken(); 4568 4569 CommonScopeName = TryParseCXX11AttributeIdentifier( 4570 CommonScopeLoc, Sema::AttributeCompletion::Scope); 4571 if (!CommonScopeName) { 4572 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 4573 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch); 4574 } 4575 if (!TryConsumeToken(tok::colon) && CommonScopeName) 4576 Diag(Tok.getLocation(), diag::err_expected) << tok::colon; 4577 } 4578 4579 bool AttrParsed = false; 4580 while (!Tok.isOneOf(tok::r_square, tok::semi, tok::eof)) { 4581 if (AttrParsed) { 4582 // If we parsed an attribute, a comma is required before parsing any 4583 // additional attributes. 4584 if (ExpectAndConsume(tok::comma)) { 4585 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch); 4586 continue; 4587 } 4588 AttrParsed = false; 4589 } 4590 4591 // Eat all remaining superfluous commas before parsing the next attribute. 4592 while (TryConsumeToken(tok::comma)) 4593 ; 4594 4595 SourceLocation ScopeLoc, AttrLoc; 4596 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr; 4597 4598 AttrName = TryParseCXX11AttributeIdentifier( 4599 AttrLoc, Sema::AttributeCompletion::Attribute, CommonScopeName); 4600 if (!AttrName) 4601 // Break out to the "expected ']'" diagnostic. 4602 break; 4603 4604 // scoped attribute 4605 if (TryConsumeToken(tok::coloncolon)) { 4606 ScopeName = AttrName; 4607 ScopeLoc = AttrLoc; 4608 4609 AttrName = TryParseCXX11AttributeIdentifier( 4610 AttrLoc, Sema::AttributeCompletion::Attribute, ScopeName); 4611 if (!AttrName) { 4612 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; 4613 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch); 4614 continue; 4615 } 4616 } 4617 4618 if (CommonScopeName) { 4619 if (ScopeName) { 4620 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict) 4621 << SourceRange(CommonScopeLoc); 4622 } else { 4623 ScopeName = CommonScopeName; 4624 ScopeLoc = CommonScopeLoc; 4625 } 4626 } 4627 4628 // Parse attribute arguments 4629 if (Tok.is(tok::l_paren)) 4630 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, Attrs, EndLoc, 4631 ScopeName, ScopeLoc, OpenMPTokens); 4632 4633 if (!AttrParsed) { 4634 Attrs.addNew( 4635 AttrName, 4636 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc), 4637 ScopeName, ScopeLoc, nullptr, 0, 4638 getLangOpts().CPlusPlus ? ParsedAttr::Form::CXX11() 4639 : ParsedAttr::Form::C23()); 4640 AttrParsed = true; 4641 } 4642 4643 if (TryConsumeToken(tok::ellipsis)) 4644 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis) << AttrName; 4645 } 4646 4647 // If we hit an error and recovered by parsing up to a semicolon, eat the 4648 // semicolon and don't issue further diagnostics about missing brackets. 4649 if (Tok.is(tok::semi)) { 4650 ConsumeToken(); 4651 return; 4652 } 4653 4654 SourceLocation CloseLoc = Tok.getLocation(); 4655 if (ExpectAndConsume(tok::r_square)) 4656 SkipUntil(tok::r_square); 4657 else if (Tok.is(tok::r_square)) 4658 checkCompoundToken(CloseLoc, tok::r_square, CompoundToken::AttrEnd); 4659 if (EndLoc) 4660 *EndLoc = Tok.getLocation(); 4661 if (ExpectAndConsume(tok::r_square)) 4662 SkipUntil(tok::r_square); 4663 } 4664 4665 /// ParseCXX11Attributes - Parse a C++11 or C23 attribute-specifier-seq. 4666 /// 4667 /// attribute-specifier-seq: 4668 /// attribute-specifier-seq[opt] attribute-specifier 4669 void Parser::ParseCXX11Attributes(ParsedAttributes &Attrs) { 4670 SourceLocation StartLoc = Tok.getLocation(); 4671 SourceLocation EndLoc = StartLoc; 4672 4673 do { 4674 ParseCXX11AttributeSpecifier(Attrs, &EndLoc); 4675 } while (isAllowedCXX11AttributeSpecifier()); 4676 4677 Attrs.Range = SourceRange(StartLoc, EndLoc); 4678 } 4679 4680 void Parser::DiagnoseAndSkipCXX11Attributes() { 4681 auto Keyword = 4682 Tok.isRegularKeywordAttribute() ? Tok.getIdentifierInfo() : nullptr; 4683 // Start and end location of an attribute or an attribute list. 4684 SourceLocation StartLoc = Tok.getLocation(); 4685 SourceLocation EndLoc = SkipCXX11Attributes(); 4686 4687 if (EndLoc.isValid()) { 4688 SourceRange Range(StartLoc, EndLoc); 4689 (Keyword ? Diag(StartLoc, diag::err_keyword_not_allowed) << Keyword 4690 : Diag(StartLoc, diag::err_attributes_not_allowed)) 4691 << Range; 4692 } 4693 } 4694 4695 SourceLocation Parser::SkipCXX11Attributes() { 4696 SourceLocation EndLoc; 4697 4698 if (!isCXX11AttributeSpecifier()) 4699 return EndLoc; 4700 4701 do { 4702 if (Tok.is(tok::l_square)) { 4703 BalancedDelimiterTracker T(*this, tok::l_square); 4704 T.consumeOpen(); 4705 T.skipToEnd(); 4706 EndLoc = T.getCloseLocation(); 4707 } else if (Tok.isRegularKeywordAttribute()) { 4708 EndLoc = Tok.getLocation(); 4709 ConsumeToken(); 4710 } else { 4711 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier"); 4712 ConsumeToken(); 4713 BalancedDelimiterTracker T(*this, tok::l_paren); 4714 if (!T.consumeOpen()) 4715 T.skipToEnd(); 4716 EndLoc = T.getCloseLocation(); 4717 } 4718 } while (isCXX11AttributeSpecifier()); 4719 4720 return EndLoc; 4721 } 4722 4723 /// Parse uuid() attribute when it appears in a [] Microsoft attribute. 4724 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) { 4725 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list"); 4726 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo(); 4727 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list"); 4728 4729 SourceLocation UuidLoc = Tok.getLocation(); 4730 ConsumeToken(); 4731 4732 // Ignore the left paren location for now. 4733 BalancedDelimiterTracker T(*this, tok::l_paren); 4734 if (T.consumeOpen()) { 4735 Diag(Tok, diag::err_expected) << tok::l_paren; 4736 return; 4737 } 4738 4739 ArgsVector ArgExprs; 4740 if (isTokenStringLiteral()) { 4741 // Easy case: uuid("...") -- quoted string. 4742 ExprResult StringResult = ParseUnevaluatedStringLiteralExpression(); 4743 if (StringResult.isInvalid()) 4744 return; 4745 ArgExprs.push_back(StringResult.get()); 4746 } else { 4747 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no 4748 // quotes in the parens. Just append the spelling of all tokens encountered 4749 // until the closing paren. 4750 4751 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul 4752 StrBuffer += "\""; 4753 4754 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace, 4755 // tok::r_brace, tok::minus, tok::identifier (think C000) and 4756 // tok::numeric_constant (0000) should be enough. But the spelling of the 4757 // uuid argument is checked later anyways, so there's no harm in accepting 4758 // almost anything here. 4759 // cl is very strict about whitespace in this form and errors out if any 4760 // is present, so check the space flags on the tokens. 4761 SourceLocation StartLoc = Tok.getLocation(); 4762 while (Tok.isNot(tok::r_paren)) { 4763 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) { 4764 Diag(Tok, diag::err_attribute_uuid_malformed_guid); 4765 SkipUntil(tok::r_paren, StopAtSemi); 4766 return; 4767 } 4768 SmallString<16> SpellingBuffer; 4769 SpellingBuffer.resize(Tok.getLength() + 1); 4770 bool Invalid = false; 4771 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 4772 if (Invalid) { 4773 SkipUntil(tok::r_paren, StopAtSemi); 4774 return; 4775 } 4776 StrBuffer += TokSpelling; 4777 ConsumeAnyToken(); 4778 } 4779 StrBuffer += "\""; 4780 4781 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) { 4782 Diag(Tok, diag::err_attribute_uuid_malformed_guid); 4783 ConsumeParen(); 4784 return; 4785 } 4786 4787 // Pretend the user wrote the appropriate string literal here. 4788 // ActOnStringLiteral() copies the string data into the literal, so it's 4789 // ok that the Token points to StrBuffer. 4790 Token Toks[1]; 4791 Toks[0].startToken(); 4792 Toks[0].setKind(tok::string_literal); 4793 Toks[0].setLocation(StartLoc); 4794 Toks[0].setLiteralData(StrBuffer.data()); 4795 Toks[0].setLength(StrBuffer.size()); 4796 StringLiteral *UuidString = 4797 cast<StringLiteral>(Actions.ActOnUnevaluatedStringLiteral(Toks).get()); 4798 ArgExprs.push_back(UuidString); 4799 } 4800 4801 if (!T.consumeClose()) { 4802 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr, 4803 SourceLocation(), ArgExprs.data(), ArgExprs.size(), 4804 ParsedAttr::Form::Microsoft()); 4805 } 4806 } 4807 4808 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr] 4809 /// 4810 /// [MS] ms-attribute: 4811 /// '[' token-seq ']' 4812 /// 4813 /// [MS] ms-attribute-seq: 4814 /// ms-attribute[opt] 4815 /// ms-attribute ms-attribute-seq 4816 void Parser::ParseMicrosoftAttributes(ParsedAttributes &Attrs) { 4817 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list"); 4818 4819 SourceLocation StartLoc = Tok.getLocation(); 4820 SourceLocation EndLoc = StartLoc; 4821 do { 4822 // FIXME: If this is actually a C++11 attribute, parse it as one. 4823 BalancedDelimiterTracker T(*this, tok::l_square); 4824 T.consumeOpen(); 4825 4826 // Skip most ms attributes except for a specific list. 4827 while (true) { 4828 SkipUntil(tok::r_square, tok::identifier, 4829 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); 4830 if (Tok.is(tok::code_completion)) { 4831 cutOffParsing(); 4832 Actions.CodeCompleteAttribute(AttributeCommonInfo::AS_Microsoft, 4833 Sema::AttributeCompletion::Attribute, 4834 /*Scope=*/nullptr); 4835 break; 4836 } 4837 if (Tok.isNot(tok::identifier)) // ']', but also eof 4838 break; 4839 if (Tok.getIdentifierInfo()->getName() == "uuid") 4840 ParseMicrosoftUuidAttributeArgs(Attrs); 4841 else { 4842 IdentifierInfo *II = Tok.getIdentifierInfo(); 4843 SourceLocation NameLoc = Tok.getLocation(); 4844 ConsumeToken(); 4845 ParsedAttr::Kind AttrKind = 4846 ParsedAttr::getParsedKind(II, nullptr, ParsedAttr::AS_Microsoft); 4847 // For HLSL we want to handle all attributes, but for MSVC compat, we 4848 // silently ignore unknown Microsoft attributes. 4849 if (getLangOpts().HLSL || AttrKind != ParsedAttr::UnknownAttribute) { 4850 bool AttrParsed = false; 4851 if (Tok.is(tok::l_paren)) { 4852 CachedTokens OpenMPTokens; 4853 AttrParsed = 4854 ParseCXX11AttributeArgs(II, NameLoc, Attrs, &EndLoc, nullptr, 4855 SourceLocation(), OpenMPTokens); 4856 ReplayOpenMPAttributeTokens(OpenMPTokens); 4857 } 4858 if (!AttrParsed) { 4859 Attrs.addNew(II, NameLoc, nullptr, SourceLocation(), nullptr, 0, 4860 ParsedAttr::Form::Microsoft()); 4861 } 4862 } 4863 } 4864 } 4865 4866 T.consumeClose(); 4867 EndLoc = T.getCloseLocation(); 4868 } while (Tok.is(tok::l_square)); 4869 4870 Attrs.Range = SourceRange(StartLoc, EndLoc); 4871 } 4872 4873 void Parser::ParseMicrosoftIfExistsClassDeclaration( 4874 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, 4875 AccessSpecifier &CurAS) { 4876 IfExistsCondition Result; 4877 if (ParseMicrosoftIfExistsCondition(Result)) 4878 return; 4879 4880 BalancedDelimiterTracker Braces(*this, tok::l_brace); 4881 if (Braces.consumeOpen()) { 4882 Diag(Tok, diag::err_expected) << tok::l_brace; 4883 return; 4884 } 4885 4886 switch (Result.Behavior) { 4887 case IEB_Parse: 4888 // Parse the declarations below. 4889 break; 4890 4891 case IEB_Dependent: 4892 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) 4893 << Result.IsIfExists; 4894 // Fall through to skip. 4895 [[fallthrough]]; 4896 4897 case IEB_Skip: 4898 Braces.skipToEnd(); 4899 return; 4900 } 4901 4902 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 4903 // __if_exists, __if_not_exists can nest. 4904 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) { 4905 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, CurAS); 4906 continue; 4907 } 4908 4909 // Check for extraneous top-level semicolon. 4910 if (Tok.is(tok::semi)) { 4911 ConsumeExtraSemi(InsideStruct, TagType); 4912 continue; 4913 } 4914 4915 AccessSpecifier AS = getAccessSpecifierIfPresent(); 4916 if (AS != AS_none) { 4917 // Current token is a C++ access specifier. 4918 CurAS = AS; 4919 SourceLocation ASLoc = Tok.getLocation(); 4920 ConsumeToken(); 4921 if (Tok.is(tok::colon)) 4922 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(), 4923 ParsedAttributesView{}); 4924 else 4925 Diag(Tok, diag::err_expected) << tok::colon; 4926 ConsumeToken(); 4927 continue; 4928 } 4929 4930 // Parse all the comma separated declarators. 4931 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs); 4932 } 4933 4934 Braces.consumeClose(); 4935 } 4936