1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the C++ Declaration portions of the Parser interfaces. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Basic/OperatorKinds.h" 15 #include "clang/Parse/Parser.h" 16 #include "clang/Parse/ParseDiagnostic.h" 17 #include "clang/Sema/DeclSpec.h" 18 #include "clang/Sema/Scope.h" 19 #include "clang/Sema/ParsedTemplate.h" 20 #include "clang/Sema/PrettyDeclStackTrace.h" 21 #include "llvm/ADT/SmallString.h" 22 #include "RAIIObjectsForParser.h" 23 using namespace clang; 24 25 /// ParseNamespace - We know that the current token is a namespace keyword. This 26 /// may either be a top level namespace or a block-level namespace alias. If 27 /// there was an inline keyword, it has already been parsed. 28 /// 29 /// namespace-definition: [C++ 7.3: basic.namespace] 30 /// named-namespace-definition 31 /// unnamed-namespace-definition 32 /// 33 /// unnamed-namespace-definition: 34 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}' 35 /// 36 /// named-namespace-definition: 37 /// original-namespace-definition 38 /// extension-namespace-definition 39 /// 40 /// original-namespace-definition: 41 /// 'inline'[opt] 'namespace' identifier attributes[opt] 42 /// '{' namespace-body '}' 43 /// 44 /// extension-namespace-definition: 45 /// 'inline'[opt] 'namespace' original-namespace-name 46 /// '{' namespace-body '}' 47 /// 48 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias] 49 /// 'namespace' identifier '=' qualified-namespace-specifier ';' 50 /// 51 Decl *Parser::ParseNamespace(unsigned Context, 52 SourceLocation &DeclEnd, 53 SourceLocation InlineLoc) { 54 assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); 55 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. 56 ObjCDeclContextSwitch ObjCDC(*this); 57 58 if (Tok.is(tok::code_completion)) { 59 Actions.CodeCompleteNamespaceDecl(getCurScope()); 60 cutOffParsing(); 61 return 0; 62 } 63 64 SourceLocation IdentLoc; 65 IdentifierInfo *Ident = 0; 66 std::vector<SourceLocation> ExtraIdentLoc; 67 std::vector<IdentifierInfo*> ExtraIdent; 68 std::vector<SourceLocation> ExtraNamespaceLoc; 69 70 Token attrTok; 71 72 if (Tok.is(tok::identifier)) { 73 Ident = Tok.getIdentifierInfo(); 74 IdentLoc = ConsumeToken(); // eat the identifier. 75 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) { 76 ExtraNamespaceLoc.push_back(ConsumeToken()); 77 ExtraIdent.push_back(Tok.getIdentifierInfo()); 78 ExtraIdentLoc.push_back(ConsumeToken()); 79 } 80 } 81 82 // Read label attributes, if present. 83 ParsedAttributes attrs(AttrFactory); 84 if (Tok.is(tok::kw___attribute)) { 85 attrTok = Tok; 86 ParseGNUAttributes(attrs); 87 } 88 89 if (Tok.is(tok::equal)) { 90 if (!attrs.empty()) 91 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias); 92 if (InlineLoc.isValid()) 93 Diag(InlineLoc, diag::err_inline_namespace_alias) 94 << FixItHint::CreateRemoval(InlineLoc); 95 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd); 96 } 97 98 99 BalancedDelimiterTracker T(*this, tok::l_brace); 100 if (T.consumeOpen()) { 101 if (!ExtraIdent.empty()) { 102 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 103 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 104 } 105 Diag(Tok, Ident ? diag::err_expected_lbrace : 106 diag::err_expected_ident_lbrace); 107 return 0; 108 } 109 110 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || 111 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || 112 getCurScope()->getFnParent()) { 113 if (!ExtraIdent.empty()) { 114 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 115 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 116 } 117 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope); 118 SkipUntil(tok::r_brace, false); 119 return 0; 120 } 121 122 if (!ExtraIdent.empty()) { 123 TentativeParsingAction TPA(*this); 124 SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true); 125 Token rBraceToken = Tok; 126 TPA.Revert(); 127 128 if (!rBraceToken.is(tok::r_brace)) { 129 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 130 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); 131 } else { 132 std::string NamespaceFix; 133 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(), 134 E = ExtraIdent.end(); I != E; ++I) { 135 NamespaceFix += " { namespace "; 136 NamespaceFix += (*I)->getName(); 137 } 138 139 std::string RBraces; 140 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i) 141 RBraces += "} "; 142 143 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon) 144 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(), 145 ExtraIdentLoc.back()), 146 NamespaceFix) 147 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces); 148 } 149 } 150 151 // If we're still good, complain about inline namespaces in non-C++0x now. 152 if (InlineLoc.isValid()) 153 Diag(InlineLoc, getLangOpts().CPlusPlus0x ? 154 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace); 155 156 // Enter a scope for the namespace. 157 ParseScope NamespaceScope(this, Scope::DeclScope); 158 159 Decl *NamespcDecl = 160 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc, 161 IdentLoc, Ident, T.getOpenLocation(), 162 attrs.getList()); 163 164 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc, 165 "parsing namespace"); 166 167 // Parse the contents of the namespace. This includes parsing recovery on 168 // any improperly nested namespaces. 169 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0, 170 InlineLoc, attrs, T); 171 172 // Leave the namespace scope. 173 NamespaceScope.Exit(); 174 175 DeclEnd = T.getCloseLocation(); 176 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd); 177 178 return NamespcDecl; 179 } 180 181 /// ParseInnerNamespace - Parse the contents of a namespace. 182 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc, 183 std::vector<IdentifierInfo*>& Ident, 184 std::vector<SourceLocation>& NamespaceLoc, 185 unsigned int index, SourceLocation& InlineLoc, 186 ParsedAttributes& attrs, 187 BalancedDelimiterTracker &Tracker) { 188 if (index == Ident.size()) { 189 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 190 ParsedAttributesWithRange attrs(AttrFactory); 191 MaybeParseCXX0XAttributes(attrs); 192 MaybeParseMicrosoftAttributes(attrs); 193 ParseExternalDeclaration(attrs); 194 } 195 196 // The caller is what called check -- we are simply calling 197 // the close for it. 198 Tracker.consumeClose(); 199 200 return; 201 } 202 203 // Parse improperly nested namespaces. 204 ParseScope NamespaceScope(this, Scope::DeclScope); 205 Decl *NamespcDecl = 206 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(), 207 NamespaceLoc[index], IdentLoc[index], 208 Ident[index], Tracker.getOpenLocation(), 209 attrs.getList()); 210 211 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc, 212 attrs, Tracker); 213 214 NamespaceScope.Exit(); 215 216 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation()); 217 } 218 219 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace 220 /// alias definition. 221 /// 222 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, 223 SourceLocation AliasLoc, 224 IdentifierInfo *Alias, 225 SourceLocation &DeclEnd) { 226 assert(Tok.is(tok::equal) && "Not equal token"); 227 228 ConsumeToken(); // eat the '='. 229 230 if (Tok.is(tok::code_completion)) { 231 Actions.CodeCompleteNamespaceAliasDecl(getCurScope()); 232 cutOffParsing(); 233 return 0; 234 } 235 236 CXXScopeSpec SS; 237 // Parse (optional) nested-name-specifier. 238 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 239 240 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 241 Diag(Tok, diag::err_expected_namespace_name); 242 // Skip to end of the definition and eat the ';'. 243 SkipUntil(tok::semi); 244 return 0; 245 } 246 247 // Parse identifier. 248 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 249 SourceLocation IdentLoc = ConsumeToken(); 250 251 // Eat the ';'. 252 DeclEnd = Tok.getLocation(); 253 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name, 254 "", tok::semi); 255 256 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias, 257 SS, IdentLoc, Ident); 258 } 259 260 /// ParseLinkage - We know that the current token is a string_literal 261 /// and just before that, that extern was seen. 262 /// 263 /// linkage-specification: [C++ 7.5p2: dcl.link] 264 /// 'extern' string-literal '{' declaration-seq[opt] '}' 265 /// 'extern' string-literal declaration 266 /// 267 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) { 268 assert(Tok.is(tok::string_literal) && "Not a string literal!"); 269 SmallString<8> LangBuffer; 270 bool Invalid = false; 271 StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid); 272 if (Invalid) 273 return 0; 274 275 // FIXME: This is incorrect: linkage-specifiers are parsed in translation 276 // phase 7, so string-literal concatenation is supposed to occur. 277 // extern "" "C" "" "+" "+" { } is legal. 278 if (Tok.hasUDSuffix()) 279 Diag(Tok, diag::err_invalid_string_udl); 280 SourceLocation Loc = ConsumeStringToken(); 281 282 ParseScope LinkageScope(this, Scope::DeclScope); 283 Decl *LinkageSpec 284 = Actions.ActOnStartLinkageSpecification(getCurScope(), 285 DS.getSourceRange().getBegin(), 286 Loc, Lang, 287 Tok.is(tok::l_brace) ? Tok.getLocation() 288 : SourceLocation()); 289 290 ParsedAttributesWithRange attrs(AttrFactory); 291 MaybeParseCXX0XAttributes(attrs); 292 MaybeParseMicrosoftAttributes(attrs); 293 294 if (Tok.isNot(tok::l_brace)) { 295 // Reset the source range in DS, as the leading "extern" 296 // does not really belong to the inner declaration ... 297 DS.SetRangeStart(SourceLocation()); 298 DS.SetRangeEnd(SourceLocation()); 299 // ... but anyway remember that such an "extern" was seen. 300 DS.setExternInLinkageSpec(true); 301 ParseExternalDeclaration(attrs, &DS); 302 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, 303 SourceLocation()); 304 } 305 306 DS.abort(); 307 308 ProhibitAttributes(attrs); 309 310 BalancedDelimiterTracker T(*this, tok::l_brace); 311 T.consumeOpen(); 312 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 313 ParsedAttributesWithRange attrs(AttrFactory); 314 MaybeParseCXX0XAttributes(attrs); 315 MaybeParseMicrosoftAttributes(attrs); 316 ParseExternalDeclaration(attrs); 317 } 318 319 T.consumeClose(); 320 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, 321 T.getCloseLocation()); 322 } 323 324 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or 325 /// using-directive. Assumes that current token is 'using'. 326 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context, 327 const ParsedTemplateInfo &TemplateInfo, 328 SourceLocation &DeclEnd, 329 ParsedAttributesWithRange &attrs, 330 Decl **OwnedType) { 331 assert(Tok.is(tok::kw_using) && "Not using token"); 332 ObjCDeclContextSwitch ObjCDC(*this); 333 334 // Eat 'using'. 335 SourceLocation UsingLoc = ConsumeToken(); 336 337 if (Tok.is(tok::code_completion)) { 338 Actions.CodeCompleteUsing(getCurScope()); 339 cutOffParsing(); 340 return 0; 341 } 342 343 // 'using namespace' means this is a using-directive. 344 if (Tok.is(tok::kw_namespace)) { 345 // Template parameters are always an error here. 346 if (TemplateInfo.Kind) { 347 SourceRange R = TemplateInfo.getSourceRange(); 348 Diag(UsingLoc, diag::err_templated_using_directive) 349 << R << FixItHint::CreateRemoval(R); 350 } 351 352 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs); 353 } 354 355 // Otherwise, it must be a using-declaration or an alias-declaration. 356 357 // Using declarations can't have attributes. 358 ProhibitAttributes(attrs); 359 360 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd, 361 AS_none, OwnedType); 362 } 363 364 /// ParseUsingDirective - Parse C++ using-directive, assumes 365 /// that current token is 'namespace' and 'using' was already parsed. 366 /// 367 /// using-directive: [C++ 7.3.p4: namespace.udir] 368 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 369 /// namespace-name ; 370 /// [GNU] using-directive: 371 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 372 /// namespace-name attributes[opt] ; 373 /// 374 Decl *Parser::ParseUsingDirective(unsigned Context, 375 SourceLocation UsingLoc, 376 SourceLocation &DeclEnd, 377 ParsedAttributes &attrs) { 378 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token"); 379 380 // Eat 'namespace'. 381 SourceLocation NamespcLoc = ConsumeToken(); 382 383 if (Tok.is(tok::code_completion)) { 384 Actions.CodeCompleteUsingDirective(getCurScope()); 385 cutOffParsing(); 386 return 0; 387 } 388 389 CXXScopeSpec SS; 390 // Parse (optional) nested-name-specifier. 391 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 392 393 IdentifierInfo *NamespcName = 0; 394 SourceLocation IdentLoc = SourceLocation(); 395 396 // Parse namespace-name. 397 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 398 Diag(Tok, diag::err_expected_namespace_name); 399 // If there was invalid namespace name, skip to end of decl, and eat ';'. 400 SkipUntil(tok::semi); 401 // FIXME: Are there cases, when we would like to call ActOnUsingDirective? 402 return 0; 403 } 404 405 // Parse identifier. 406 NamespcName = Tok.getIdentifierInfo(); 407 IdentLoc = ConsumeToken(); 408 409 // Parse (optional) attributes (most likely GNU strong-using extension). 410 bool GNUAttr = false; 411 if (Tok.is(tok::kw___attribute)) { 412 GNUAttr = true; 413 ParseGNUAttributes(attrs); 414 } 415 416 // Eat ';'. 417 DeclEnd = Tok.getLocation(); 418 ExpectAndConsume(tok::semi, 419 GNUAttr ? diag::err_expected_semi_after_attribute_list 420 : diag::err_expected_semi_after_namespace_name, 421 "", tok::semi); 422 423 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS, 424 IdentLoc, NamespcName, attrs.getList()); 425 } 426 427 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration. 428 /// Assumes that 'using' was already seen. 429 /// 430 /// using-declaration: [C++ 7.3.p3: namespace.udecl] 431 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier 432 /// unqualified-id 433 /// 'using' :: unqualified-id 434 /// 435 /// alias-declaration: C++0x [decl.typedef]p2 436 /// 'using' identifier = type-id ; 437 /// 438 Decl *Parser::ParseUsingDeclaration(unsigned Context, 439 const ParsedTemplateInfo &TemplateInfo, 440 SourceLocation UsingLoc, 441 SourceLocation &DeclEnd, 442 AccessSpecifier AS, 443 Decl **OwnedType) { 444 CXXScopeSpec SS; 445 SourceLocation TypenameLoc; 446 bool IsTypeName; 447 ParsedAttributesWithRange attrs(AttrFactory); 448 449 // FIXME: Simply skip the attributes and diagnose, don't bother parsing them. 450 MaybeParseCXX0XAttributes(attrs); 451 ProhibitAttributes(attrs); 452 attrs.clear(); 453 attrs.Range = SourceRange(); 454 455 // Ignore optional 'typename'. 456 // FIXME: This is wrong; we should parse this as a typename-specifier. 457 if (Tok.is(tok::kw_typename)) { 458 TypenameLoc = Tok.getLocation(); 459 ConsumeToken(); 460 IsTypeName = true; 461 } 462 else 463 IsTypeName = false; 464 465 // Parse nested-name-specifier. 466 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 467 468 // Check nested-name specifier. 469 if (SS.isInvalid()) { 470 SkipUntil(tok::semi); 471 return 0; 472 } 473 474 // Parse the unqualified-id. We allow parsing of both constructor and 475 // destructor names and allow the action module to diagnose any semantic 476 // errors. 477 SourceLocation TemplateKWLoc; 478 UnqualifiedId Name; 479 if (ParseUnqualifiedId(SS, 480 /*EnteringContext=*/false, 481 /*AllowDestructorName=*/true, 482 /*AllowConstructorName=*/true, 483 ParsedType(), 484 TemplateKWLoc, 485 Name)) { 486 SkipUntil(tok::semi); 487 return 0; 488 } 489 490 MaybeParseCXX0XAttributes(attrs); 491 492 // Maybe this is an alias-declaration. 493 bool IsAliasDecl = Tok.is(tok::equal); 494 TypeResult TypeAlias; 495 if (IsAliasDecl) { 496 // TODO: Attribute support. C++0x attributes may appear before the equals. 497 // Where can GNU attributes appear? 498 ConsumeToken(); 499 500 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ? 501 diag::warn_cxx98_compat_alias_declaration : 502 diag::ext_alias_declaration); 503 504 // Type alias templates cannot be specialized. 505 int SpecKind = -1; 506 if (TemplateInfo.Kind == ParsedTemplateInfo::Template && 507 Name.getKind() == UnqualifiedId::IK_TemplateId) 508 SpecKind = 0; 509 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) 510 SpecKind = 1; 511 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 512 SpecKind = 2; 513 if (SpecKind != -1) { 514 SourceRange Range; 515 if (SpecKind == 0) 516 Range = SourceRange(Name.TemplateId->LAngleLoc, 517 Name.TemplateId->RAngleLoc); 518 else 519 Range = TemplateInfo.getSourceRange(); 520 Diag(Range.getBegin(), diag::err_alias_declaration_specialization) 521 << SpecKind << Range; 522 SkipUntil(tok::semi); 523 return 0; 524 } 525 526 // Name must be an identifier. 527 if (Name.getKind() != UnqualifiedId::IK_Identifier) { 528 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier); 529 // No removal fixit: can't recover from this. 530 SkipUntil(tok::semi); 531 return 0; 532 } else if (IsTypeName) 533 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier) 534 << FixItHint::CreateRemoval(SourceRange(TypenameLoc, 535 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc)); 536 else if (SS.isNotEmpty()) 537 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier) 538 << FixItHint::CreateRemoval(SS.getRange()); 539 540 TypeAlias = ParseTypeName(0, TemplateInfo.Kind ? 541 Declarator::AliasTemplateContext : 542 Declarator::AliasDeclContext, AS, OwnedType); 543 } else { 544 // C++11 attributes are not allowed on a using-declaration, but GNU ones 545 // are. 546 ProhibitAttributes(attrs); 547 548 // Parse (optional) attributes (most likely GNU strong-using extension). 549 MaybeParseGNUAttributes(attrs); 550 } 551 552 // Eat ';'. 553 DeclEnd = Tok.getLocation(); 554 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 555 !attrs.empty() ? "attributes list" : 556 IsAliasDecl ? "alias declaration" : "using declaration", 557 tok::semi); 558 559 // Diagnose an attempt to declare a templated using-declaration. 560 // In C++0x, alias-declarations can be templates: 561 // template <...> using id = type; 562 if (TemplateInfo.Kind && !IsAliasDecl) { 563 SourceRange R = TemplateInfo.getSourceRange(); 564 Diag(UsingLoc, diag::err_templated_using_declaration) 565 << R << FixItHint::CreateRemoval(R); 566 567 // Unfortunately, we have to bail out instead of recovering by 568 // ignoring the parameters, just in case the nested name specifier 569 // depends on the parameters. 570 return 0; 571 } 572 573 // "typename" keyword is allowed for identifiers only, 574 // because it may be a type definition. 575 if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) { 576 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only) 577 << FixItHint::CreateRemoval(SourceRange(TypenameLoc)); 578 // Proceed parsing, but reset the IsTypeName flag. 579 IsTypeName = false; 580 } 581 582 if (IsAliasDecl) { 583 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 584 MultiTemplateParamsArg TemplateParamsArg( 585 TemplateParams ? TemplateParams->data() : 0, 586 TemplateParams ? TemplateParams->size() : 0); 587 // FIXME: Propagate attributes. 588 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg, 589 UsingLoc, Name, TypeAlias); 590 } 591 592 return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS, 593 Name, attrs.getList(), 594 IsTypeName, TypenameLoc); 595 } 596 597 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration. 598 /// 599 /// [C++0x] static_assert-declaration: 600 /// static_assert ( constant-expression , string-literal ) ; 601 /// 602 /// [C11] static_assert-declaration: 603 /// _Static_assert ( constant-expression , string-literal ) ; 604 /// 605 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ 606 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) && 607 "Not a static_assert declaration"); 608 609 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11) 610 Diag(Tok, diag::ext_c11_static_assert); 611 if (Tok.is(tok::kw_static_assert)) 612 Diag(Tok, diag::warn_cxx98_compat_static_assert); 613 614 SourceLocation StaticAssertLoc = ConsumeToken(); 615 616 BalancedDelimiterTracker T(*this, tok::l_paren); 617 if (T.consumeOpen()) { 618 Diag(Tok, diag::err_expected_lparen); 619 return 0; 620 } 621 622 ExprResult AssertExpr(ParseConstantExpression()); 623 if (AssertExpr.isInvalid()) { 624 SkipUntil(tok::semi); 625 return 0; 626 } 627 628 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi)) 629 return 0; 630 631 if (!isTokenStringLiteral()) { 632 Diag(Tok, diag::err_expected_string_literal); 633 SkipUntil(tok::semi); 634 return 0; 635 } 636 637 ExprResult AssertMessage(ParseStringLiteralExpression()); 638 if (AssertMessage.isInvalid()) { 639 SkipUntil(tok::semi); 640 return 0; 641 } 642 643 T.consumeClose(); 644 645 DeclEnd = Tok.getLocation(); 646 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert); 647 648 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, 649 AssertExpr.take(), 650 AssertMessage.take(), 651 T.getCloseLocation()); 652 } 653 654 /// ParseDecltypeSpecifier - Parse a C++0x decltype specifier. 655 /// 656 /// 'decltype' ( expression ) 657 /// 658 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) { 659 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) 660 && "Not a decltype specifier"); 661 662 663 ExprResult Result; 664 SourceLocation StartLoc = Tok.getLocation(); 665 SourceLocation EndLoc; 666 667 if (Tok.is(tok::annot_decltype)) { 668 Result = getExprAnnotation(Tok); 669 EndLoc = Tok.getAnnotationEndLoc(); 670 ConsumeToken(); 671 if (Result.isInvalid()) { 672 DS.SetTypeSpecError(); 673 return EndLoc; 674 } 675 } else { 676 if (Tok.getIdentifierInfo()->isStr("decltype")) 677 Diag(Tok, diag::warn_cxx98_compat_decltype); 678 679 ConsumeToken(); 680 681 BalancedDelimiterTracker T(*this, tok::l_paren); 682 if (T.expectAndConsume(diag::err_expected_lparen_after, 683 "decltype", tok::r_paren)) { 684 DS.SetTypeSpecError(); 685 return T.getOpenLocation() == Tok.getLocation() ? 686 StartLoc : T.getOpenLocation(); 687 } 688 689 // Parse the expression 690 691 // C++0x [dcl.type.simple]p4: 692 // The operand of the decltype specifier is an unevaluated operand. 693 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 694 0, /*IsDecltype=*/true); 695 Result = ParseExpression(); 696 if (Result.isInvalid()) { 697 SkipUntil(tok::r_paren); 698 DS.SetTypeSpecError(); 699 return StartLoc; 700 } 701 702 // Match the ')' 703 T.consumeClose(); 704 if (T.getCloseLocation().isInvalid()) { 705 DS.SetTypeSpecError(); 706 // FIXME: this should return the location of the last token 707 // that was consumed (by "consumeClose()") 708 return T.getCloseLocation(); 709 } 710 711 Result = Actions.ActOnDecltypeExpression(Result.take()); 712 if (Result.isInvalid()) { 713 DS.SetTypeSpecError(); 714 return T.getCloseLocation(); 715 } 716 717 EndLoc = T.getCloseLocation(); 718 } 719 720 const char *PrevSpec = 0; 721 unsigned DiagID; 722 // Check for duplicate type specifiers (e.g. "int decltype(a)"). 723 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, 724 DiagID, Result.release())) { 725 Diag(StartLoc, DiagID) << PrevSpec; 726 DS.SetTypeSpecError(); 727 } 728 return EndLoc; 729 } 730 731 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, 732 SourceLocation StartLoc, 733 SourceLocation EndLoc) { 734 // make sure we have a token we can turn into an annotation token 735 if (PP.isBacktrackEnabled()) 736 PP.RevertCachedTokens(1); 737 else 738 PP.EnterToken(Tok); 739 740 Tok.setKind(tok::annot_decltype); 741 setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ? 742 DS.getRepAsExpr() : ExprResult()); 743 Tok.setAnnotationEndLoc(EndLoc); 744 Tok.setLocation(StartLoc); 745 PP.AnnotateCachedTokens(Tok); 746 } 747 748 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) { 749 assert(Tok.is(tok::kw___underlying_type) && 750 "Not an underlying type specifier"); 751 752 SourceLocation StartLoc = ConsumeToken(); 753 BalancedDelimiterTracker T(*this, tok::l_paren); 754 if (T.expectAndConsume(diag::err_expected_lparen_after, 755 "__underlying_type", tok::r_paren)) { 756 return; 757 } 758 759 TypeResult Result = ParseTypeName(); 760 if (Result.isInvalid()) { 761 SkipUntil(tok::r_paren); 762 return; 763 } 764 765 // Match the ')' 766 T.consumeClose(); 767 if (T.getCloseLocation().isInvalid()) 768 return; 769 770 const char *PrevSpec = 0; 771 unsigned DiagID; 772 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec, 773 DiagID, Result.release())) 774 Diag(StartLoc, DiagID) << PrevSpec; 775 } 776 777 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a 778 /// class name or decltype-specifier. Note that we only check that the result 779 /// names a type; semantic analysis will need to verify that the type names a 780 /// class. The result is either a type or null, depending on whether a type 781 /// name was found. 782 /// 783 /// base-type-specifier: [C++ 10.1] 784 /// class-or-decltype 785 /// class-or-decltype: [C++ 10.1] 786 /// nested-name-specifier[opt] class-name 787 /// decltype-specifier 788 /// class-name: [C++ 9.1] 789 /// identifier 790 /// simple-template-id 791 /// 792 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc, 793 SourceLocation &EndLocation) { 794 // Ignore attempts to use typename 795 if (Tok.is(tok::kw_typename)) { 796 Diag(Tok, diag::err_expected_class_name_not_template) 797 << FixItHint::CreateRemoval(Tok.getLocation()); 798 ConsumeToken(); 799 } 800 801 // Parse optional nested-name-specifier 802 CXXScopeSpec SS; 803 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 804 805 BaseLoc = Tok.getLocation(); 806 807 // Parse decltype-specifier 808 // tok == kw_decltype is just error recovery, it can only happen when SS 809 // isn't empty 810 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) { 811 if (SS.isNotEmpty()) 812 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype) 813 << FixItHint::CreateRemoval(SS.getRange()); 814 // Fake up a Declarator to use with ActOnTypeName. 815 DeclSpec DS(AttrFactory); 816 817 EndLocation = ParseDecltypeSpecifier(DS); 818 819 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 820 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 821 } 822 823 // Check whether we have a template-id that names a type. 824 if (Tok.is(tok::annot_template_id)) { 825 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 826 if (TemplateId->Kind == TNK_Type_template || 827 TemplateId->Kind == TNK_Dependent_template_name) { 828 AnnotateTemplateIdTokenAsType(); 829 830 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 831 ParsedType Type = getTypeAnnotation(Tok); 832 EndLocation = Tok.getAnnotationEndLoc(); 833 ConsumeToken(); 834 835 if (Type) 836 return Type; 837 return true; 838 } 839 840 // Fall through to produce an error below. 841 } 842 843 if (Tok.isNot(tok::identifier)) { 844 Diag(Tok, diag::err_expected_class_name); 845 return true; 846 } 847 848 IdentifierInfo *Id = Tok.getIdentifierInfo(); 849 SourceLocation IdLoc = ConsumeToken(); 850 851 if (Tok.is(tok::less)) { 852 // It looks the user intended to write a template-id here, but the 853 // template-name was wrong. Try to fix that. 854 TemplateNameKind TNK = TNK_Type_template; 855 TemplateTy Template; 856 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(), 857 &SS, Template, TNK)) { 858 Diag(IdLoc, diag::err_unknown_template_name) 859 << Id; 860 } 861 862 if (!Template) 863 return true; 864 865 // Form the template name 866 UnqualifiedId TemplateName; 867 TemplateName.setIdentifier(Id, IdLoc); 868 869 // Parse the full template-id, then turn it into a type. 870 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 871 TemplateName, true)) 872 return true; 873 if (TNK == TNK_Dependent_template_name) 874 AnnotateTemplateIdTokenAsType(); 875 876 // If we didn't end up with a typename token, there's nothing more we 877 // can do. 878 if (Tok.isNot(tok::annot_typename)) 879 return true; 880 881 // Retrieve the type from the annotation token, consume that token, and 882 // return. 883 EndLocation = Tok.getAnnotationEndLoc(); 884 ParsedType Type = getTypeAnnotation(Tok); 885 ConsumeToken(); 886 return Type; 887 } 888 889 // We have an identifier; check whether it is actually a type. 890 IdentifierInfo *CorrectedII = 0; 891 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true, 892 false, ParsedType(), 893 /*IsCtorOrDtorName=*/false, 894 /*NonTrivialTypeSourceInfo=*/true, 895 &CorrectedII); 896 if (!Type) { 897 Diag(IdLoc, diag::err_expected_class_name); 898 return true; 899 } 900 901 // Consume the identifier. 902 EndLocation = IdLoc; 903 904 // Fake up a Declarator to use with ActOnTypeName. 905 DeclSpec DS(AttrFactory); 906 DS.SetRangeStart(IdLoc); 907 DS.SetRangeEnd(EndLocation); 908 DS.getTypeSpecScope() = SS; 909 910 const char *PrevSpec = 0; 911 unsigned DiagID; 912 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type); 913 914 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 915 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 916 } 917 918 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) { 919 while (Tok.is(tok::kw___single_inheritance) || 920 Tok.is(tok::kw___multiple_inheritance) || 921 Tok.is(tok::kw___virtual_inheritance)) { 922 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 923 SourceLocation AttrNameLoc = ConsumeToken(); 924 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 925 SourceLocation(), 0, 0, AttributeList::AS_GNU); 926 } 927 } 928 929 /// Determine whether the following tokens are valid after a type-specifier 930 /// which could be a standalone declaration. This will conservatively return 931 /// true if there's any doubt, and is appropriate for insert-';' fixits. 932 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) { 933 // This switch enumerates the valid "follow" set for type-specifiers. 934 switch (Tok.getKind()) { 935 default: break; 936 case tok::semi: // struct foo {...} ; 937 case tok::star: // struct foo {...} * P; 938 case tok::amp: // struct foo {...} & R = ... 939 case tok::identifier: // struct foo {...} V ; 940 case tok::r_paren: //(struct foo {...} ) {4} 941 case tok::annot_cxxscope: // struct foo {...} a:: b; 942 case tok::annot_typename: // struct foo {...} a ::b; 943 case tok::annot_template_id: // struct foo {...} a<int> ::b; 944 case tok::l_paren: // struct foo {...} ( x); 945 case tok::comma: // __builtin_offsetof(struct foo{...} , 946 return true; 947 case tok::colon: 948 return CouldBeBitfield; // enum E { ... } : 2; 949 // Type qualifiers 950 case tok::kw_const: // struct foo {...} const x; 951 case tok::kw_volatile: // struct foo {...} volatile x; 952 case tok::kw_restrict: // struct foo {...} restrict x; 953 case tok::kw_inline: // struct foo {...} inline foo() {}; 954 // Storage-class specifiers 955 case tok::kw_static: // struct foo {...} static x; 956 case tok::kw_extern: // struct foo {...} extern x; 957 case tok::kw_typedef: // struct foo {...} typedef x; 958 case tok::kw_register: // struct foo {...} register x; 959 case tok::kw_auto: // struct foo {...} auto x; 960 case tok::kw_mutable: // struct foo {...} mutable x; 961 case tok::kw_constexpr: // struct foo {...} constexpr x; 962 // As shown above, type qualifiers and storage class specifiers absolutely 963 // can occur after class specifiers according to the grammar. However, 964 // almost no one actually writes code like this. If we see one of these, 965 // it is much more likely that someone missed a semi colon and the 966 // type/storage class specifier we're seeing is part of the *next* 967 // intended declaration, as in: 968 // 969 // struct foo { ... } 970 // typedef int X; 971 // 972 // We'd really like to emit a missing semicolon error instead of emitting 973 // an error on the 'int' saying that you can't have two type specifiers in 974 // the same declaration of X. Because of this, we look ahead past this 975 // token to see if it's a type specifier. If so, we know the code is 976 // otherwise invalid, so we can produce the expected semi error. 977 if (!isKnownToBeTypeSpecifier(NextToken())) 978 return true; 979 break; 980 case tok::r_brace: // struct bar { struct foo {...} } 981 // Missing ';' at end of struct is accepted as an extension in C mode. 982 if (!getLangOpts().CPlusPlus) 983 return true; 984 break; 985 } 986 return false; 987 } 988 989 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or 990 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which 991 /// until we reach the start of a definition or see a token that 992 /// cannot start a definition. 993 /// 994 /// class-specifier: [C++ class] 995 /// class-head '{' member-specification[opt] '}' 996 /// class-head '{' member-specification[opt] '}' attributes[opt] 997 /// class-head: 998 /// class-key identifier[opt] base-clause[opt] 999 /// class-key nested-name-specifier identifier base-clause[opt] 1000 /// class-key nested-name-specifier[opt] simple-template-id 1001 /// base-clause[opt] 1002 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] 1003 /// [GNU] class-key attributes[opt] nested-name-specifier 1004 /// identifier base-clause[opt] 1005 /// [GNU] class-key attributes[opt] nested-name-specifier[opt] 1006 /// simple-template-id base-clause[opt] 1007 /// class-key: 1008 /// 'class' 1009 /// 'struct' 1010 /// 'union' 1011 /// 1012 /// elaborated-type-specifier: [C++ dcl.type.elab] 1013 /// class-key ::[opt] nested-name-specifier[opt] identifier 1014 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] 1015 /// simple-template-id 1016 /// 1017 /// Note that the C++ class-specifier and elaborated-type-specifier, 1018 /// together, subsume the C99 struct-or-union-specifier: 1019 /// 1020 /// struct-or-union-specifier: [C99 6.7.2.1] 1021 /// struct-or-union identifier[opt] '{' struct-contents '}' 1022 /// struct-or-union identifier 1023 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents 1024 /// '}' attributes[opt] 1025 /// [GNU] struct-or-union attributes[opt] identifier 1026 /// struct-or-union: 1027 /// 'struct' 1028 /// 'union' 1029 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, 1030 SourceLocation StartLoc, DeclSpec &DS, 1031 const ParsedTemplateInfo &TemplateInfo, 1032 AccessSpecifier AS, 1033 bool EnteringContext, DeclSpecContext DSC) { 1034 DeclSpec::TST TagType; 1035 if (TagTokKind == tok::kw_struct) 1036 TagType = DeclSpec::TST_struct; 1037 else if (TagTokKind == tok::kw___interface) 1038 TagType = DeclSpec::TST_interface; 1039 else if (TagTokKind == tok::kw_class) 1040 TagType = DeclSpec::TST_class; 1041 else { 1042 assert(TagTokKind == tok::kw_union && "Not a class specifier"); 1043 TagType = DeclSpec::TST_union; 1044 } 1045 1046 if (Tok.is(tok::code_completion)) { 1047 // Code completion for a struct, class, or union name. 1048 Actions.CodeCompleteTag(getCurScope(), TagType); 1049 return cutOffParsing(); 1050 } 1051 1052 // C++03 [temp.explicit] 14.7.2/8: 1053 // The usual access checking rules do not apply to names used to specify 1054 // explicit instantiations. 1055 // 1056 // As an extension we do not perform access checking on the names used to 1057 // specify explicit specializations either. This is important to allow 1058 // specializing traits classes for private types. 1059 // 1060 // Note that we don't suppress if this turns out to be an elaborated 1061 // type specifier. 1062 bool shouldDelayDiagsInTag = 1063 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 1064 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); 1065 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); 1066 1067 ParsedAttributesWithRange attrs(AttrFactory); 1068 // If attributes exist after tag, parse them. 1069 if (Tok.is(tok::kw___attribute)) 1070 ParseGNUAttributes(attrs); 1071 1072 // If declspecs exist after tag, parse them. 1073 while (Tok.is(tok::kw___declspec)) 1074 ParseMicrosoftDeclSpec(attrs); 1075 1076 // Parse inheritance specifiers. 1077 if (Tok.is(tok::kw___single_inheritance) || 1078 Tok.is(tok::kw___multiple_inheritance) || 1079 Tok.is(tok::kw___virtual_inheritance)) 1080 ParseMicrosoftInheritanceClassAttributes(attrs); 1081 1082 // If C++0x attributes exist here, parse them. 1083 // FIXME: Are we consistent with the ordering of parsing of different 1084 // styles of attributes? 1085 MaybeParseCXX0XAttributes(attrs); 1086 1087 if (TagType == DeclSpec::TST_struct && 1088 !Tok.is(tok::identifier) && 1089 Tok.getIdentifierInfo() && 1090 (Tok.is(tok::kw___is_arithmetic) || 1091 Tok.is(tok::kw___is_convertible) || 1092 Tok.is(tok::kw___is_empty) || 1093 Tok.is(tok::kw___is_floating_point) || 1094 Tok.is(tok::kw___is_function) || 1095 Tok.is(tok::kw___is_fundamental) || 1096 Tok.is(tok::kw___is_integral) || 1097 Tok.is(tok::kw___is_member_function_pointer) || 1098 Tok.is(tok::kw___is_member_pointer) || 1099 Tok.is(tok::kw___is_pod) || 1100 Tok.is(tok::kw___is_pointer) || 1101 Tok.is(tok::kw___is_same) || 1102 Tok.is(tok::kw___is_scalar) || 1103 Tok.is(tok::kw___is_signed) || 1104 Tok.is(tok::kw___is_unsigned) || 1105 Tok.is(tok::kw___is_void))) { 1106 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the 1107 // name of struct templates, but some are keywords in GCC >= 4.3 1108 // and Clang. Therefore, when we see the token sequence "struct 1109 // X", make X into a normal identifier rather than a keyword, to 1110 // allow libstdc++ 4.2 and libc++ to work properly. 1111 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 1112 Tok.setKind(tok::identifier); 1113 } 1114 1115 // Parse the (optional) nested-name-specifier. 1116 CXXScopeSpec &SS = DS.getTypeSpecScope(); 1117 if (getLangOpts().CPlusPlus) { 1118 // "FOO : BAR" is not a potential typo for "FOO::BAR". 1119 ColonProtectionRAIIObject X(*this); 1120 1121 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) 1122 DS.SetTypeSpecError(); 1123 if (SS.isSet()) 1124 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 1125 Diag(Tok, diag::err_expected_ident); 1126 } 1127 1128 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 1129 1130 // Parse the (optional) class name or simple-template-id. 1131 IdentifierInfo *Name = 0; 1132 SourceLocation NameLoc; 1133 TemplateIdAnnotation *TemplateId = 0; 1134 if (Tok.is(tok::identifier)) { 1135 Name = Tok.getIdentifierInfo(); 1136 NameLoc = ConsumeToken(); 1137 1138 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) { 1139 // The name was supposed to refer to a template, but didn't. 1140 // Eat the template argument list and try to continue parsing this as 1141 // a class (or template thereof). 1142 TemplateArgList TemplateArgs; 1143 SourceLocation LAngleLoc, RAngleLoc; 1144 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS, 1145 true, LAngleLoc, 1146 TemplateArgs, RAngleLoc)) { 1147 // We couldn't parse the template argument list at all, so don't 1148 // try to give any location information for the list. 1149 LAngleLoc = RAngleLoc = SourceLocation(); 1150 } 1151 1152 Diag(NameLoc, diag::err_explicit_spec_non_template) 1153 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 1154 << (TagType == DeclSpec::TST_class? 0 1155 : TagType == DeclSpec::TST_struct? 1 1156 : TagType == DeclSpec::TST_interface? 2 1157 : 3) 1158 << Name 1159 << SourceRange(LAngleLoc, RAngleLoc); 1160 1161 // Strip off the last template parameter list if it was empty, since 1162 // we've removed its template argument list. 1163 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) { 1164 if (TemplateParams && TemplateParams->size() > 1) { 1165 TemplateParams->pop_back(); 1166 } else { 1167 TemplateParams = 0; 1168 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 1169 = ParsedTemplateInfo::NonTemplate; 1170 } 1171 } else if (TemplateInfo.Kind 1172 == ParsedTemplateInfo::ExplicitInstantiation) { 1173 // Pretend this is just a forward declaration. 1174 TemplateParams = 0; 1175 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 1176 = ParsedTemplateInfo::NonTemplate; 1177 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc 1178 = SourceLocation(); 1179 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc 1180 = SourceLocation(); 1181 } 1182 } 1183 } else if (Tok.is(tok::annot_template_id)) { 1184 TemplateId = takeTemplateIdAnnotation(Tok); 1185 NameLoc = ConsumeToken(); 1186 1187 if (TemplateId->Kind != TNK_Type_template && 1188 TemplateId->Kind != TNK_Dependent_template_name) { 1189 // The template-name in the simple-template-id refers to 1190 // something other than a class template. Give an appropriate 1191 // error message and skip to the ';'. 1192 SourceRange Range(NameLoc); 1193 if (SS.isNotEmpty()) 1194 Range.setBegin(SS.getBeginLoc()); 1195 1196 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) 1197 << Name << static_cast<int>(TemplateId->Kind) << Range; 1198 1199 DS.SetTypeSpecError(); 1200 SkipUntil(tok::semi, false, true); 1201 return; 1202 } 1203 } 1204 1205 // There are four options here. 1206 // - If we are in a trailing return type, this is always just a reference, 1207 // and we must not try to parse a definition. For instance, 1208 // [] () -> struct S { }; 1209 // does not define a type. 1210 // - If we have 'struct foo {...', 'struct foo :...', 1211 // 'struct foo final :' or 'struct foo final {', then this is a definition. 1212 // - If we have 'struct foo;', then this is either a forward declaration 1213 // or a friend declaration, which have to be treated differently. 1214 // - Otherwise we have something like 'struct foo xyz', a reference. 1215 // However, in type-specifier-seq's, things look like declarations but are 1216 // just references, e.g. 1217 // new struct s; 1218 // or 1219 // &T::operator struct s; 1220 // For these, DSC is DSC_type_specifier. 1221 Sema::TagUseKind TUK; 1222 if (DSC == DSC_trailing) 1223 TUK = Sema::TUK_Reference; 1224 else if (Tok.is(tok::l_brace) || 1225 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) || 1226 (isCXX0XFinalKeyword() && 1227 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) { 1228 if (DS.isFriendSpecified()) { 1229 // C++ [class.friend]p2: 1230 // A class shall not be defined in a friend declaration. 1231 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) 1232 << SourceRange(DS.getFriendSpecLoc()); 1233 1234 // Skip everything up to the semicolon, so that this looks like a proper 1235 // friend class (or template thereof) declaration. 1236 SkipUntil(tok::semi, true, true); 1237 TUK = Sema::TUK_Friend; 1238 } else { 1239 // Okay, this is a class definition. 1240 TUK = Sema::TUK_Definition; 1241 } 1242 } else if (DSC != DSC_type_specifier && 1243 (Tok.is(tok::semi) || 1244 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) { 1245 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 1246 if (Tok.isNot(tok::semi)) { 1247 // A semicolon was missing after this declaration. Diagnose and recover. 1248 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 1249 DeclSpec::getSpecifierName(TagType)); 1250 PP.EnterToken(Tok); 1251 Tok.setKind(tok::semi); 1252 } 1253 } else 1254 TUK = Sema::TUK_Reference; 1255 1256 // If this is an elaborated type specifier, and we delayed 1257 // diagnostics before, just merge them into the current pool. 1258 if (shouldDelayDiagsInTag) { 1259 diagsFromTag.done(); 1260 if (TUK == Sema::TUK_Reference) 1261 diagsFromTag.redelay(); 1262 } 1263 1264 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error || 1265 TUK != Sema::TUK_Definition)) { 1266 if (DS.getTypeSpecType() != DeclSpec::TST_error) { 1267 // We have a declaration or reference to an anonymous class. 1268 Diag(StartLoc, diag::err_anon_type_definition) 1269 << DeclSpec::getSpecifierName(TagType); 1270 } 1271 1272 SkipUntil(tok::comma, true); 1273 return; 1274 } 1275 1276 // Create the tag portion of the class or class template. 1277 DeclResult TagOrTempResult = true; // invalid 1278 TypeResult TypeResult = true; // invalid 1279 1280 bool Owned = false; 1281 if (TemplateId) { 1282 // Explicit specialization, class template partial specialization, 1283 // or explicit instantiation. 1284 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 1285 TemplateId->NumArgs); 1286 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 1287 TUK == Sema::TUK_Declaration) { 1288 // This is an explicit instantiation of a class template. 1289 ProhibitAttributes(attrs); 1290 1291 TagOrTempResult 1292 = Actions.ActOnExplicitInstantiation(getCurScope(), 1293 TemplateInfo.ExternLoc, 1294 TemplateInfo.TemplateLoc, 1295 TagType, 1296 StartLoc, 1297 SS, 1298 TemplateId->Template, 1299 TemplateId->TemplateNameLoc, 1300 TemplateId->LAngleLoc, 1301 TemplateArgsPtr, 1302 TemplateId->RAngleLoc, 1303 attrs.getList()); 1304 1305 // Friend template-ids are treated as references unless 1306 // they have template headers, in which case they're ill-formed 1307 // (FIXME: "template <class T> friend class A<T>::B<int>;"). 1308 // We diagnose this error in ActOnClassTemplateSpecialization. 1309 } else if (TUK == Sema::TUK_Reference || 1310 (TUK == Sema::TUK_Friend && 1311 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) { 1312 ProhibitAttributes(attrs); 1313 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc, 1314 TemplateId->SS, 1315 TemplateId->TemplateKWLoc, 1316 TemplateId->Template, 1317 TemplateId->TemplateNameLoc, 1318 TemplateId->LAngleLoc, 1319 TemplateArgsPtr, 1320 TemplateId->RAngleLoc); 1321 } else { 1322 // This is an explicit specialization or a class template 1323 // partial specialization. 1324 TemplateParameterLists FakedParamLists; 1325 1326 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 1327 // This looks like an explicit instantiation, because we have 1328 // something like 1329 // 1330 // template class Foo<X> 1331 // 1332 // but it actually has a definition. Most likely, this was 1333 // meant to be an explicit specialization, but the user forgot 1334 // the '<>' after 'template'. 1335 assert(TUK == Sema::TUK_Definition && "Expected a definition here"); 1336 1337 SourceLocation LAngleLoc 1338 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 1339 Diag(TemplateId->TemplateNameLoc, 1340 diag::err_explicit_instantiation_with_definition) 1341 << SourceRange(TemplateInfo.TemplateLoc) 1342 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 1343 1344 // Create a fake template parameter list that contains only 1345 // "template<>", so that we treat this construct as a class 1346 // template specialization. 1347 FakedParamLists.push_back( 1348 Actions.ActOnTemplateParameterList(0, SourceLocation(), 1349 TemplateInfo.TemplateLoc, 1350 LAngleLoc, 1351 0, 0, 1352 LAngleLoc)); 1353 TemplateParams = &FakedParamLists; 1354 } 1355 1356 // Build the class template specialization. 1357 TagOrTempResult 1358 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK, 1359 StartLoc, DS.getModulePrivateSpecLoc(), SS, 1360 TemplateId->Template, 1361 TemplateId->TemplateNameLoc, 1362 TemplateId->LAngleLoc, 1363 TemplateArgsPtr, 1364 TemplateId->RAngleLoc, 1365 attrs.getList(), 1366 MultiTemplateParamsArg( 1367 TemplateParams? &(*TemplateParams)[0] : 0, 1368 TemplateParams? TemplateParams->size() : 0)); 1369 } 1370 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 1371 TUK == Sema::TUK_Declaration) { 1372 // Explicit instantiation of a member of a class template 1373 // specialization, e.g., 1374 // 1375 // template struct Outer<int>::Inner; 1376 // 1377 ProhibitAttributes(attrs); 1378 1379 TagOrTempResult 1380 = Actions.ActOnExplicitInstantiation(getCurScope(), 1381 TemplateInfo.ExternLoc, 1382 TemplateInfo.TemplateLoc, 1383 TagType, StartLoc, SS, Name, 1384 NameLoc, attrs.getList()); 1385 } else if (TUK == Sema::TUK_Friend && 1386 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) { 1387 ProhibitAttributes(attrs); 1388 1389 TagOrTempResult = 1390 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(), 1391 TagType, StartLoc, SS, 1392 Name, NameLoc, attrs.getList(), 1393 MultiTemplateParamsArg( 1394 TemplateParams? &(*TemplateParams)[0] : 0, 1395 TemplateParams? TemplateParams->size() : 0)); 1396 } else { 1397 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 1398 TUK == Sema::TUK_Definition) { 1399 // FIXME: Diagnose this particular error. 1400 } 1401 1402 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition) 1403 ProhibitAttributes(attrs); 1404 1405 bool IsDependent = false; 1406 1407 // Don't pass down template parameter lists if this is just a tag 1408 // reference. For example, we don't need the template parameters here: 1409 // template <class T> class A *makeA(T t); 1410 MultiTemplateParamsArg TParams; 1411 if (TUK != Sema::TUK_Reference && TemplateParams) 1412 TParams = 1413 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size()); 1414 1415 // Declaration or definition of a class type 1416 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc, 1417 SS, Name, NameLoc, attrs.getList(), AS, 1418 DS.getModulePrivateSpecLoc(), 1419 TParams, Owned, IsDependent, 1420 SourceLocation(), false, 1421 clang::TypeResult()); 1422 1423 // If ActOnTag said the type was dependent, try again with the 1424 // less common call. 1425 if (IsDependent) { 1426 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend); 1427 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, 1428 SS, Name, StartLoc, NameLoc); 1429 } 1430 } 1431 1432 // If there is a body, parse it and inform the actions module. 1433 if (TUK == Sema::TUK_Definition) { 1434 assert(Tok.is(tok::l_brace) || 1435 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) || 1436 isCXX0XFinalKeyword()); 1437 if (getLangOpts().CPlusPlus) 1438 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get()); 1439 else 1440 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); 1441 } 1442 1443 const char *PrevSpec = 0; 1444 unsigned DiagID; 1445 bool Result; 1446 if (!TypeResult.isInvalid()) { 1447 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, 1448 NameLoc.isValid() ? NameLoc : StartLoc, 1449 PrevSpec, DiagID, TypeResult.get()); 1450 } else if (!TagOrTempResult.isInvalid()) { 1451 Result = DS.SetTypeSpecType(TagType, StartLoc, 1452 NameLoc.isValid() ? NameLoc : StartLoc, 1453 PrevSpec, DiagID, TagOrTempResult.get(), Owned); 1454 } else { 1455 DS.SetTypeSpecError(); 1456 return; 1457 } 1458 1459 if (Result) 1460 Diag(StartLoc, DiagID) << PrevSpec; 1461 1462 // At this point, we've successfully parsed a class-specifier in 'definition' 1463 // form (e.g. "struct foo { int x; }". While we could just return here, we're 1464 // going to look at what comes after it to improve error recovery. If an 1465 // impossible token occurs next, we assume that the programmer forgot a ; at 1466 // the end of the declaration and recover that way. 1467 // 1468 // Also enforce C++ [temp]p3: 1469 // In a template-declaration which defines a class, no declarator 1470 // is permitted. 1471 if (TUK == Sema::TUK_Definition && 1472 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) { 1473 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 1474 DeclSpec::getSpecifierName(TagType)); 1475 // Push this token back into the preprocessor and change our current token 1476 // to ';' so that the rest of the code recovers as though there were an 1477 // ';' after the definition. 1478 PP.EnterToken(Tok); 1479 Tok.setKind(tok::semi); 1480 } 1481 } 1482 1483 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 1484 /// 1485 /// base-clause : [C++ class.derived] 1486 /// ':' base-specifier-list 1487 /// base-specifier-list: 1488 /// base-specifier '...'[opt] 1489 /// base-specifier-list ',' base-specifier '...'[opt] 1490 void Parser::ParseBaseClause(Decl *ClassDecl) { 1491 assert(Tok.is(tok::colon) && "Not a base clause"); 1492 ConsumeToken(); 1493 1494 // Build up an array of parsed base specifiers. 1495 SmallVector<CXXBaseSpecifier *, 8> BaseInfo; 1496 1497 while (true) { 1498 // Parse a base-specifier. 1499 BaseResult Result = ParseBaseSpecifier(ClassDecl); 1500 if (Result.isInvalid()) { 1501 // Skip the rest of this base specifier, up until the comma or 1502 // opening brace. 1503 SkipUntil(tok::comma, tok::l_brace, true, true); 1504 } else { 1505 // Add this to our array of base specifiers. 1506 BaseInfo.push_back(Result.get()); 1507 } 1508 1509 // If the next token is a comma, consume it and keep reading 1510 // base-specifiers. 1511 if (Tok.isNot(tok::comma)) break; 1512 1513 // Consume the comma. 1514 ConsumeToken(); 1515 } 1516 1517 // Attach the base specifiers 1518 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); 1519 } 1520 1521 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 1522 /// one entry in the base class list of a class specifier, for example: 1523 /// class foo : public bar, virtual private baz { 1524 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1525 /// 1526 /// base-specifier: [C++ class.derived] 1527 /// ::[opt] nested-name-specifier[opt] class-name 1528 /// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt] 1529 /// base-type-specifier 1530 /// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt] 1531 /// base-type-specifier 1532 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) { 1533 bool IsVirtual = false; 1534 SourceLocation StartLoc = Tok.getLocation(); 1535 1536 // Parse the 'virtual' keyword. 1537 if (Tok.is(tok::kw_virtual)) { 1538 ConsumeToken(); 1539 IsVirtual = true; 1540 } 1541 1542 // Parse an (optional) access specifier. 1543 AccessSpecifier Access = getAccessSpecifierIfPresent(); 1544 if (Access != AS_none) 1545 ConsumeToken(); 1546 1547 // Parse the 'virtual' keyword (again!), in case it came after the 1548 // access specifier. 1549 if (Tok.is(tok::kw_virtual)) { 1550 SourceLocation VirtualLoc = ConsumeToken(); 1551 if (IsVirtual) { 1552 // Complain about duplicate 'virtual' 1553 Diag(VirtualLoc, diag::err_dup_virtual) 1554 << FixItHint::CreateRemoval(VirtualLoc); 1555 } 1556 1557 IsVirtual = true; 1558 } 1559 1560 // Parse the class-name. 1561 SourceLocation EndLocation; 1562 SourceLocation BaseLoc; 1563 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation); 1564 if (BaseType.isInvalid()) 1565 return true; 1566 1567 // Parse the optional ellipsis (for a pack expansion). The ellipsis is 1568 // actually part of the base-specifier-list grammar productions, but we 1569 // parse it here for convenience. 1570 SourceLocation EllipsisLoc; 1571 if (Tok.is(tok::ellipsis)) 1572 EllipsisLoc = ConsumeToken(); 1573 1574 // Find the complete source range for the base-specifier. 1575 SourceRange Range(StartLoc, EndLocation); 1576 1577 // Notify semantic analysis that we have parsed a complete 1578 // base-specifier. 1579 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, 1580 BaseType.get(), BaseLoc, EllipsisLoc); 1581 } 1582 1583 /// getAccessSpecifierIfPresent - Determine whether the next token is 1584 /// a C++ access-specifier. 1585 /// 1586 /// access-specifier: [C++ class.derived] 1587 /// 'private' 1588 /// 'protected' 1589 /// 'public' 1590 AccessSpecifier Parser::getAccessSpecifierIfPresent() const { 1591 switch (Tok.getKind()) { 1592 default: return AS_none; 1593 case tok::kw_private: return AS_private; 1594 case tok::kw_protected: return AS_protected; 1595 case tok::kw_public: return AS_public; 1596 } 1597 } 1598 1599 /// \brief If the given declarator has any parts for which parsing has to be 1600 /// delayed, e.g., default arguments, create a late-parsed method declaration 1601 /// record to handle the parsing at the end of the class definition. 1602 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, 1603 Decl *ThisDecl) { 1604 // We just declared a member function. If this member function 1605 // has any default arguments, we'll need to parse them later. 1606 LateParsedMethodDeclaration *LateMethod = 0; 1607 DeclaratorChunk::FunctionTypeInfo &FTI 1608 = DeclaratorInfo.getFunctionTypeInfo(); 1609 1610 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { 1611 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { 1612 if (!LateMethod) { 1613 // Push this method onto the stack of late-parsed method 1614 // declarations. 1615 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl); 1616 getCurrentClass().LateParsedDeclarations.push_back(LateMethod); 1617 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope(); 1618 1619 // Add all of the parameters prior to this one (they don't 1620 // have default arguments). 1621 LateMethod->DefaultArgs.reserve(FTI.NumArgs); 1622 for (unsigned I = 0; I < ParamIdx; ++I) 1623 LateMethod->DefaultArgs.push_back( 1624 LateParsedDefaultArgument(FTI.ArgInfo[I].Param)); 1625 } 1626 1627 // Add this parameter to the list of parameters (it may or may 1628 // not have a default argument). 1629 LateMethod->DefaultArgs.push_back( 1630 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param, 1631 FTI.ArgInfo[ParamIdx].DefaultArgTokens)); 1632 } 1633 } 1634 } 1635 1636 /// isCXX0XVirtSpecifier - Determine whether the given token is a C++0x 1637 /// virt-specifier. 1638 /// 1639 /// virt-specifier: 1640 /// override 1641 /// final 1642 VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier(const Token &Tok) const { 1643 if (!getLangOpts().CPlusPlus) 1644 return VirtSpecifiers::VS_None; 1645 1646 if (Tok.is(tok::identifier)) { 1647 IdentifierInfo *II = Tok.getIdentifierInfo(); 1648 1649 // Initialize the contextual keywords. 1650 if (!Ident_final) { 1651 Ident_final = &PP.getIdentifierTable().get("final"); 1652 Ident_override = &PP.getIdentifierTable().get("override"); 1653 } 1654 1655 if (II == Ident_override) 1656 return VirtSpecifiers::VS_Override; 1657 1658 if (II == Ident_final) 1659 return VirtSpecifiers::VS_Final; 1660 } 1661 1662 return VirtSpecifiers::VS_None; 1663 } 1664 1665 /// ParseOptionalCXX0XVirtSpecifierSeq - Parse a virt-specifier-seq. 1666 /// 1667 /// virt-specifier-seq: 1668 /// virt-specifier 1669 /// virt-specifier-seq virt-specifier 1670 void Parser::ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS) { 1671 while (true) { 1672 VirtSpecifiers::Specifier Specifier = isCXX0XVirtSpecifier(); 1673 if (Specifier == VirtSpecifiers::VS_None) 1674 return; 1675 1676 // C++ [class.mem]p8: 1677 // A virt-specifier-seq shall contain at most one of each virt-specifier. 1678 const char *PrevSpec = 0; 1679 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec)) 1680 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier) 1681 << PrevSpec 1682 << FixItHint::CreateRemoval(Tok.getLocation()); 1683 1684 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ? 1685 diag::warn_cxx98_compat_override_control_keyword : 1686 diag::ext_override_control_keyword) 1687 << VirtSpecifiers::getSpecifierName(Specifier); 1688 ConsumeToken(); 1689 } 1690 } 1691 1692 /// isCXX0XFinalKeyword - Determine whether the next token is a C++0x 1693 /// contextual 'final' keyword. 1694 bool Parser::isCXX0XFinalKeyword() const { 1695 if (!getLangOpts().CPlusPlus) 1696 return false; 1697 1698 if (!Tok.is(tok::identifier)) 1699 return false; 1700 1701 // Initialize the contextual keywords. 1702 if (!Ident_final) { 1703 Ident_final = &PP.getIdentifierTable().get("final"); 1704 Ident_override = &PP.getIdentifierTable().get("override"); 1705 } 1706 1707 return Tok.getIdentifierInfo() == Ident_final; 1708 } 1709 1710 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 1711 /// 1712 /// member-declaration: 1713 /// decl-specifier-seq[opt] member-declarator-list[opt] ';' 1714 /// function-definition ';'[opt] 1715 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 1716 /// using-declaration [TODO] 1717 /// [C++0x] static_assert-declaration 1718 /// template-declaration 1719 /// [GNU] '__extension__' member-declaration 1720 /// 1721 /// member-declarator-list: 1722 /// member-declarator 1723 /// member-declarator-list ',' member-declarator 1724 /// 1725 /// member-declarator: 1726 /// declarator virt-specifier-seq[opt] pure-specifier[opt] 1727 /// declarator constant-initializer[opt] 1728 /// [C++11] declarator brace-or-equal-initializer[opt] 1729 /// identifier[opt] ':' constant-expression 1730 /// 1731 /// virt-specifier-seq: 1732 /// virt-specifier 1733 /// virt-specifier-seq virt-specifier 1734 /// 1735 /// virt-specifier: 1736 /// override 1737 /// final 1738 /// 1739 /// pure-specifier: 1740 /// '= 0' 1741 /// 1742 /// constant-initializer: 1743 /// '=' constant-expression 1744 /// 1745 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, 1746 AttributeList *AccessAttrs, 1747 const ParsedTemplateInfo &TemplateInfo, 1748 ParsingDeclRAIIObject *TemplateDiags) { 1749 if (Tok.is(tok::at)) { 1750 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs)) 1751 Diag(Tok, diag::err_at_defs_cxx); 1752 else 1753 Diag(Tok, diag::err_at_in_class); 1754 1755 ConsumeToken(); 1756 SkipUntil(tok::r_brace); 1757 return; 1758 } 1759 1760 // Access declarations. 1761 bool MalformedTypeSpec = false; 1762 if (!TemplateInfo.Kind && 1763 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) { 1764 if (TryAnnotateCXXScopeToken()) 1765 MalformedTypeSpec = true; 1766 1767 bool isAccessDecl; 1768 if (Tok.isNot(tok::annot_cxxscope)) 1769 isAccessDecl = false; 1770 else if (NextToken().is(tok::identifier)) 1771 isAccessDecl = GetLookAheadToken(2).is(tok::semi); 1772 else 1773 isAccessDecl = NextToken().is(tok::kw_operator); 1774 1775 if (isAccessDecl) { 1776 // Collect the scope specifier token we annotated earlier. 1777 CXXScopeSpec SS; 1778 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 1779 /*EnteringContext=*/false); 1780 1781 // Try to parse an unqualified-id. 1782 SourceLocation TemplateKWLoc; 1783 UnqualifiedId Name; 1784 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), 1785 TemplateKWLoc, Name)) { 1786 SkipUntil(tok::semi); 1787 return; 1788 } 1789 1790 // TODO: recover from mistakenly-qualified operator declarations. 1791 if (ExpectAndConsume(tok::semi, 1792 diag::err_expected_semi_after, 1793 "access declaration", 1794 tok::semi)) 1795 return; 1796 1797 Actions.ActOnUsingDeclaration(getCurScope(), AS, 1798 false, SourceLocation(), 1799 SS, Name, 1800 /* AttrList */ 0, 1801 /* IsTypeName */ false, 1802 SourceLocation()); 1803 return; 1804 } 1805 } 1806 1807 // static_assert-declaration 1808 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) { 1809 // FIXME: Check for templates 1810 SourceLocation DeclEnd; 1811 ParseStaticAssertDeclaration(DeclEnd); 1812 return; 1813 } 1814 1815 if (Tok.is(tok::kw_template)) { 1816 assert(!TemplateInfo.TemplateParams && 1817 "Nested template improperly parsed?"); 1818 SourceLocation DeclEnd; 1819 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, 1820 AS, AccessAttrs); 1821 return; 1822 } 1823 1824 // Handle: member-declaration ::= '__extension__' member-declaration 1825 if (Tok.is(tok::kw___extension__)) { 1826 // __extension__ silences extension warnings in the subexpression. 1827 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1828 ConsumeToken(); 1829 return ParseCXXClassMemberDeclaration(AS, AccessAttrs, 1830 TemplateInfo, TemplateDiags); 1831 } 1832 1833 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it 1834 // is a bitfield. 1835 ColonProtectionRAIIObject X(*this); 1836 1837 ParsedAttributesWithRange attrs(AttrFactory); 1838 // Optional C++0x attribute-specifier 1839 MaybeParseCXX0XAttributes(attrs); 1840 MaybeParseMicrosoftAttributes(attrs); 1841 1842 if (Tok.is(tok::kw_using)) { 1843 ProhibitAttributes(attrs); 1844 1845 // Eat 'using'. 1846 SourceLocation UsingLoc = ConsumeToken(); 1847 1848 if (Tok.is(tok::kw_namespace)) { 1849 Diag(UsingLoc, diag::err_using_namespace_in_class); 1850 SkipUntil(tok::semi, true, true); 1851 } else { 1852 SourceLocation DeclEnd; 1853 // Otherwise, it must be a using-declaration or an alias-declaration. 1854 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo, 1855 UsingLoc, DeclEnd, AS); 1856 } 1857 return; 1858 } 1859 1860 // Hold late-parsed attributes so we can attach a Decl to them later. 1861 LateParsedAttrList CommonLateParsedAttrs; 1862 1863 // decl-specifier-seq: 1864 // Parse the common declaration-specifiers piece. 1865 ParsingDeclSpec DS(*this, TemplateDiags); 1866 DS.takeAttributesFrom(attrs); 1867 if (MalformedTypeSpec) 1868 DS.SetTypeSpecError(); 1869 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class, 1870 &CommonLateParsedAttrs); 1871 1872 MultiTemplateParamsArg TemplateParams( 1873 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0, 1874 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0); 1875 1876 if (Tok.is(tok::semi)) { 1877 ConsumeToken(); 1878 Decl *TheDecl = 1879 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams); 1880 DS.complete(TheDecl); 1881 return; 1882 } 1883 1884 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext); 1885 VirtSpecifiers VS; 1886 1887 // Hold late-parsed attributes so we can attach a Decl to them later. 1888 LateParsedAttrList LateParsedAttrs; 1889 1890 SourceLocation EqualLoc; 1891 bool HasInitializer = false; 1892 ExprResult Init; 1893 if (Tok.isNot(tok::colon)) { 1894 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 1895 ColonProtectionRAIIObject X(*this); 1896 1897 // Parse the first declarator. 1898 ParseDeclarator(DeclaratorInfo); 1899 // Error parsing the declarator? 1900 if (!DeclaratorInfo.hasName()) { 1901 // If so, skip until the semi-colon or a }. 1902 SkipUntil(tok::r_brace, true, true); 1903 if (Tok.is(tok::semi)) 1904 ConsumeToken(); 1905 return; 1906 } 1907 1908 ParseOptionalCXX0XVirtSpecifierSeq(VS); 1909 1910 // If attributes exist after the declarator, but before an '{', parse them. 1911 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); 1912 1913 // MSVC permits pure specifier on inline functions declared at class scope. 1914 // Hence check for =0 before checking for function definition. 1915 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) && 1916 DeclaratorInfo.isFunctionDeclarator() && 1917 NextToken().is(tok::numeric_constant)) { 1918 EqualLoc = ConsumeToken(); 1919 Init = ParseInitializer(); 1920 if (Init.isInvalid()) 1921 SkipUntil(tok::comma, true, true); 1922 else 1923 HasInitializer = true; 1924 } 1925 1926 FunctionDefinitionKind DefinitionKind = FDK_Declaration; 1927 // function-definition: 1928 // 1929 // In C++11, a non-function declarator followed by an open brace is a 1930 // braced-init-list for an in-class member initialization, not an 1931 // erroneous function definition. 1932 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus0x) { 1933 DefinitionKind = FDK_Definition; 1934 } else if (DeclaratorInfo.isFunctionDeclarator()) { 1935 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) { 1936 DefinitionKind = FDK_Definition; 1937 } else if (Tok.is(tok::equal)) { 1938 const Token &KW = NextToken(); 1939 if (KW.is(tok::kw_default)) 1940 DefinitionKind = FDK_Defaulted; 1941 else if (KW.is(tok::kw_delete)) 1942 DefinitionKind = FDK_Deleted; 1943 } 1944 } 1945 1946 if (DefinitionKind) { 1947 if (!DeclaratorInfo.isFunctionDeclarator()) { 1948 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params); 1949 ConsumeBrace(); 1950 SkipUntil(tok::r_brace, /*StopAtSemi*/false); 1951 1952 // Consume the optional ';' 1953 if (Tok.is(tok::semi)) 1954 ConsumeToken(); 1955 return; 1956 } 1957 1958 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1959 Diag(DeclaratorInfo.getIdentifierLoc(), 1960 diag::err_function_declared_typedef); 1961 // This recovery skips the entire function body. It would be nice 1962 // to simply call ParseCXXInlineMethodDef() below, however Sema 1963 // assumes the declarator represents a function, not a typedef. 1964 ConsumeBrace(); 1965 SkipUntil(tok::r_brace, /*StopAtSemi*/false); 1966 1967 // Consume the optional ';' 1968 if (Tok.is(tok::semi)) 1969 ConsumeToken(); 1970 return; 1971 } 1972 1973 Decl *FunDecl = 1974 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo, 1975 VS, DefinitionKind, Init); 1976 1977 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) { 1978 CommonLateParsedAttrs[i]->addDecl(FunDecl); 1979 } 1980 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) { 1981 LateParsedAttrs[i]->addDecl(FunDecl); 1982 } 1983 LateParsedAttrs.clear(); 1984 1985 // Consume the ';' - it's optional unless we have a delete or default 1986 if (Tok.is(tok::semi)) 1987 ConsumeExtraSemi(AfterMemberFunctionDefinition); 1988 1989 return; 1990 } 1991 } 1992 1993 // member-declarator-list: 1994 // member-declarator 1995 // member-declarator-list ',' member-declarator 1996 1997 SmallVector<Decl *, 8> DeclsInGroup; 1998 ExprResult BitfieldSize; 1999 bool ExpectSemi = true; 2000 2001 while (1) { 2002 // member-declarator: 2003 // declarator pure-specifier[opt] 2004 // declarator brace-or-equal-initializer[opt] 2005 // identifier[opt] ':' constant-expression 2006 if (Tok.is(tok::colon)) { 2007 ConsumeToken(); 2008 BitfieldSize = ParseConstantExpression(); 2009 if (BitfieldSize.isInvalid()) 2010 SkipUntil(tok::comma, true, true); 2011 } 2012 2013 // If a simple-asm-expr is present, parse it. 2014 if (Tok.is(tok::kw_asm)) { 2015 SourceLocation Loc; 2016 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 2017 if (AsmLabel.isInvalid()) 2018 SkipUntil(tok::comma, true, true); 2019 2020 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 2021 DeclaratorInfo.SetRangeEnd(Loc); 2022 } 2023 2024 // If attributes exist after the declarator, parse them. 2025 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); 2026 2027 // FIXME: When g++ adds support for this, we'll need to check whether it 2028 // goes before or after the GNU attributes and __asm__. 2029 ParseOptionalCXX0XVirtSpecifierSeq(VS); 2030 2031 InClassInitStyle HasInClassInit = ICIS_NoInit; 2032 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) { 2033 if (BitfieldSize.get()) { 2034 Diag(Tok, diag::err_bitfield_member_init); 2035 SkipUntil(tok::comma, true, true); 2036 } else { 2037 HasInitializer = true; 2038 if (!DeclaratorInfo.isDeclarationOfFunction() && 2039 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 2040 != DeclSpec::SCS_static && 2041 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 2042 != DeclSpec::SCS_typedef) 2043 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit; 2044 } 2045 } 2046 2047 // NOTE: If Sema is the Action module and declarator is an instance field, 2048 // this call will *not* return the created decl; It will return null. 2049 // See Sema::ActOnCXXMemberDeclarator for details. 2050 2051 Decl *ThisDecl = 0; 2052 if (DS.isFriendSpecified()) { 2053 // TODO: handle initializers, bitfields, 'delete' 2054 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, 2055 TemplateParams); 2056 } else { 2057 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, 2058 DeclaratorInfo, 2059 TemplateParams, 2060 BitfieldSize.release(), 2061 VS, HasInClassInit); 2062 if (AccessAttrs) 2063 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs, 2064 false, true); 2065 } 2066 2067 // Set the Decl for any late parsed attributes 2068 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) { 2069 CommonLateParsedAttrs[i]->addDecl(ThisDecl); 2070 } 2071 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) { 2072 LateParsedAttrs[i]->addDecl(ThisDecl); 2073 } 2074 LateParsedAttrs.clear(); 2075 2076 // Handle the initializer. 2077 if (HasInClassInit != ICIS_NoInit) { 2078 // The initializer was deferred; parse it and cache the tokens. 2079 Diag(Tok, getLangOpts().CPlusPlus0x ? 2080 diag::warn_cxx98_compat_nonstatic_member_init : 2081 diag::ext_nonstatic_member_init); 2082 2083 if (DeclaratorInfo.isArrayOfUnknownBound()) { 2084 // C++11 [dcl.array]p3: An array bound may also be omitted when the 2085 // declarator is followed by an initializer. 2086 // 2087 // A brace-or-equal-initializer for a member-declarator is not an 2088 // initializer in the grammar, so this is ill-formed. 2089 Diag(Tok, diag::err_incomplete_array_member_init); 2090 SkipUntil(tok::comma, true, true); 2091 if (ThisDecl) 2092 // Avoid later warnings about a class member of incomplete type. 2093 ThisDecl->setInvalidDecl(); 2094 } else 2095 ParseCXXNonStaticMemberInitializer(ThisDecl); 2096 } else if (HasInitializer) { 2097 // Normal initializer. 2098 if (!Init.isUsable()) 2099 Init = ParseCXXMemberInitializer(ThisDecl, 2100 DeclaratorInfo.isDeclarationOfFunction(), EqualLoc); 2101 2102 if (Init.isInvalid()) 2103 SkipUntil(tok::comma, true, true); 2104 else if (ThisDecl) 2105 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(), 2106 DS.getTypeSpecType() == DeclSpec::TST_auto); 2107 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) { 2108 // No initializer. 2109 Actions.ActOnUninitializedDecl(ThisDecl, 2110 DS.getTypeSpecType() == DeclSpec::TST_auto); 2111 } 2112 2113 if (ThisDecl) { 2114 Actions.FinalizeDeclaration(ThisDecl); 2115 DeclsInGroup.push_back(ThisDecl); 2116 } 2117 2118 if (ThisDecl && DeclaratorInfo.isFunctionDeclarator() && 2119 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 2120 != DeclSpec::SCS_typedef) { 2121 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl); 2122 } 2123 2124 DeclaratorInfo.complete(ThisDecl); 2125 2126 // If we don't have a comma, it is either the end of the list (a ';') 2127 // or an error, bail out. 2128 if (Tok.isNot(tok::comma)) 2129 break; 2130 2131 // Consume the comma. 2132 SourceLocation CommaLoc = ConsumeToken(); 2133 2134 if (Tok.isAtStartOfLine() && 2135 !MightBeDeclarator(Declarator::MemberContext)) { 2136 // This comma was followed by a line-break and something which can't be 2137 // the start of a declarator. The comma was probably a typo for a 2138 // semicolon. 2139 Diag(CommaLoc, diag::err_expected_semi_declaration) 2140 << FixItHint::CreateReplacement(CommaLoc, ";"); 2141 ExpectSemi = false; 2142 break; 2143 } 2144 2145 // Parse the next declarator. 2146 DeclaratorInfo.clear(); 2147 VS.clear(); 2148 BitfieldSize = true; 2149 Init = true; 2150 HasInitializer = false; 2151 DeclaratorInfo.setCommaLoc(CommaLoc); 2152 2153 // Attributes are only allowed on the second declarator. 2154 MaybeParseGNUAttributes(DeclaratorInfo); 2155 2156 if (Tok.isNot(tok::colon)) 2157 ParseDeclarator(DeclaratorInfo); 2158 } 2159 2160 if (ExpectSemi && 2161 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { 2162 // Skip to end of block or statement. 2163 SkipUntil(tok::r_brace, true, true); 2164 // If we stopped at a ';', eat it. 2165 if (Tok.is(tok::semi)) ConsumeToken(); 2166 return; 2167 } 2168 2169 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(), 2170 DeclsInGroup.size()); 2171 } 2172 2173 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or 2174 /// pure-specifier. Also detect and reject any attempted defaulted/deleted 2175 /// function definition. The location of the '=', if any, will be placed in 2176 /// EqualLoc. 2177 /// 2178 /// pure-specifier: 2179 /// '= 0' 2180 /// 2181 /// brace-or-equal-initializer: 2182 /// '=' initializer-expression 2183 /// braced-init-list 2184 /// 2185 /// initializer-clause: 2186 /// assignment-expression 2187 /// braced-init-list 2188 /// 2189 /// defaulted/deleted function-definition: 2190 /// '=' 'default' 2191 /// '=' 'delete' 2192 /// 2193 /// Prior to C++0x, the assignment-expression in an initializer-clause must 2194 /// be a constant-expression. 2195 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction, 2196 SourceLocation &EqualLoc) { 2197 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace)) 2198 && "Data member initializer not starting with '=' or '{'"); 2199 2200 EnterExpressionEvaluationContext Context(Actions, 2201 Sema::PotentiallyEvaluated, 2202 D); 2203 if (Tok.is(tok::equal)) { 2204 EqualLoc = ConsumeToken(); 2205 if (Tok.is(tok::kw_delete)) { 2206 // In principle, an initializer of '= delete p;' is legal, but it will 2207 // never type-check. It's better to diagnose it as an ill-formed expression 2208 // than as an ill-formed deleted non-function member. 2209 // An initializer of '= delete p, foo' will never be parsed, because 2210 // a top-level comma always ends the initializer expression. 2211 const Token &Next = NextToken(); 2212 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) || 2213 Next.is(tok::eof)) { 2214 if (IsFunction) 2215 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) 2216 << 1 /* delete */; 2217 else 2218 Diag(ConsumeToken(), diag::err_deleted_non_function); 2219 return ExprResult(); 2220 } 2221 } else if (Tok.is(tok::kw_default)) { 2222 if (IsFunction) 2223 Diag(Tok, diag::err_default_delete_in_multiple_declaration) 2224 << 0 /* default */; 2225 else 2226 Diag(ConsumeToken(), diag::err_default_special_members); 2227 return ExprResult(); 2228 } 2229 2230 } 2231 return ParseInitializer(); 2232 } 2233 2234 /// ParseCXXMemberSpecification - Parse the class definition. 2235 /// 2236 /// member-specification: 2237 /// member-declaration member-specification[opt] 2238 /// access-specifier ':' member-specification[opt] 2239 /// 2240 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 2241 unsigned TagType, Decl *TagDecl) { 2242 assert((TagType == DeclSpec::TST_struct || 2243 TagType == DeclSpec::TST_interface || 2244 TagType == DeclSpec::TST_union || 2245 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 2246 2247 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 2248 "parsing struct/union/class body"); 2249 2250 // Determine whether this is a non-nested class. Note that local 2251 // classes are *not* considered to be nested classes. 2252 bool NonNestedClass = true; 2253 if (!ClassStack.empty()) { 2254 for (const Scope *S = getCurScope(); S; S = S->getParent()) { 2255 if (S->isClassScope()) { 2256 // We're inside a class scope, so this is a nested class. 2257 NonNestedClass = false; 2258 break; 2259 } 2260 2261 if ((S->getFlags() & Scope::FnScope)) { 2262 // If we're in a function or function template declared in the 2263 // body of a class, then this is a local class rather than a 2264 // nested class. 2265 const Scope *Parent = S->getParent(); 2266 if (Parent->isTemplateParamScope()) 2267 Parent = Parent->getParent(); 2268 if (Parent->isClassScope()) 2269 break; 2270 } 2271 } 2272 } 2273 2274 // Enter a scope for the class. 2275 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 2276 2277 // Note that we are parsing a new (potentially-nested) class definition. 2278 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass); 2279 2280 if (TagDecl) 2281 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 2282 2283 SourceLocation FinalLoc; 2284 2285 // Parse the optional 'final' keyword. 2286 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { 2287 assert(isCXX0XFinalKeyword() && "not a class definition"); 2288 FinalLoc = ConsumeToken(); 2289 2290 Diag(FinalLoc, getLangOpts().CPlusPlus0x ? 2291 diag::warn_cxx98_compat_override_control_keyword : 2292 diag::ext_override_control_keyword) << "final"; 2293 } 2294 2295 if (Tok.is(tok::colon)) { 2296 ParseBaseClause(TagDecl); 2297 2298 if (!Tok.is(tok::l_brace)) { 2299 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers); 2300 2301 if (TagDecl) 2302 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 2303 return; 2304 } 2305 } 2306 2307 assert(Tok.is(tok::l_brace)); 2308 BalancedDelimiterTracker T(*this, tok::l_brace); 2309 T.consumeOpen(); 2310 2311 if (TagDecl) 2312 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc, 2313 T.getOpenLocation()); 2314 2315 // C++ 11p3: Members of a class defined with the keyword class are private 2316 // by default. Members of a class defined with the keywords struct or union 2317 // are public by default. 2318 AccessSpecifier CurAS; 2319 if (TagType == DeclSpec::TST_class) 2320 CurAS = AS_private; 2321 else 2322 CurAS = AS_public; 2323 ParsedAttributes AccessAttrs(AttrFactory); 2324 2325 if (TagDecl) { 2326 // While we still have something to read, read the member-declarations. 2327 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 2328 // Each iteration of this loop reads one member-declaration. 2329 2330 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) || 2331 Tok.is(tok::kw___if_not_exists))) { 2332 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS); 2333 continue; 2334 } 2335 2336 // Check for extraneous top-level semicolon. 2337 if (Tok.is(tok::semi)) { 2338 ConsumeExtraSemi(InsideStruct, TagType); 2339 continue; 2340 } 2341 2342 if (Tok.is(tok::annot_pragma_vis)) { 2343 HandlePragmaVisibility(); 2344 continue; 2345 } 2346 2347 if (Tok.is(tok::annot_pragma_pack)) { 2348 HandlePragmaPack(); 2349 continue; 2350 } 2351 2352 AccessSpecifier AS = getAccessSpecifierIfPresent(); 2353 if (AS != AS_none) { 2354 // Current token is a C++ access specifier. 2355 CurAS = AS; 2356 SourceLocation ASLoc = Tok.getLocation(); 2357 unsigned TokLength = Tok.getLength(); 2358 ConsumeToken(); 2359 AccessAttrs.clear(); 2360 MaybeParseGNUAttributes(AccessAttrs); 2361 2362 SourceLocation EndLoc; 2363 if (Tok.is(tok::colon)) { 2364 EndLoc = Tok.getLocation(); 2365 ConsumeToken(); 2366 } else if (Tok.is(tok::semi)) { 2367 EndLoc = Tok.getLocation(); 2368 ConsumeToken(); 2369 Diag(EndLoc, diag::err_expected_colon) 2370 << FixItHint::CreateReplacement(EndLoc, ":"); 2371 } else { 2372 EndLoc = ASLoc.getLocWithOffset(TokLength); 2373 Diag(EndLoc, diag::err_expected_colon) 2374 << FixItHint::CreateInsertion(EndLoc, ":"); 2375 } 2376 2377 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc, 2378 AccessAttrs.getList())) { 2379 // found another attribute than only annotations 2380 AccessAttrs.clear(); 2381 } 2382 2383 continue; 2384 } 2385 2386 // FIXME: Make sure we don't have a template here. 2387 2388 // Parse all the comma separated declarators. 2389 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList()); 2390 } 2391 2392 T.consumeClose(); 2393 } else { 2394 SkipUntil(tok::r_brace, false, false); 2395 } 2396 2397 // If attributes exist after class contents, parse them. 2398 ParsedAttributes attrs(AttrFactory); 2399 MaybeParseGNUAttributes(attrs); 2400 2401 if (TagDecl) 2402 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, 2403 T.getOpenLocation(), 2404 T.getCloseLocation(), 2405 attrs.getList()); 2406 2407 // C++11 [class.mem]p2: 2408 // Within the class member-specification, the class is regarded as complete 2409 // within function bodies, default arguments, and 2410 // brace-or-equal-initializers for non-static data members (including such 2411 // things in nested classes). 2412 if (TagDecl && NonNestedClass) { 2413 // We are not inside a nested class. This class and its nested classes 2414 // are complete and we can parse the delayed portions of method 2415 // declarations and the lexed inline method definitions, along with any 2416 // delayed attributes. 2417 SourceLocation SavedPrevTokLocation = PrevTokLocation; 2418 ParseLexedAttributes(getCurrentClass()); 2419 ParseLexedMethodDeclarations(getCurrentClass()); 2420 2421 // We've finished with all pending member declarations. 2422 Actions.ActOnFinishCXXMemberDecls(); 2423 2424 ParseLexedMemberInitializers(getCurrentClass()); 2425 ParseLexedMethodDefs(getCurrentClass()); 2426 PrevTokLocation = SavedPrevTokLocation; 2427 } 2428 2429 if (TagDecl) 2430 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 2431 T.getCloseLocation()); 2432 2433 // Leave the class scope. 2434 ParsingDef.Pop(); 2435 ClassScope.Exit(); 2436 } 2437 2438 /// ParseConstructorInitializer - Parse a C++ constructor initializer, 2439 /// which explicitly initializes the members or base classes of a 2440 /// class (C++ [class.base.init]). For example, the three initializers 2441 /// after the ':' in the Derived constructor below: 2442 /// 2443 /// @code 2444 /// class Base { }; 2445 /// class Derived : Base { 2446 /// int x; 2447 /// float f; 2448 /// public: 2449 /// Derived(float f) : Base(), x(17), f(f) { } 2450 /// }; 2451 /// @endcode 2452 /// 2453 /// [C++] ctor-initializer: 2454 /// ':' mem-initializer-list 2455 /// 2456 /// [C++] mem-initializer-list: 2457 /// mem-initializer ...[opt] 2458 /// mem-initializer ...[opt] , mem-initializer-list 2459 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) { 2460 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 2461 2462 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers 2463 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 2464 SourceLocation ColonLoc = ConsumeToken(); 2465 2466 SmallVector<CXXCtorInitializer*, 4> MemInitializers; 2467 bool AnyErrors = false; 2468 2469 do { 2470 if (Tok.is(tok::code_completion)) { 2471 Actions.CodeCompleteConstructorInitializer(ConstructorDecl, 2472 MemInitializers.data(), 2473 MemInitializers.size()); 2474 return cutOffParsing(); 2475 } else { 2476 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 2477 if (!MemInit.isInvalid()) 2478 MemInitializers.push_back(MemInit.get()); 2479 else 2480 AnyErrors = true; 2481 } 2482 2483 if (Tok.is(tok::comma)) 2484 ConsumeToken(); 2485 else if (Tok.is(tok::l_brace)) 2486 break; 2487 // If the next token looks like a base or member initializer, assume that 2488 // we're just missing a comma. 2489 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) { 2490 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 2491 Diag(Loc, diag::err_ctor_init_missing_comma) 2492 << FixItHint::CreateInsertion(Loc, ", "); 2493 } else { 2494 // Skip over garbage, until we get to '{'. Don't eat the '{'. 2495 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 2496 SkipUntil(tok::l_brace, true, true); 2497 break; 2498 } 2499 } while (true); 2500 2501 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, 2502 MemInitializers.data(), MemInitializers.size(), 2503 AnyErrors); 2504 } 2505 2506 /// ParseMemInitializer - Parse a C++ member initializer, which is 2507 /// part of a constructor initializer that explicitly initializes one 2508 /// member or base class (C++ [class.base.init]). See 2509 /// ParseConstructorInitializer for an example. 2510 /// 2511 /// [C++] mem-initializer: 2512 /// mem-initializer-id '(' expression-list[opt] ')' 2513 /// [C++0x] mem-initializer-id braced-init-list 2514 /// 2515 /// [C++] mem-initializer-id: 2516 /// '::'[opt] nested-name-specifier[opt] class-name 2517 /// identifier 2518 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { 2519 // parse '::'[opt] nested-name-specifier[opt] 2520 CXXScopeSpec SS; 2521 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 2522 ParsedType TemplateTypeTy; 2523 if (Tok.is(tok::annot_template_id)) { 2524 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 2525 if (TemplateId->Kind == TNK_Type_template || 2526 TemplateId->Kind == TNK_Dependent_template_name) { 2527 AnnotateTemplateIdTokenAsType(); 2528 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 2529 TemplateTypeTy = getTypeAnnotation(Tok); 2530 } 2531 } 2532 // Uses of decltype will already have been converted to annot_decltype by 2533 // ParseOptionalCXXScopeSpecifier at this point. 2534 if (!TemplateTypeTy && Tok.isNot(tok::identifier) 2535 && Tok.isNot(tok::annot_decltype)) { 2536 Diag(Tok, diag::err_expected_member_or_base_name); 2537 return true; 2538 } 2539 2540 IdentifierInfo *II = 0; 2541 DeclSpec DS(AttrFactory); 2542 SourceLocation IdLoc = Tok.getLocation(); 2543 if (Tok.is(tok::annot_decltype)) { 2544 // Get the decltype expression, if there is one. 2545 ParseDecltypeSpecifier(DS); 2546 } else { 2547 if (Tok.is(tok::identifier)) 2548 // Get the identifier. This may be a member name or a class name, 2549 // but we'll let the semantic analysis determine which it is. 2550 II = Tok.getIdentifierInfo(); 2551 ConsumeToken(); 2552 } 2553 2554 2555 // Parse the '('. 2556 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 2557 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 2558 2559 ExprResult InitList = ParseBraceInitializer(); 2560 if (InitList.isInvalid()) 2561 return true; 2562 2563 SourceLocation EllipsisLoc; 2564 if (Tok.is(tok::ellipsis)) 2565 EllipsisLoc = ConsumeToken(); 2566 2567 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 2568 TemplateTypeTy, DS, IdLoc, 2569 InitList.take(), EllipsisLoc); 2570 } else if(Tok.is(tok::l_paren)) { 2571 BalancedDelimiterTracker T(*this, tok::l_paren); 2572 T.consumeOpen(); 2573 2574 // Parse the optional expression-list. 2575 ExprVector ArgExprs; 2576 CommaLocsTy CommaLocs; 2577 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 2578 SkipUntil(tok::r_paren); 2579 return true; 2580 } 2581 2582 T.consumeClose(); 2583 2584 SourceLocation EllipsisLoc; 2585 if (Tok.is(tok::ellipsis)) 2586 EllipsisLoc = ConsumeToken(); 2587 2588 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 2589 TemplateTypeTy, DS, IdLoc, 2590 T.getOpenLocation(), ArgExprs.data(), 2591 ArgExprs.size(), T.getCloseLocation(), 2592 EllipsisLoc); 2593 } 2594 2595 Diag(Tok, getLangOpts().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace 2596 : diag::err_expected_lparen); 2597 return true; 2598 } 2599 2600 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]). 2601 /// 2602 /// exception-specification: 2603 /// dynamic-exception-specification 2604 /// noexcept-specification 2605 /// 2606 /// noexcept-specification: 2607 /// 'noexcept' 2608 /// 'noexcept' '(' constant-expression ')' 2609 ExceptionSpecificationType 2610 Parser::tryParseExceptionSpecification( 2611 SourceRange &SpecificationRange, 2612 SmallVectorImpl<ParsedType> &DynamicExceptions, 2613 SmallVectorImpl<SourceRange> &DynamicExceptionRanges, 2614 ExprResult &NoexceptExpr) { 2615 ExceptionSpecificationType Result = EST_None; 2616 2617 // See if there's a dynamic specification. 2618 if (Tok.is(tok::kw_throw)) { 2619 Result = ParseDynamicExceptionSpecification(SpecificationRange, 2620 DynamicExceptions, 2621 DynamicExceptionRanges); 2622 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() && 2623 "Produced different number of exception types and ranges."); 2624 } 2625 2626 // If there's no noexcept specification, we're done. 2627 if (Tok.isNot(tok::kw_noexcept)) 2628 return Result; 2629 2630 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl); 2631 2632 // If we already had a dynamic specification, parse the noexcept for, 2633 // recovery, but emit a diagnostic and don't store the results. 2634 SourceRange NoexceptRange; 2635 ExceptionSpecificationType NoexceptType = EST_None; 2636 2637 SourceLocation KeywordLoc = ConsumeToken(); 2638 if (Tok.is(tok::l_paren)) { 2639 // There is an argument. 2640 BalancedDelimiterTracker T(*this, tok::l_paren); 2641 T.consumeOpen(); 2642 NoexceptType = EST_ComputedNoexcept; 2643 NoexceptExpr = ParseConstantExpression(); 2644 // The argument must be contextually convertible to bool. We use 2645 // ActOnBooleanCondition for this purpose. 2646 if (!NoexceptExpr.isInvalid()) 2647 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc, 2648 NoexceptExpr.get()); 2649 T.consumeClose(); 2650 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation()); 2651 } else { 2652 // There is no argument. 2653 NoexceptType = EST_BasicNoexcept; 2654 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc); 2655 } 2656 2657 if (Result == EST_None) { 2658 SpecificationRange = NoexceptRange; 2659 Result = NoexceptType; 2660 2661 // If there's a dynamic specification after a noexcept specification, 2662 // parse that and ignore the results. 2663 if (Tok.is(tok::kw_throw)) { 2664 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 2665 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions, 2666 DynamicExceptionRanges); 2667 } 2668 } else { 2669 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 2670 } 2671 2672 return Result; 2673 } 2674 2675 /// ParseDynamicExceptionSpecification - Parse a C++ 2676 /// dynamic-exception-specification (C++ [except.spec]). 2677 /// 2678 /// dynamic-exception-specification: 2679 /// 'throw' '(' type-id-list [opt] ')' 2680 /// [MS] 'throw' '(' '...' ')' 2681 /// 2682 /// type-id-list: 2683 /// type-id ... [opt] 2684 /// type-id-list ',' type-id ... [opt] 2685 /// 2686 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification( 2687 SourceRange &SpecificationRange, 2688 SmallVectorImpl<ParsedType> &Exceptions, 2689 SmallVectorImpl<SourceRange> &Ranges) { 2690 assert(Tok.is(tok::kw_throw) && "expected throw"); 2691 2692 SpecificationRange.setBegin(ConsumeToken()); 2693 BalancedDelimiterTracker T(*this, tok::l_paren); 2694 if (T.consumeOpen()) { 2695 Diag(Tok, diag::err_expected_lparen_after) << "throw"; 2696 SpecificationRange.setEnd(SpecificationRange.getBegin()); 2697 return EST_DynamicNone; 2698 } 2699 2700 // Parse throw(...), a Microsoft extension that means "this function 2701 // can throw anything". 2702 if (Tok.is(tok::ellipsis)) { 2703 SourceLocation EllipsisLoc = ConsumeToken(); 2704 if (!getLangOpts().MicrosoftExt) 2705 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 2706 T.consumeClose(); 2707 SpecificationRange.setEnd(T.getCloseLocation()); 2708 return EST_MSAny; 2709 } 2710 2711 // Parse the sequence of type-ids. 2712 SourceRange Range; 2713 while (Tok.isNot(tok::r_paren)) { 2714 TypeResult Res(ParseTypeName(&Range)); 2715 2716 if (Tok.is(tok::ellipsis)) { 2717 // C++0x [temp.variadic]p5: 2718 // - In a dynamic-exception-specification (15.4); the pattern is a 2719 // type-id. 2720 SourceLocation Ellipsis = ConsumeToken(); 2721 Range.setEnd(Ellipsis); 2722 if (!Res.isInvalid()) 2723 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis); 2724 } 2725 2726 if (!Res.isInvalid()) { 2727 Exceptions.push_back(Res.get()); 2728 Ranges.push_back(Range); 2729 } 2730 2731 if (Tok.is(tok::comma)) 2732 ConsumeToken(); 2733 else 2734 break; 2735 } 2736 2737 T.consumeClose(); 2738 SpecificationRange.setEnd(T.getCloseLocation()); 2739 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic; 2740 } 2741 2742 /// ParseTrailingReturnType - Parse a trailing return type on a new-style 2743 /// function declaration. 2744 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) { 2745 assert(Tok.is(tok::arrow) && "expected arrow"); 2746 2747 ConsumeToken(); 2748 2749 return ParseTypeName(&Range, Declarator::TrailingReturnContext); 2750 } 2751 2752 /// \brief We have just started parsing the definition of a new class, 2753 /// so push that class onto our stack of classes that is currently 2754 /// being parsed. 2755 Sema::ParsingClassState 2756 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) { 2757 assert((NonNestedClass || !ClassStack.empty()) && 2758 "Nested class without outer class"); 2759 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass)); 2760 return Actions.PushParsingClass(); 2761 } 2762 2763 /// \brief Deallocate the given parsed class and all of its nested 2764 /// classes. 2765 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 2766 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I) 2767 delete Class->LateParsedDeclarations[I]; 2768 delete Class; 2769 } 2770 2771 /// \brief Pop the top class of the stack of classes that are 2772 /// currently being parsed. 2773 /// 2774 /// This routine should be called when we have finished parsing the 2775 /// definition of a class, but have not yet popped the Scope 2776 /// associated with the class's definition. 2777 void Parser::PopParsingClass(Sema::ParsingClassState state) { 2778 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 2779 2780 Actions.PopParsingClass(state); 2781 2782 ParsingClass *Victim = ClassStack.top(); 2783 ClassStack.pop(); 2784 if (Victim->TopLevelClass) { 2785 // Deallocate all of the nested classes of this class, 2786 // recursively: we don't need to keep any of this information. 2787 DeallocateParsedClasses(Victim); 2788 return; 2789 } 2790 assert(!ClassStack.empty() && "Missing top-level class?"); 2791 2792 if (Victim->LateParsedDeclarations.empty()) { 2793 // The victim is a nested class, but we will not need to perform 2794 // any processing after the definition of this class since it has 2795 // no members whose handling was delayed. Therefore, we can just 2796 // remove this nested class. 2797 DeallocateParsedClasses(Victim); 2798 return; 2799 } 2800 2801 // This nested class has some members that will need to be processed 2802 // after the top-level class is completely defined. Therefore, add 2803 // it to the list of nested classes within its parent. 2804 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?"); 2805 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim)); 2806 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope(); 2807 } 2808 2809 /// \brief Try to parse an 'identifier' which appears within an attribute-token. 2810 /// 2811 /// \return the parsed identifier on success, and 0 if the next token is not an 2812 /// attribute-token. 2813 /// 2814 /// C++11 [dcl.attr.grammar]p3: 2815 /// If a keyword or an alternative token that satisfies the syntactic 2816 /// requirements of an identifier is contained in an attribute-token, 2817 /// it is considered an identifier. 2818 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) { 2819 switch (Tok.getKind()) { 2820 default: 2821 // Identifiers and keywords have identifier info attached. 2822 if (IdentifierInfo *II = Tok.getIdentifierInfo()) { 2823 Loc = ConsumeToken(); 2824 return II; 2825 } 2826 return 0; 2827 2828 case tok::ampamp: // 'and' 2829 case tok::pipe: // 'bitor' 2830 case tok::pipepipe: // 'or' 2831 case tok::caret: // 'xor' 2832 case tok::tilde: // 'compl' 2833 case tok::amp: // 'bitand' 2834 case tok::ampequal: // 'and_eq' 2835 case tok::pipeequal: // 'or_eq' 2836 case tok::caretequal: // 'xor_eq' 2837 case tok::exclaim: // 'not' 2838 case tok::exclaimequal: // 'not_eq' 2839 // Alternative tokens do not have identifier info, but their spelling 2840 // starts with an alphabetical character. 2841 llvm::SmallString<8> SpellingBuf; 2842 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf); 2843 if (std::isalpha(Spelling[0])) { 2844 Loc = ConsumeToken(); 2845 return &PP.getIdentifierTable().get(Spelling); 2846 } 2847 return 0; 2848 } 2849 } 2850 2851 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently 2852 /// only parses standard attributes. 2853 /// 2854 /// [C++11] attribute-specifier: 2855 /// '[' '[' attribute-list ']' ']' 2856 /// alignment-specifier 2857 /// 2858 /// [C++11] attribute-list: 2859 /// attribute[opt] 2860 /// attribute-list ',' attribute[opt] 2861 /// attribute '...' 2862 /// attribute-list ',' attribute '...' 2863 /// 2864 /// [C++11] attribute: 2865 /// attribute-token attribute-argument-clause[opt] 2866 /// 2867 /// [C++11] attribute-token: 2868 /// identifier 2869 /// attribute-scoped-token 2870 /// 2871 /// [C++11] attribute-scoped-token: 2872 /// attribute-namespace '::' identifier 2873 /// 2874 /// [C++11] attribute-namespace: 2875 /// identifier 2876 /// 2877 /// [C++11] attribute-argument-clause: 2878 /// '(' balanced-token-seq ')' 2879 /// 2880 /// [C++11] balanced-token-seq: 2881 /// balanced-token 2882 /// balanced-token-seq balanced-token 2883 /// 2884 /// [C++11] balanced-token: 2885 /// '(' balanced-token-seq ')' 2886 /// '[' balanced-token-seq ']' 2887 /// '{' balanced-token-seq '}' 2888 /// any token but '(', ')', '[', ']', '{', or '}' 2889 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, 2890 SourceLocation *endLoc) { 2891 if (Tok.is(tok::kw_alignas)) { 2892 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas); 2893 ParseAlignmentSpecifier(attrs, endLoc); 2894 return; 2895 } 2896 2897 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) 2898 && "Not a C++11 attribute list"); 2899 2900 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute); 2901 2902 ConsumeBracket(); 2903 ConsumeBracket(); 2904 2905 while (Tok.isNot(tok::r_square)) { 2906 // attribute not present 2907 if (Tok.is(tok::comma)) { 2908 ConsumeToken(); 2909 continue; 2910 } 2911 2912 SourceLocation ScopeLoc, AttrLoc; 2913 IdentifierInfo *ScopeName = 0, *AttrName = 0; 2914 2915 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); 2916 if (!AttrName) 2917 // Break out to the "expected ']'" diagnostic. 2918 break; 2919 2920 // scoped attribute 2921 if (Tok.is(tok::coloncolon)) { 2922 ConsumeToken(); 2923 2924 ScopeName = AttrName; 2925 ScopeLoc = AttrLoc; 2926 2927 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); 2928 if (!AttrName) { 2929 Diag(Tok.getLocation(), diag::err_expected_ident); 2930 SkipUntil(tok::r_square, tok::comma, true, true); 2931 continue; 2932 } 2933 } 2934 2935 bool AttrParsed = false; 2936 switch (AttributeList::getKind(AttrName, ScopeName, 2937 AttributeList::AS_CXX11)) { 2938 // No arguments 2939 case AttributeList::AT_CarriesDependency: 2940 // FIXME: implement generic support of attributes with C++11 syntax 2941 // see Parse/ParseDecl.cpp: ParseGNUAttributes 2942 case AttributeList::AT_FallThrough: 2943 case AttributeList::AT_NoReturn: { 2944 if (Tok.is(tok::l_paren)) { 2945 Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments) 2946 << AttrName->getName(); 2947 break; 2948 } 2949 2950 attrs.addNew(AttrName, 2951 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, 2952 AttrLoc), 2953 ScopeName, ScopeLoc, 0, 2954 SourceLocation(), 0, 0, AttributeList::AS_CXX11); 2955 AttrParsed = true; 2956 break; 2957 } 2958 2959 // Silence warnings 2960 default: break; 2961 } 2962 2963 // Skip the entire parameter clause, if any 2964 if (!AttrParsed && Tok.is(tok::l_paren)) { 2965 ConsumeParen(); 2966 // SkipUntil maintains the balancedness of tokens. 2967 SkipUntil(tok::r_paren, false); 2968 } 2969 2970 if (Tok.is(tok::ellipsis)) { 2971 if (AttrParsed) 2972 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis) 2973 << AttrName->getName(); 2974 ConsumeToken(); 2975 } 2976 } 2977 2978 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2979 SkipUntil(tok::r_square, false); 2980 if (endLoc) 2981 *endLoc = Tok.getLocation(); 2982 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2983 SkipUntil(tok::r_square, false); 2984 } 2985 2986 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq. 2987 /// 2988 /// attribute-specifier-seq: 2989 /// attribute-specifier-seq[opt] attribute-specifier 2990 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs, 2991 SourceLocation *endLoc) { 2992 SourceLocation StartLoc = Tok.getLocation(), Loc; 2993 if (!endLoc) 2994 endLoc = &Loc; 2995 2996 do { 2997 ParseCXX11AttributeSpecifier(attrs, endLoc); 2998 } while (isCXX11AttributeSpecifier()); 2999 3000 attrs.Range = SourceRange(StartLoc, *endLoc); 3001 } 3002 3003 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr] 3004 /// 3005 /// [MS] ms-attribute: 3006 /// '[' token-seq ']' 3007 /// 3008 /// [MS] ms-attribute-seq: 3009 /// ms-attribute[opt] 3010 /// ms-attribute ms-attribute-seq 3011 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs, 3012 SourceLocation *endLoc) { 3013 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list"); 3014 3015 while (Tok.is(tok::l_square)) { 3016 // FIXME: If this is actually a C++11 attribute, parse it as one. 3017 ConsumeBracket(); 3018 SkipUntil(tok::r_square, true, true); 3019 if (endLoc) *endLoc = Tok.getLocation(); 3020 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); 3021 } 3022 } 3023 3024 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, 3025 AccessSpecifier& CurAS) { 3026 IfExistsCondition Result; 3027 if (ParseMicrosoftIfExistsCondition(Result)) 3028 return; 3029 3030 BalancedDelimiterTracker Braces(*this, tok::l_brace); 3031 if (Braces.consumeOpen()) { 3032 Diag(Tok, diag::err_expected_lbrace); 3033 return; 3034 } 3035 3036 switch (Result.Behavior) { 3037 case IEB_Parse: 3038 // Parse the declarations below. 3039 break; 3040 3041 case IEB_Dependent: 3042 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) 3043 << Result.IsIfExists; 3044 // Fall through to skip. 3045 3046 case IEB_Skip: 3047 Braces.skipToEnd(); 3048 return; 3049 } 3050 3051 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 3052 // __if_exists, __if_not_exists can nest. 3053 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) { 3054 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS); 3055 continue; 3056 } 3057 3058 // Check for extraneous top-level semicolon. 3059 if (Tok.is(tok::semi)) { 3060 ConsumeExtraSemi(InsideStruct, TagType); 3061 continue; 3062 } 3063 3064 AccessSpecifier AS = getAccessSpecifierIfPresent(); 3065 if (AS != AS_none) { 3066 // Current token is a C++ access specifier. 3067 CurAS = AS; 3068 SourceLocation ASLoc = Tok.getLocation(); 3069 ConsumeToken(); 3070 if (Tok.is(tok::colon)) 3071 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation()); 3072 else 3073 Diag(Tok, diag::err_expected_colon); 3074 ConsumeToken(); 3075 continue; 3076 } 3077 3078 // Parse all the comma separated declarators. 3079 ParseCXXClassMemberDeclaration(CurAS, 0); 3080 } 3081 3082 Braces.consumeClose(); 3083 } 3084