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