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