ParseDeclCXX.cpp revision 37bf9d2bb74944c9d9a52522412bc077629977f1
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 56 if (Tok.is(tok::code_completion)) { 57 Actions.CodeCompleteNamespaceDecl(getCurScope()); 58 ConsumeCodeCompletionToken(); 59 } 60 61 SourceLocation IdentLoc; 62 IdentifierInfo *Ident = 0; 63 64 Token attrTok; 65 66 if (Tok.is(tok::identifier)) { 67 Ident = Tok.getIdentifierInfo(); 68 IdentLoc = ConsumeToken(); // eat the identifier. 69 } 70 71 // Read label attributes, if present. 72 llvm::OwningPtr<AttributeList> AttrList; 73 if (Tok.is(tok::kw___attribute)) { 74 attrTok = Tok; 75 76 // FIXME: save these somewhere. 77 AttrList.reset(ParseGNUAttributes()); 78 } 79 80 if (Tok.is(tok::equal)) { 81 if (AttrList) 82 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias); 83 if (InlineLoc.isValid()) 84 Diag(InlineLoc, diag::err_inline_namespace_alias) 85 << FixItHint::CreateRemoval(InlineLoc); 86 87 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd); 88 } 89 90 if (Tok.isNot(tok::l_brace)) { 91 Diag(Tok, Ident ? diag::err_expected_lbrace : 92 diag::err_expected_ident_lbrace); 93 return 0; 94 } 95 96 SourceLocation LBrace = ConsumeBrace(); 97 98 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || 99 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || 100 getCurScope()->getFnParent()) { 101 Diag(LBrace, diag::err_namespace_nonnamespace_scope); 102 SkipUntil(tok::r_brace, false); 103 return 0; 104 } 105 106 // If we're still good, complain about inline namespaces in non-C++0x now. 107 if (!getLang().CPlusPlus0x && InlineLoc.isValid()) 108 Diag(InlineLoc, diag::ext_inline_namespace); 109 110 // Enter a scope for the namespace. 111 ParseScope NamespaceScope(this, Scope::DeclScope); 112 113 Decl *NamespcDecl = 114 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, IdentLoc, Ident, 115 LBrace, AttrList.get()); 116 117 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc, 118 "parsing namespace"); 119 120 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 121 CXX0XAttributeList Attr; 122 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) 123 Attr = ParseCXX0XAttributes(); 124 ParseExternalDeclaration(Attr); 125 } 126 127 // Leave the namespace scope. 128 NamespaceScope.Exit(); 129 130 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBrace); 131 Actions.ActOnFinishNamespaceDef(NamespcDecl, RBraceLoc); 132 133 DeclEnd = RBraceLoc; 134 return NamespcDecl; 135} 136 137/// ParseNamespaceAlias - Parse the part after the '=' in a namespace 138/// alias definition. 139/// 140Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, 141 SourceLocation AliasLoc, 142 IdentifierInfo *Alias, 143 SourceLocation &DeclEnd) { 144 assert(Tok.is(tok::equal) && "Not equal token"); 145 146 ConsumeToken(); // eat the '='. 147 148 if (Tok.is(tok::code_completion)) { 149 Actions.CodeCompleteNamespaceAliasDecl(getCurScope()); 150 ConsumeCodeCompletionToken(); 151 } 152 153 CXXScopeSpec SS; 154 // Parse (optional) nested-name-specifier. 155 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 156 157 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 158 Diag(Tok, diag::err_expected_namespace_name); 159 // Skip to end of the definition and eat the ';'. 160 SkipUntil(tok::semi); 161 return 0; 162 } 163 164 // Parse identifier. 165 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 166 SourceLocation IdentLoc = ConsumeToken(); 167 168 // Eat the ';'. 169 DeclEnd = Tok.getLocation(); 170 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name, 171 "", tok::semi); 172 173 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias, 174 SS, IdentLoc, Ident); 175} 176 177/// ParseLinkage - We know that the current token is a string_literal 178/// and just before that, that extern was seen. 179/// 180/// linkage-specification: [C++ 7.5p2: dcl.link] 181/// 'extern' string-literal '{' declaration-seq[opt] '}' 182/// 'extern' string-literal declaration 183/// 184Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, 185 unsigned Context) { 186 assert(Tok.is(tok::string_literal) && "Not a string literal!"); 187 llvm::SmallString<8> LangBuffer; 188 // LangBuffer is guaranteed to be big enough. 189 bool Invalid = false; 190 llvm::StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid); 191 if (Invalid) 192 return 0; 193 194 SourceLocation Loc = ConsumeStringToken(); 195 196 ParseScope LinkageScope(this, Scope::DeclScope); 197 Decl *LinkageSpec 198 = Actions.ActOnStartLinkageSpecification(getCurScope(), 199 /*FIXME: */SourceLocation(), 200 Loc, Lang, 201 Tok.is(tok::l_brace)? Tok.getLocation() 202 : SourceLocation()); 203 204 CXX0XAttributeList Attr; 205 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 206 Attr = ParseCXX0XAttributes(); 207 } 208 209 if (Tok.isNot(tok::l_brace)) { 210 DS.setExternInLinkageSpec(true); 211 ParseExternalDeclaration(Attr, &DS); 212 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, 213 SourceLocation()); 214 } 215 216 DS.abort(); 217 218 if (Attr.HasAttr) 219 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 220 << Attr.Range; 221 222 SourceLocation LBrace = ConsumeBrace(); 223 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 224 CXX0XAttributeList Attr; 225 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) 226 Attr = ParseCXX0XAttributes(); 227 ParseExternalDeclaration(Attr); 228 } 229 230 SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace); 231 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, RBrace); 232} 233 234/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or 235/// using-directive. Assumes that current token is 'using'. 236Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context, 237 SourceLocation &DeclEnd, 238 CXX0XAttributeList Attr) { 239 assert(Tok.is(tok::kw_using) && "Not using token"); 240 241 // Eat 'using'. 242 SourceLocation UsingLoc = ConsumeToken(); 243 244 if (Tok.is(tok::code_completion)) { 245 Actions.CodeCompleteUsing(getCurScope()); 246 ConsumeCodeCompletionToken(); 247 } 248 249 if (Tok.is(tok::kw_namespace)) 250 // Next token after 'using' is 'namespace' so it must be using-directive 251 return ParseUsingDirective(Context, UsingLoc, DeclEnd, Attr.AttrList); 252 253 if (Attr.HasAttr) 254 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 255 << Attr.Range; 256 257 // Otherwise, it must be using-declaration. 258 // Ignore illegal attributes (the caller should already have issued an error. 259 return ParseUsingDeclaration(Context, UsingLoc, DeclEnd); 260} 261 262/// ParseUsingDirective - Parse C++ using-directive, assumes 263/// that current token is 'namespace' and 'using' was already parsed. 264/// 265/// using-directive: [C++ 7.3.p4: namespace.udir] 266/// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 267/// namespace-name ; 268/// [GNU] using-directive: 269/// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 270/// namespace-name attributes[opt] ; 271/// 272Decl *Parser::ParseUsingDirective(unsigned Context, 273 SourceLocation UsingLoc, 274 SourceLocation &DeclEnd, 275 AttributeList *Attr) { 276 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token"); 277 278 // Eat 'namespace'. 279 SourceLocation NamespcLoc = ConsumeToken(); 280 281 if (Tok.is(tok::code_completion)) { 282 Actions.CodeCompleteUsingDirective(getCurScope()); 283 ConsumeCodeCompletionToken(); 284 } 285 286 CXXScopeSpec SS; 287 // Parse (optional) nested-name-specifier. 288 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 289 290 IdentifierInfo *NamespcName = 0; 291 SourceLocation IdentLoc = SourceLocation(); 292 293 // Parse namespace-name. 294 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 295 Diag(Tok, diag::err_expected_namespace_name); 296 // If there was invalid namespace name, skip to end of decl, and eat ';'. 297 SkipUntil(tok::semi); 298 // FIXME: Are there cases, when we would like to call ActOnUsingDirective? 299 return 0; 300 } 301 302 // Parse identifier. 303 NamespcName = Tok.getIdentifierInfo(); 304 IdentLoc = ConsumeToken(); 305 306 // Parse (optional) attributes (most likely GNU strong-using extension). 307 bool GNUAttr = false; 308 if (Tok.is(tok::kw___attribute)) { 309 GNUAttr = true; 310 Attr = addAttributeLists(Attr, ParseGNUAttributes()); 311 } 312 313 // Eat ';'. 314 DeclEnd = Tok.getLocation(); 315 ExpectAndConsume(tok::semi, 316 GNUAttr ? diag::err_expected_semi_after_attribute_list 317 : diag::err_expected_semi_after_namespace_name, 318 "", tok::semi); 319 320 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS, 321 IdentLoc, NamespcName, Attr); 322} 323 324/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that 325/// 'using' was already seen. 326/// 327/// using-declaration: [C++ 7.3.p3: namespace.udecl] 328/// 'using' 'typename'[opt] ::[opt] nested-name-specifier 329/// unqualified-id 330/// 'using' :: unqualified-id 331/// 332Decl *Parser::ParseUsingDeclaration(unsigned Context, 333 SourceLocation UsingLoc, 334 SourceLocation &DeclEnd, 335 AccessSpecifier AS) { 336 CXXScopeSpec SS; 337 SourceLocation TypenameLoc; 338 bool IsTypeName; 339 340 // Ignore optional 'typename'. 341 // FIXME: This is wrong; we should parse this as a typename-specifier. 342 if (Tok.is(tok::kw_typename)) { 343 TypenameLoc = Tok.getLocation(); 344 ConsumeToken(); 345 IsTypeName = true; 346 } 347 else 348 IsTypeName = false; 349 350 // Parse nested-name-specifier. 351 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 352 353 // Check nested-name specifier. 354 if (SS.isInvalid()) { 355 SkipUntil(tok::semi); 356 return 0; 357 } 358 359 // Parse the unqualified-id. We allow parsing of both constructor and 360 // destructor names and allow the action module to diagnose any semantic 361 // errors. 362 UnqualifiedId Name; 363 if (ParseUnqualifiedId(SS, 364 /*EnteringContext=*/false, 365 /*AllowDestructorName=*/true, 366 /*AllowConstructorName=*/true, 367 ParsedType(), 368 Name)) { 369 SkipUntil(tok::semi); 370 return 0; 371 } 372 373 // Parse (optional) attributes (most likely GNU strong-using extension). 374 llvm::OwningPtr<AttributeList> AttrList; 375 if (Tok.is(tok::kw___attribute)) 376 AttrList.reset(ParseGNUAttributes()); 377 378 // Eat ';'. 379 DeclEnd = Tok.getLocation(); 380 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 381 AttrList ? "attributes list" : "using declaration", 382 tok::semi); 383 384 return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS, Name, 385 AttrList.get(), IsTypeName, TypenameLoc); 386} 387 388/// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion. 389/// 390/// static_assert-declaration: 391/// static_assert ( constant-expression , string-literal ) ; 392/// 393Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ 394 assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration"); 395 SourceLocation StaticAssertLoc = ConsumeToken(); 396 397 if (Tok.isNot(tok::l_paren)) { 398 Diag(Tok, diag::err_expected_lparen); 399 return 0; 400 } 401 402 SourceLocation LParenLoc = ConsumeParen(); 403 404 ExprResult AssertExpr(ParseConstantExpression()); 405 if (AssertExpr.isInvalid()) { 406 SkipUntil(tok::semi); 407 return 0; 408 } 409 410 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi)) 411 return 0; 412 413 if (Tok.isNot(tok::string_literal)) { 414 Diag(Tok, diag::err_expected_string_literal); 415 SkipUntil(tok::semi); 416 return 0; 417 } 418 419 ExprResult AssertMessage(ParseStringLiteralExpression()); 420 if (AssertMessage.isInvalid()) 421 return 0; 422 423 MatchRHSPunctuation(tok::r_paren, LParenLoc); 424 425 DeclEnd = Tok.getLocation(); 426 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert); 427 428 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, 429 AssertExpr.take(), 430 AssertMessage.take()); 431} 432 433/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier. 434/// 435/// 'decltype' ( expression ) 436/// 437void Parser::ParseDecltypeSpecifier(DeclSpec &DS) { 438 assert(Tok.is(tok::kw_decltype) && "Not a decltype specifier"); 439 440 SourceLocation StartLoc = ConsumeToken(); 441 SourceLocation LParenLoc = Tok.getLocation(); 442 443 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 444 "decltype")) { 445 SkipUntil(tok::r_paren); 446 return; 447 } 448 449 // Parse the expression 450 451 // C++0x [dcl.type.simple]p4: 452 // The operand of the decltype specifier is an unevaluated operand. 453 EnterExpressionEvaluationContext Unevaluated(Actions, 454 Sema::Unevaluated); 455 ExprResult Result = ParseExpression(); 456 if (Result.isInvalid()) { 457 SkipUntil(tok::r_paren); 458 return; 459 } 460 461 // Match the ')' 462 SourceLocation RParenLoc; 463 if (Tok.is(tok::r_paren)) 464 RParenLoc = ConsumeParen(); 465 else 466 MatchRHSPunctuation(tok::r_paren, LParenLoc); 467 468 if (RParenLoc.isInvalid()) 469 return; 470 471 const char *PrevSpec = 0; 472 unsigned DiagID; 473 // Check for duplicate type specifiers (e.g. "int decltype(a)"). 474 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, 475 DiagID, Result.release())) 476 Diag(StartLoc, DiagID) << PrevSpec; 477} 478 479/// ParseClassName - Parse a C++ class-name, which names a class. Note 480/// that we only check that the result names a type; semantic analysis 481/// will need to verify that the type names a class. The result is 482/// either a type or NULL, depending on whether a type name was 483/// found. 484/// 485/// class-name: [C++ 9.1] 486/// identifier 487/// simple-template-id 488/// 489Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation, 490 CXXScopeSpec *SS) { 491 // Check whether we have a template-id that names a type. 492 if (Tok.is(tok::annot_template_id)) { 493 TemplateIdAnnotation *TemplateId 494 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 495 if (TemplateId->Kind == TNK_Type_template || 496 TemplateId->Kind == TNK_Dependent_template_name) { 497 AnnotateTemplateIdTokenAsType(SS); 498 499 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 500 ParsedType Type = getTypeAnnotation(Tok); 501 EndLocation = Tok.getAnnotationEndLoc(); 502 ConsumeToken(); 503 504 if (Type) 505 return Type; 506 return true; 507 } 508 509 // Fall through to produce an error below. 510 } 511 512 if (Tok.isNot(tok::identifier)) { 513 Diag(Tok, diag::err_expected_class_name); 514 return true; 515 } 516 517 IdentifierInfo *Id = Tok.getIdentifierInfo(); 518 SourceLocation IdLoc = ConsumeToken(); 519 520 if (Tok.is(tok::less)) { 521 // It looks the user intended to write a template-id here, but the 522 // template-name was wrong. Try to fix that. 523 TemplateNameKind TNK = TNK_Type_template; 524 TemplateTy Template; 525 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(), 526 SS, Template, TNK)) { 527 Diag(IdLoc, diag::err_unknown_template_name) 528 << Id; 529 } 530 531 if (!Template) 532 return true; 533 534 // Form the template name 535 UnqualifiedId TemplateName; 536 TemplateName.setIdentifier(Id, IdLoc); 537 538 // Parse the full template-id, then turn it into a type. 539 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName, 540 SourceLocation(), true)) 541 return true; 542 if (TNK == TNK_Dependent_template_name) 543 AnnotateTemplateIdTokenAsType(SS); 544 545 // If we didn't end up with a typename token, there's nothing more we 546 // can do. 547 if (Tok.isNot(tok::annot_typename)) 548 return true; 549 550 // Retrieve the type from the annotation token, consume that token, and 551 // return. 552 EndLocation = Tok.getAnnotationEndLoc(); 553 ParsedType Type = getTypeAnnotation(Tok); 554 ConsumeToken(); 555 return Type; 556 } 557 558 // We have an identifier; check whether it is actually a type. 559 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), SS, true); 560 if (!Type) { 561 Diag(IdLoc, diag::err_expected_class_name); 562 return true; 563 } 564 565 // Consume the identifier. 566 EndLocation = IdLoc; 567 568 // Fake up a Declarator to use with ActOnTypeName. 569 DeclSpec DS; 570 DS.SetRangeStart(IdLoc); 571 DS.SetRangeEnd(EndLocation); 572 DS.getTypeSpecScope() = *SS; 573 574 const char *PrevSpec = 0; 575 unsigned DiagID; 576 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type); 577 578 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 579 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 580} 581 582/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or 583/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which 584/// until we reach the start of a definition or see a token that 585/// cannot start a definition. If SuppressDeclarations is true, we do know. 586/// 587/// class-specifier: [C++ class] 588/// class-head '{' member-specification[opt] '}' 589/// class-head '{' member-specification[opt] '}' attributes[opt] 590/// class-head: 591/// class-key identifier[opt] base-clause[opt] 592/// class-key nested-name-specifier identifier base-clause[opt] 593/// class-key nested-name-specifier[opt] simple-template-id 594/// base-clause[opt] 595/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] 596/// [GNU] class-key attributes[opt] nested-name-specifier 597/// identifier base-clause[opt] 598/// [GNU] class-key attributes[opt] nested-name-specifier[opt] 599/// simple-template-id base-clause[opt] 600/// class-key: 601/// 'class' 602/// 'struct' 603/// 'union' 604/// 605/// elaborated-type-specifier: [C++ dcl.type.elab] 606/// class-key ::[opt] nested-name-specifier[opt] identifier 607/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] 608/// simple-template-id 609/// 610/// Note that the C++ class-specifier and elaborated-type-specifier, 611/// together, subsume the C99 struct-or-union-specifier: 612/// 613/// struct-or-union-specifier: [C99 6.7.2.1] 614/// struct-or-union identifier[opt] '{' struct-contents '}' 615/// struct-or-union identifier 616/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents 617/// '}' attributes[opt] 618/// [GNU] struct-or-union attributes[opt] identifier 619/// struct-or-union: 620/// 'struct' 621/// 'union' 622void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, 623 SourceLocation StartLoc, DeclSpec &DS, 624 const ParsedTemplateInfo &TemplateInfo, 625 AccessSpecifier AS, bool SuppressDeclarations){ 626 DeclSpec::TST TagType; 627 if (TagTokKind == tok::kw_struct) 628 TagType = DeclSpec::TST_struct; 629 else if (TagTokKind == tok::kw_class) 630 TagType = DeclSpec::TST_class; 631 else { 632 assert(TagTokKind == tok::kw_union && "Not a class specifier"); 633 TagType = DeclSpec::TST_union; 634 } 635 636 if (Tok.is(tok::code_completion)) { 637 // Code completion for a struct, class, or union name. 638 Actions.CodeCompleteTag(getCurScope(), TagType); 639 ConsumeCodeCompletionToken(); 640 } 641 642 // C++03 [temp.explicit] 14.7.2/8: 643 // The usual access checking rules do not apply to names used to specify 644 // explicit instantiations. 645 // 646 // As an extension we do not perform access checking on the names used to 647 // specify explicit specializations either. This is important to allow 648 // specializing traits classes for private types. 649 bool SuppressingAccessChecks = false; 650 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 651 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) { 652 Actions.ActOnStartSuppressingAccessChecks(); 653 SuppressingAccessChecks = true; 654 } 655 656 AttributeList *AttrList = 0; 657 // If attributes exist after tag, parse them. 658 if (Tok.is(tok::kw___attribute)) 659 AttrList = ParseGNUAttributes(); 660 661 // If declspecs exist after tag, parse them. 662 while (Tok.is(tok::kw___declspec)) 663 AttrList = ParseMicrosoftDeclSpec(AttrList); 664 665 // If C++0x attributes exist here, parse them. 666 // FIXME: Are we consistent with the ordering of parsing of different 667 // styles of attributes? 668 if (isCXX0XAttributeSpecifier()) 669 AttrList = addAttributeLists(AttrList, ParseCXX0XAttributes().AttrList); 670 671 if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_pod)) { 672 // GNU libstdc++ 4.2 uses __is_pod as the name of a struct template, but 673 // __is_pod is a keyword in GCC >= 4.3. Therefore, when we see the 674 // token sequence "struct __is_pod", make __is_pod into a normal 675 // identifier rather than a keyword, to allow libstdc++ 4.2 to work 676 // properly. 677 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 678 Tok.setKind(tok::identifier); 679 } 680 681 if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_empty)) { 682 // GNU libstdc++ 4.2 uses __is_empty as the name of a struct template, but 683 // __is_empty is a keyword in GCC >= 4.3. Therefore, when we see the 684 // token sequence "struct __is_empty", make __is_empty into a normal 685 // identifier rather than a keyword, to allow libstdc++ 4.2 to work 686 // properly. 687 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 688 Tok.setKind(tok::identifier); 689 } 690 691 // Parse the (optional) nested-name-specifier. 692 CXXScopeSpec &SS = DS.getTypeSpecScope(); 693 if (getLang().CPlusPlus) { 694 // "FOO : BAR" is not a potential typo for "FOO::BAR". 695 ColonProtectionRAIIObject X(*this); 696 697 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) 698 DS.SetTypeSpecError(); 699 if (SS.isSet()) 700 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 701 Diag(Tok, diag::err_expected_ident); 702 } 703 704 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 705 706 // Parse the (optional) class name or simple-template-id. 707 IdentifierInfo *Name = 0; 708 SourceLocation NameLoc; 709 TemplateIdAnnotation *TemplateId = 0; 710 if (Tok.is(tok::identifier)) { 711 Name = Tok.getIdentifierInfo(); 712 NameLoc = ConsumeToken(); 713 714 if (Tok.is(tok::less) && getLang().CPlusPlus) { 715 // The name was supposed to refer to a template, but didn't. 716 // Eat the template argument list and try to continue parsing this as 717 // a class (or template thereof). 718 TemplateArgList TemplateArgs; 719 SourceLocation LAngleLoc, RAngleLoc; 720 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, &SS, 721 true, LAngleLoc, 722 TemplateArgs, RAngleLoc)) { 723 // We couldn't parse the template argument list at all, so don't 724 // try to give any location information for the list. 725 LAngleLoc = RAngleLoc = SourceLocation(); 726 } 727 728 Diag(NameLoc, diag::err_explicit_spec_non_template) 729 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 730 << (TagType == DeclSpec::TST_class? 0 731 : TagType == DeclSpec::TST_struct? 1 732 : 2) 733 << Name 734 << SourceRange(LAngleLoc, RAngleLoc); 735 736 // Strip off the last template parameter list if it was empty, since 737 // we've removed its template argument list. 738 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) { 739 if (TemplateParams && TemplateParams->size() > 1) { 740 TemplateParams->pop_back(); 741 } else { 742 TemplateParams = 0; 743 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 744 = ParsedTemplateInfo::NonTemplate; 745 } 746 } else if (TemplateInfo.Kind 747 == ParsedTemplateInfo::ExplicitInstantiation) { 748 // Pretend this is just a forward declaration. 749 TemplateParams = 0; 750 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 751 = ParsedTemplateInfo::NonTemplate; 752 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc 753 = SourceLocation(); 754 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc 755 = SourceLocation(); 756 } 757 } 758 } else if (Tok.is(tok::annot_template_id)) { 759 TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 760 NameLoc = ConsumeToken(); 761 762 if (TemplateId->Kind != TNK_Type_template) { 763 // The template-name in the simple-template-id refers to 764 // something other than a class template. Give an appropriate 765 // error message and skip to the ';'. 766 SourceRange Range(NameLoc); 767 if (SS.isNotEmpty()) 768 Range.setBegin(SS.getBeginLoc()); 769 770 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) 771 << Name << static_cast<int>(TemplateId->Kind) << Range; 772 773 DS.SetTypeSpecError(); 774 SkipUntil(tok::semi, false, true); 775 TemplateId->Destroy(); 776 if (SuppressingAccessChecks) 777 Actions.ActOnStopSuppressingAccessChecks(); 778 779 return; 780 } 781 } 782 783 // As soon as we're finished parsing the class's template-id, turn access 784 // checking back on. 785 if (SuppressingAccessChecks) 786 Actions.ActOnStopSuppressingAccessChecks(); 787 788 // There are four options here. If we have 'struct foo;', then this 789 // is either a forward declaration or a friend declaration, which 790 // have to be treated differently. If we have 'struct foo {...' or 791 // 'struct foo :...' then this is a definition. Otherwise we have 792 // something like 'struct foo xyz', a reference. 793 // However, in some contexts, things look like declarations but are just 794 // references, e.g. 795 // new struct s; 796 // or 797 // &T::operator struct s; 798 // For these, SuppressDeclarations is true. 799 Sema::TagUseKind TUK; 800 if (SuppressDeclarations) 801 TUK = Sema::TUK_Reference; 802 else if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))){ 803 if (DS.isFriendSpecified()) { 804 // C++ [class.friend]p2: 805 // A class shall not be defined in a friend declaration. 806 Diag(Tok.getLocation(), diag::err_friend_decl_defines_class) 807 << SourceRange(DS.getFriendSpecLoc()); 808 809 // Skip everything up to the semicolon, so that this looks like a proper 810 // friend class (or template thereof) declaration. 811 SkipUntil(tok::semi, true, true); 812 TUK = Sema::TUK_Friend; 813 } else { 814 // Okay, this is a class definition. 815 TUK = Sema::TUK_Definition; 816 } 817 } else if (Tok.is(tok::semi)) 818 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 819 else 820 TUK = Sema::TUK_Reference; 821 822 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error || 823 TUK != Sema::TUK_Definition)) { 824 if (DS.getTypeSpecType() != DeclSpec::TST_error) { 825 // We have a declaration or reference to an anonymous class. 826 Diag(StartLoc, diag::err_anon_type_definition) 827 << DeclSpec::getSpecifierName(TagType); 828 } 829 830 SkipUntil(tok::comma, true); 831 832 if (TemplateId) 833 TemplateId->Destroy(); 834 return; 835 } 836 837 // Create the tag portion of the class or class template. 838 DeclResult TagOrTempResult = true; // invalid 839 TypeResult TypeResult = true; // invalid 840 841 bool Owned = false; 842 if (TemplateId) { 843 // Explicit specialization, class template partial specialization, 844 // or explicit instantiation. 845 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 846 TemplateId->getTemplateArgs(), 847 TemplateId->NumArgs); 848 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 849 TUK == Sema::TUK_Declaration) { 850 // This is an explicit instantiation of a class template. 851 TagOrTempResult 852 = Actions.ActOnExplicitInstantiation(getCurScope(), 853 TemplateInfo.ExternLoc, 854 TemplateInfo.TemplateLoc, 855 TagType, 856 StartLoc, 857 SS, 858 TemplateId->Template, 859 TemplateId->TemplateNameLoc, 860 TemplateId->LAngleLoc, 861 TemplateArgsPtr, 862 TemplateId->RAngleLoc, 863 AttrList); 864 865 // Friend template-ids are treated as references unless 866 // they have template headers, in which case they're ill-formed 867 // (FIXME: "template <class T> friend class A<T>::B<int>;"). 868 // We diagnose this error in ActOnClassTemplateSpecialization. 869 } else if (TUK == Sema::TUK_Reference || 870 (TUK == Sema::TUK_Friend && 871 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) { 872 TypeResult 873 = Actions.ActOnTemplateIdType(TemplateId->Template, 874 TemplateId->TemplateNameLoc, 875 TemplateId->LAngleLoc, 876 TemplateArgsPtr, 877 TemplateId->RAngleLoc); 878 879 TypeResult = Actions.ActOnTagTemplateIdType(TypeResult, TUK, 880 TagType, StartLoc); 881 } else { 882 // This is an explicit specialization or a class template 883 // partial specialization. 884 TemplateParameterLists FakedParamLists; 885 886 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 887 // This looks like an explicit instantiation, because we have 888 // something like 889 // 890 // template class Foo<X> 891 // 892 // but it actually has a definition. Most likely, this was 893 // meant to be an explicit specialization, but the user forgot 894 // the '<>' after 'template'. 895 assert(TUK == Sema::TUK_Definition && "Expected a definition here"); 896 897 SourceLocation LAngleLoc 898 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 899 Diag(TemplateId->TemplateNameLoc, 900 diag::err_explicit_instantiation_with_definition) 901 << SourceRange(TemplateInfo.TemplateLoc) 902 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 903 904 // Create a fake template parameter list that contains only 905 // "template<>", so that we treat this construct as a class 906 // template specialization. 907 FakedParamLists.push_back( 908 Actions.ActOnTemplateParameterList(0, SourceLocation(), 909 TemplateInfo.TemplateLoc, 910 LAngleLoc, 911 0, 0, 912 LAngleLoc)); 913 TemplateParams = &FakedParamLists; 914 } 915 916 // Build the class template specialization. 917 TagOrTempResult 918 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK, 919 StartLoc, SS, 920 TemplateId->Template, 921 TemplateId->TemplateNameLoc, 922 TemplateId->LAngleLoc, 923 TemplateArgsPtr, 924 TemplateId->RAngleLoc, 925 AttrList, 926 MultiTemplateParamsArg(Actions, 927 TemplateParams? &(*TemplateParams)[0] : 0, 928 TemplateParams? TemplateParams->size() : 0)); 929 } 930 TemplateId->Destroy(); 931 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 932 TUK == Sema::TUK_Declaration) { 933 // Explicit instantiation of a member of a class template 934 // specialization, e.g., 935 // 936 // template struct Outer<int>::Inner; 937 // 938 TagOrTempResult 939 = Actions.ActOnExplicitInstantiation(getCurScope(), 940 TemplateInfo.ExternLoc, 941 TemplateInfo.TemplateLoc, 942 TagType, StartLoc, SS, Name, 943 NameLoc, AttrList); 944 } else { 945 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 946 TUK == Sema::TUK_Definition) { 947 // FIXME: Diagnose this particular error. 948 } 949 950 bool IsDependent = false; 951 952 // Declaration or definition of a class type 953 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc, SS, 954 Name, NameLoc, AttrList, AS, 955 MultiTemplateParamsArg(Actions, 956 TemplateParams? &(*TemplateParams)[0] : 0, 957 TemplateParams? TemplateParams->size() : 0), 958 Owned, IsDependent); 959 960 // If ActOnTag said the type was dependent, try again with the 961 // less common call. 962 if (IsDependent) 963 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, 964 SS, Name, StartLoc, NameLoc); 965 } 966 967 // If there is a body, parse it and inform the actions module. 968 if (TUK == Sema::TUK_Definition) { 969 assert(Tok.is(tok::l_brace) || 970 (getLang().CPlusPlus && Tok.is(tok::colon))); 971 if (getLang().CPlusPlus) 972 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get()); 973 else 974 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); 975 } 976 977 // FIXME: The DeclSpec should keep the locations of both the keyword and the 978 // name (if there is one). 979 SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc; 980 981 const char *PrevSpec = 0; 982 unsigned DiagID; 983 bool Result; 984 if (!TypeResult.isInvalid()) { 985 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, TSTLoc, 986 PrevSpec, DiagID, TypeResult.get()); 987 } else if (!TagOrTempResult.isInvalid()) { 988 Result = DS.SetTypeSpecType(TagType, TSTLoc, PrevSpec, DiagID, 989 TagOrTempResult.get(), Owned); 990 } else { 991 DS.SetTypeSpecError(); 992 return; 993 } 994 995 if (Result) 996 Diag(StartLoc, DiagID) << PrevSpec; 997 998 // At this point, we've successfully parsed a class-specifier in 'definition' 999 // form (e.g. "struct foo { int x; }". While we could just return here, we're 1000 // going to look at what comes after it to improve error recovery. If an 1001 // impossible token occurs next, we assume that the programmer forgot a ; at 1002 // the end of the declaration and recover that way. 1003 // 1004 // This switch enumerates the valid "follow" set for definition. 1005 if (TUK == Sema::TUK_Definition) { 1006 bool ExpectedSemi = true; 1007 switch (Tok.getKind()) { 1008 default: break; 1009 case tok::semi: // struct foo {...} ; 1010 case tok::star: // struct foo {...} * P; 1011 case tok::amp: // struct foo {...} & R = ... 1012 case tok::identifier: // struct foo {...} V ; 1013 case tok::r_paren: //(struct foo {...} ) {4} 1014 case tok::annot_cxxscope: // struct foo {...} a:: b; 1015 case tok::annot_typename: // struct foo {...} a ::b; 1016 case tok::annot_template_id: // struct foo {...} a<int> ::b; 1017 case tok::l_paren: // struct foo {...} ( x); 1018 case tok::comma: // __builtin_offsetof(struct foo{...} , 1019 ExpectedSemi = false; 1020 break; 1021 // Type qualifiers 1022 case tok::kw_const: // struct foo {...} const x; 1023 case tok::kw_volatile: // struct foo {...} volatile x; 1024 case tok::kw_restrict: // struct foo {...} restrict x; 1025 case tok::kw_inline: // struct foo {...} inline foo() {}; 1026 // Storage-class specifiers 1027 case tok::kw_static: // struct foo {...} static x; 1028 case tok::kw_extern: // struct foo {...} extern x; 1029 case tok::kw_typedef: // struct foo {...} typedef x; 1030 case tok::kw_register: // struct foo {...} register x; 1031 case tok::kw_auto: // struct foo {...} auto x; 1032 case tok::kw_mutable: // struct foo {...} mutable x; 1033 // As shown above, type qualifiers and storage class specifiers absolutely 1034 // can occur after class specifiers according to the grammar. However, 1035 // almost noone actually writes code like this. If we see one of these, 1036 // it is much more likely that someone missed a semi colon and the 1037 // type/storage class specifier we're seeing is part of the *next* 1038 // intended declaration, as in: 1039 // 1040 // struct foo { ... } 1041 // typedef int X; 1042 // 1043 // We'd really like to emit a missing semicolon error instead of emitting 1044 // an error on the 'int' saying that you can't have two type specifiers in 1045 // the same declaration of X. Because of this, we look ahead past this 1046 // token to see if it's a type specifier. If so, we know the code is 1047 // otherwise invalid, so we can produce the expected semi error. 1048 if (!isKnownToBeTypeSpecifier(NextToken())) 1049 ExpectedSemi = false; 1050 break; 1051 1052 case tok::r_brace: // struct bar { struct foo {...} } 1053 // Missing ';' at end of struct is accepted as an extension in C mode. 1054 if (!getLang().CPlusPlus) 1055 ExpectedSemi = false; 1056 break; 1057 } 1058 1059 if (ExpectedSemi) { 1060 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 1061 TagType == DeclSpec::TST_class ? "class" 1062 : TagType == DeclSpec::TST_struct? "struct" : "union"); 1063 // Push this token back into the preprocessor and change our current token 1064 // to ';' so that the rest of the code recovers as though there were an 1065 // ';' after the definition. 1066 PP.EnterToken(Tok); 1067 Tok.setKind(tok::semi); 1068 } 1069 } 1070} 1071 1072/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 1073/// 1074/// base-clause : [C++ class.derived] 1075/// ':' base-specifier-list 1076/// base-specifier-list: 1077/// base-specifier '...'[opt] 1078/// base-specifier-list ',' base-specifier '...'[opt] 1079void Parser::ParseBaseClause(Decl *ClassDecl) { 1080 assert(Tok.is(tok::colon) && "Not a base clause"); 1081 ConsumeToken(); 1082 1083 // Build up an array of parsed base specifiers. 1084 llvm::SmallVector<CXXBaseSpecifier *, 8> BaseInfo; 1085 1086 while (true) { 1087 // Parse a base-specifier. 1088 BaseResult Result = ParseBaseSpecifier(ClassDecl); 1089 if (Result.isInvalid()) { 1090 // Skip the rest of this base specifier, up until the comma or 1091 // opening brace. 1092 SkipUntil(tok::comma, tok::l_brace, true, true); 1093 } else { 1094 // Add this to our array of base specifiers. 1095 BaseInfo.push_back(Result.get()); 1096 } 1097 1098 // If the next token is a comma, consume it and keep reading 1099 // base-specifiers. 1100 if (Tok.isNot(tok::comma)) break; 1101 1102 // Consume the comma. 1103 ConsumeToken(); 1104 } 1105 1106 // Attach the base specifiers 1107 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); 1108} 1109 1110/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 1111/// one entry in the base class list of a class specifier, for example: 1112/// class foo : public bar, virtual private baz { 1113/// 'public bar' and 'virtual private baz' are each base-specifiers. 1114/// 1115/// base-specifier: [C++ class.derived] 1116/// ::[opt] nested-name-specifier[opt] class-name 1117/// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt] 1118/// class-name 1119/// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt] 1120/// class-name 1121Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) { 1122 bool IsVirtual = false; 1123 SourceLocation StartLoc = Tok.getLocation(); 1124 1125 // Parse the 'virtual' keyword. 1126 if (Tok.is(tok::kw_virtual)) { 1127 ConsumeToken(); 1128 IsVirtual = true; 1129 } 1130 1131 // Parse an (optional) access specifier. 1132 AccessSpecifier Access = getAccessSpecifierIfPresent(); 1133 if (Access != AS_none) 1134 ConsumeToken(); 1135 1136 // Parse the 'virtual' keyword (again!), in case it came after the 1137 // access specifier. 1138 if (Tok.is(tok::kw_virtual)) { 1139 SourceLocation VirtualLoc = ConsumeToken(); 1140 if (IsVirtual) { 1141 // Complain about duplicate 'virtual' 1142 Diag(VirtualLoc, diag::err_dup_virtual) 1143 << FixItHint::CreateRemoval(VirtualLoc); 1144 } 1145 1146 IsVirtual = true; 1147 } 1148 1149 // Parse optional '::' and optional nested-name-specifier. 1150 CXXScopeSpec SS; 1151 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 1152 1153 // The location of the base class itself. 1154 SourceLocation BaseLoc = Tok.getLocation(); 1155 1156 // Parse the class-name. 1157 SourceLocation EndLocation; 1158 TypeResult BaseType = ParseClassName(EndLocation, &SS); 1159 if (BaseType.isInvalid()) 1160 return true; 1161 1162 // Find the complete source range for the base-specifier. 1163 SourceRange Range(StartLoc, EndLocation); 1164 1165 // Notify semantic analysis that we have parsed a complete 1166 // base-specifier. 1167 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, 1168 BaseType.get(), BaseLoc); 1169} 1170 1171/// getAccessSpecifierIfPresent - Determine whether the next token is 1172/// a C++ access-specifier. 1173/// 1174/// access-specifier: [C++ class.derived] 1175/// 'private' 1176/// 'protected' 1177/// 'public' 1178AccessSpecifier Parser::getAccessSpecifierIfPresent() const { 1179 switch (Tok.getKind()) { 1180 default: return AS_none; 1181 case tok::kw_private: return AS_private; 1182 case tok::kw_protected: return AS_protected; 1183 case tok::kw_public: return AS_public; 1184 } 1185} 1186 1187void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo, 1188 Decl *ThisDecl) { 1189 // We just declared a member function. If this member function 1190 // has any default arguments, we'll need to parse them later. 1191 LateParsedMethodDeclaration *LateMethod = 0; 1192 DeclaratorChunk::FunctionTypeInfo &FTI 1193 = DeclaratorInfo.getTypeObject(0).Fun; 1194 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { 1195 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { 1196 if (!LateMethod) { 1197 // Push this method onto the stack of late-parsed method 1198 // declarations. 1199 getCurrentClass().MethodDecls.push_back( 1200 LateParsedMethodDeclaration(ThisDecl)); 1201 LateMethod = &getCurrentClass().MethodDecls.back(); 1202 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope(); 1203 1204 // Add all of the parameters prior to this one (they don't 1205 // have default arguments). 1206 LateMethod->DefaultArgs.reserve(FTI.NumArgs); 1207 for (unsigned I = 0; I < ParamIdx; ++I) 1208 LateMethod->DefaultArgs.push_back( 1209 LateParsedDefaultArgument(FTI.ArgInfo[I].Param)); 1210 } 1211 1212 // Add this parameter to the list of parameters (it or may 1213 // not have a default argument). 1214 LateMethod->DefaultArgs.push_back( 1215 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param, 1216 FTI.ArgInfo[ParamIdx].DefaultArgTokens)); 1217 } 1218 } 1219} 1220 1221/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 1222/// 1223/// member-declaration: 1224/// decl-specifier-seq[opt] member-declarator-list[opt] ';' 1225/// function-definition ';'[opt] 1226/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 1227/// using-declaration [TODO] 1228/// [C++0x] static_assert-declaration 1229/// template-declaration 1230/// [GNU] '__extension__' member-declaration 1231/// 1232/// member-declarator-list: 1233/// member-declarator 1234/// member-declarator-list ',' member-declarator 1235/// 1236/// member-declarator: 1237/// declarator pure-specifier[opt] 1238/// declarator constant-initializer[opt] 1239/// identifier[opt] ':' constant-expression 1240/// 1241/// pure-specifier: 1242/// '= 0' 1243/// 1244/// constant-initializer: 1245/// '=' constant-expression 1246/// 1247void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, 1248 const ParsedTemplateInfo &TemplateInfo, 1249 ParsingDeclRAIIObject *TemplateDiags) { 1250 // Access declarations. 1251 if (!TemplateInfo.Kind && 1252 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) && 1253 !TryAnnotateCXXScopeToken() && 1254 Tok.is(tok::annot_cxxscope)) { 1255 bool isAccessDecl = false; 1256 if (NextToken().is(tok::identifier)) 1257 isAccessDecl = GetLookAheadToken(2).is(tok::semi); 1258 else 1259 isAccessDecl = NextToken().is(tok::kw_operator); 1260 1261 if (isAccessDecl) { 1262 // Collect the scope specifier token we annotated earlier. 1263 CXXScopeSpec SS; 1264 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 1265 1266 // Try to parse an unqualified-id. 1267 UnqualifiedId Name; 1268 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), Name)) { 1269 SkipUntil(tok::semi); 1270 return; 1271 } 1272 1273 // TODO: recover from mistakenly-qualified operator declarations. 1274 if (ExpectAndConsume(tok::semi, 1275 diag::err_expected_semi_after, 1276 "access declaration", 1277 tok::semi)) 1278 return; 1279 1280 Actions.ActOnUsingDeclaration(getCurScope(), AS, 1281 false, SourceLocation(), 1282 SS, Name, 1283 /* AttrList */ 0, 1284 /* IsTypeName */ false, 1285 SourceLocation()); 1286 return; 1287 } 1288 } 1289 1290 // static_assert-declaration 1291 if (Tok.is(tok::kw_static_assert)) { 1292 // FIXME: Check for templates 1293 SourceLocation DeclEnd; 1294 ParseStaticAssertDeclaration(DeclEnd); 1295 return; 1296 } 1297 1298 if (Tok.is(tok::kw_template)) { 1299 assert(!TemplateInfo.TemplateParams && 1300 "Nested template improperly parsed?"); 1301 SourceLocation DeclEnd; 1302 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, 1303 AS); 1304 return; 1305 } 1306 1307 // Handle: member-declaration ::= '__extension__' member-declaration 1308 if (Tok.is(tok::kw___extension__)) { 1309 // __extension__ silences extension warnings in the subexpression. 1310 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1311 ConsumeToken(); 1312 return ParseCXXClassMemberDeclaration(AS, TemplateInfo, TemplateDiags); 1313 } 1314 1315 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it 1316 // is a bitfield. 1317 ColonProtectionRAIIObject X(*this); 1318 1319 CXX0XAttributeList AttrList; 1320 // Optional C++0x attribute-specifier 1321 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) 1322 AttrList = ParseCXX0XAttributes(); 1323 1324 if (Tok.is(tok::kw_using)) { 1325 // FIXME: Check for template aliases 1326 1327 if (AttrList.HasAttr) 1328 Diag(AttrList.Range.getBegin(), diag::err_attributes_not_allowed) 1329 << AttrList.Range; 1330 1331 // Eat 'using'. 1332 SourceLocation UsingLoc = ConsumeToken(); 1333 1334 if (Tok.is(tok::kw_namespace)) { 1335 Diag(UsingLoc, diag::err_using_namespace_in_class); 1336 SkipUntil(tok::semi, true, true); 1337 } else { 1338 SourceLocation DeclEnd; 1339 // Otherwise, it must be using-declaration. 1340 ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd, AS); 1341 } 1342 return; 1343 } 1344 1345 SourceLocation DSStart = Tok.getLocation(); 1346 // decl-specifier-seq: 1347 // Parse the common declaration-specifiers piece. 1348 ParsingDeclSpec DS(*this, TemplateDiags); 1349 DS.AddAttributes(AttrList.AttrList); 1350 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class); 1351 1352 MultiTemplateParamsArg TemplateParams(Actions, 1353 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0, 1354 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0); 1355 1356 if (Tok.is(tok::semi)) { 1357 ConsumeToken(); 1358 Decl *TheDecl = 1359 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS); 1360 DS.complete(TheDecl); 1361 return; 1362 } 1363 1364 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext); 1365 1366 if (Tok.isNot(tok::colon)) { 1367 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 1368 ColonProtectionRAIIObject X(*this); 1369 1370 // Parse the first declarator. 1371 ParseDeclarator(DeclaratorInfo); 1372 // Error parsing the declarator? 1373 if (!DeclaratorInfo.hasName()) { 1374 // If so, skip until the semi-colon or a }. 1375 SkipUntil(tok::r_brace, true); 1376 if (Tok.is(tok::semi)) 1377 ConsumeToken(); 1378 return; 1379 } 1380 1381 // If attributes exist after the declarator, but before an '{', parse them. 1382 if (Tok.is(tok::kw___attribute)) { 1383 SourceLocation Loc; 1384 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1385 DeclaratorInfo.AddAttributes(AttrList, Loc); 1386 } 1387 1388 // function-definition: 1389 if (Tok.is(tok::l_brace) 1390 || (DeclaratorInfo.isFunctionDeclarator() && 1391 (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) { 1392 if (!DeclaratorInfo.isFunctionDeclarator()) { 1393 Diag(Tok, diag::err_func_def_no_params); 1394 ConsumeBrace(); 1395 SkipUntil(tok::r_brace, true); 1396 return; 1397 } 1398 1399 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1400 Diag(Tok, diag::err_function_declared_typedef); 1401 // This recovery skips the entire function body. It would be nice 1402 // to simply call ParseCXXInlineMethodDef() below, however Sema 1403 // assumes the declarator represents a function, not a typedef. 1404 ConsumeBrace(); 1405 SkipUntil(tok::r_brace, true); 1406 return; 1407 } 1408 1409 ParseCXXInlineMethodDef(AS, DeclaratorInfo, TemplateInfo); 1410 return; 1411 } 1412 } 1413 1414 // member-declarator-list: 1415 // member-declarator 1416 // member-declarator-list ',' member-declarator 1417 1418 llvm::SmallVector<Decl *, 8> DeclsInGroup; 1419 ExprResult BitfieldSize; 1420 ExprResult Init; 1421 bool Deleted = false; 1422 1423 while (1) { 1424 // member-declarator: 1425 // declarator pure-specifier[opt] 1426 // declarator constant-initializer[opt] 1427 // identifier[opt] ':' constant-expression 1428 if (Tok.is(tok::colon)) { 1429 ConsumeToken(); 1430 BitfieldSize = ParseConstantExpression(); 1431 if (BitfieldSize.isInvalid()) 1432 SkipUntil(tok::comma, true, true); 1433 } 1434 1435 // pure-specifier: 1436 // '= 0' 1437 // 1438 // constant-initializer: 1439 // '=' constant-expression 1440 // 1441 // defaulted/deleted function-definition: 1442 // '=' 'default' [TODO] 1443 // '=' 'delete' 1444 if (Tok.is(tok::equal)) { 1445 ConsumeToken(); 1446 if (Tok.is(tok::kw_delete)) { 1447 if (!getLang().CPlusPlus0x) 1448 Diag(Tok, diag::warn_deleted_function_accepted_as_extension); 1449 ConsumeToken(); 1450 Deleted = true; 1451 } else { 1452 Init = ParseInitializer(); 1453 if (Init.isInvalid()) 1454 SkipUntil(tok::comma, true, true); 1455 } 1456 } 1457 1458 // If a simple-asm-expr is present, parse it. 1459 if (Tok.is(tok::kw_asm)) { 1460 SourceLocation Loc; 1461 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1462 if (AsmLabel.isInvalid()) 1463 SkipUntil(tok::comma, true, true); 1464 1465 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 1466 DeclaratorInfo.SetRangeEnd(Loc); 1467 } 1468 1469 // If attributes exist after the declarator, parse them. 1470 if (Tok.is(tok::kw___attribute)) { 1471 SourceLocation Loc; 1472 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1473 DeclaratorInfo.AddAttributes(AttrList, Loc); 1474 } 1475 1476 // NOTE: If Sema is the Action module and declarator is an instance field, 1477 // this call will *not* return the created decl; It will return null. 1478 // See Sema::ActOnCXXMemberDeclarator for details. 1479 1480 Decl *ThisDecl = 0; 1481 if (DS.isFriendSpecified()) { 1482 // TODO: handle initializers, bitfields, 'delete' 1483 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, 1484 /*IsDefinition*/ false, 1485 move(TemplateParams)); 1486 } else { 1487 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, 1488 DeclaratorInfo, 1489 move(TemplateParams), 1490 BitfieldSize.release(), 1491 Init.release(), 1492 /*IsDefinition*/Deleted, 1493 Deleted); 1494 } 1495 if (ThisDecl) 1496 DeclsInGroup.push_back(ThisDecl); 1497 1498 if (DeclaratorInfo.isFunctionDeclarator() && 1499 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 1500 != DeclSpec::SCS_typedef) { 1501 HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl); 1502 } 1503 1504 DeclaratorInfo.complete(ThisDecl); 1505 1506 // If we don't have a comma, it is either the end of the list (a ';') 1507 // or an error, bail out. 1508 if (Tok.isNot(tok::comma)) 1509 break; 1510 1511 // Consume the comma. 1512 ConsumeToken(); 1513 1514 // Parse the next declarator. 1515 DeclaratorInfo.clear(); 1516 BitfieldSize = 0; 1517 Init = 0; 1518 Deleted = false; 1519 1520 // Attributes are only allowed on the second declarator. 1521 if (Tok.is(tok::kw___attribute)) { 1522 SourceLocation Loc; 1523 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1524 DeclaratorInfo.AddAttributes(AttrList, Loc); 1525 } 1526 1527 if (Tok.isNot(tok::colon)) 1528 ParseDeclarator(DeclaratorInfo); 1529 } 1530 1531 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { 1532 // Skip to end of block or statement. 1533 SkipUntil(tok::r_brace, true, true); 1534 // If we stopped at a ';', eat it. 1535 if (Tok.is(tok::semi)) ConsumeToken(); 1536 return; 1537 } 1538 1539 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(), 1540 DeclsInGroup.size()); 1541} 1542 1543/// ParseCXXMemberSpecification - Parse the class definition. 1544/// 1545/// member-specification: 1546/// member-declaration member-specification[opt] 1547/// access-specifier ':' member-specification[opt] 1548/// 1549void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 1550 unsigned TagType, Decl *TagDecl) { 1551 assert((TagType == DeclSpec::TST_struct || 1552 TagType == DeclSpec::TST_union || 1553 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 1554 1555 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 1556 "parsing struct/union/class body"); 1557 1558 // Determine whether this is a non-nested class. Note that local 1559 // classes are *not* considered to be nested classes. 1560 bool NonNestedClass = true; 1561 if (!ClassStack.empty()) { 1562 for (const Scope *S = getCurScope(); S; S = S->getParent()) { 1563 if (S->isClassScope()) { 1564 // We're inside a class scope, so this is a nested class. 1565 NonNestedClass = false; 1566 break; 1567 } 1568 1569 if ((S->getFlags() & Scope::FnScope)) { 1570 // If we're in a function or function template declared in the 1571 // body of a class, then this is a local class rather than a 1572 // nested class. 1573 const Scope *Parent = S->getParent(); 1574 if (Parent->isTemplateParamScope()) 1575 Parent = Parent->getParent(); 1576 if (Parent->isClassScope()) 1577 break; 1578 } 1579 } 1580 } 1581 1582 // Enter a scope for the class. 1583 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 1584 1585 // Note that we are parsing a new (potentially-nested) class definition. 1586 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass); 1587 1588 if (TagDecl) 1589 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 1590 1591 if (Tok.is(tok::colon)) { 1592 ParseBaseClause(TagDecl); 1593 1594 if (!Tok.is(tok::l_brace)) { 1595 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers); 1596 1597 if (TagDecl) 1598 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 1599 return; 1600 } 1601 } 1602 1603 assert(Tok.is(tok::l_brace)); 1604 1605 SourceLocation LBraceLoc = ConsumeBrace(); 1606 1607 if (TagDecl) 1608 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, LBraceLoc); 1609 1610 // C++ 11p3: Members of a class defined with the keyword class are private 1611 // by default. Members of a class defined with the keywords struct or union 1612 // are public by default. 1613 AccessSpecifier CurAS; 1614 if (TagType == DeclSpec::TST_class) 1615 CurAS = AS_private; 1616 else 1617 CurAS = AS_public; 1618 1619 SourceLocation RBraceLoc; 1620 if (TagDecl) { 1621 // While we still have something to read, read the member-declarations. 1622 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1623 // Each iteration of this loop reads one member-declaration. 1624 1625 // Check for extraneous top-level semicolon. 1626 if (Tok.is(tok::semi)) { 1627 Diag(Tok, diag::ext_extra_struct_semi) 1628 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType) 1629 << FixItHint::CreateRemoval(Tok.getLocation()); 1630 ConsumeToken(); 1631 continue; 1632 } 1633 1634 AccessSpecifier AS = getAccessSpecifierIfPresent(); 1635 if (AS != AS_none) { 1636 // Current token is a C++ access specifier. 1637 CurAS = AS; 1638 SourceLocation ASLoc = Tok.getLocation(); 1639 ConsumeToken(); 1640 if (Tok.is(tok::colon)) 1641 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation()); 1642 else 1643 Diag(Tok, diag::err_expected_colon); 1644 ConsumeToken(); 1645 continue; 1646 } 1647 1648 // FIXME: Make sure we don't have a template here. 1649 1650 // Parse all the comma separated declarators. 1651 ParseCXXClassMemberDeclaration(CurAS); 1652 } 1653 1654 RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1655 } else { 1656 SkipUntil(tok::r_brace, false, false); 1657 } 1658 1659 // If attributes exist after class contents, parse them. 1660 llvm::OwningPtr<AttributeList> AttrList; 1661 if (Tok.is(tok::kw___attribute)) 1662 AttrList.reset(ParseGNUAttributes()); 1663 1664 if (TagDecl) 1665 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, 1666 LBraceLoc, RBraceLoc, 1667 AttrList.get()); 1668 1669 // C++ 9.2p2: Within the class member-specification, the class is regarded as 1670 // complete within function bodies, default arguments, 1671 // exception-specifications, and constructor ctor-initializers (including 1672 // such things in nested classes). 1673 // 1674 // FIXME: Only function bodies and constructor ctor-initializers are 1675 // parsed correctly, fix the rest. 1676 if (TagDecl && NonNestedClass) { 1677 // We are not inside a nested class. This class and its nested classes 1678 // are complete and we can parse the delayed portions of method 1679 // declarations and the lexed inline method definitions. 1680 SourceLocation SavedPrevTokLocation = PrevTokLocation; 1681 ParseLexedMethodDeclarations(getCurrentClass()); 1682 ParseLexedMethodDefs(getCurrentClass()); 1683 PrevTokLocation = SavedPrevTokLocation; 1684 } 1685 1686 if (TagDecl) 1687 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc); 1688 1689 // Leave the class scope. 1690 ParsingDef.Pop(); 1691 ClassScope.Exit(); 1692} 1693 1694/// ParseConstructorInitializer - Parse a C++ constructor initializer, 1695/// which explicitly initializes the members or base classes of a 1696/// class (C++ [class.base.init]). For example, the three initializers 1697/// after the ':' in the Derived constructor below: 1698/// 1699/// @code 1700/// class Base { }; 1701/// class Derived : Base { 1702/// int x; 1703/// float f; 1704/// public: 1705/// Derived(float f) : Base(), x(17), f(f) { } 1706/// }; 1707/// @endcode 1708/// 1709/// [C++] ctor-initializer: 1710/// ':' mem-initializer-list 1711/// 1712/// [C++] mem-initializer-list: 1713/// mem-initializer 1714/// mem-initializer , mem-initializer-list 1715void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) { 1716 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 1717 1718 SourceLocation ColonLoc = ConsumeToken(); 1719 1720 llvm::SmallVector<CXXBaseOrMemberInitializer*, 4> MemInitializers; 1721 bool AnyErrors = false; 1722 1723 do { 1724 if (Tok.is(tok::code_completion)) { 1725 Actions.CodeCompleteConstructorInitializer(ConstructorDecl, 1726 MemInitializers.data(), 1727 MemInitializers.size()); 1728 ConsumeCodeCompletionToken(); 1729 } else { 1730 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 1731 if (!MemInit.isInvalid()) 1732 MemInitializers.push_back(MemInit.get()); 1733 else 1734 AnyErrors = true; 1735 } 1736 1737 if (Tok.is(tok::comma)) 1738 ConsumeToken(); 1739 else if (Tok.is(tok::l_brace)) 1740 break; 1741 // If the next token looks like a base or member initializer, assume that 1742 // we're just missing a comma. 1743 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) { 1744 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 1745 Diag(Loc, diag::err_ctor_init_missing_comma) 1746 << FixItHint::CreateInsertion(Loc, ", "); 1747 } else { 1748 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1749 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 1750 SkipUntil(tok::l_brace, true, true); 1751 break; 1752 } 1753 } while (true); 1754 1755 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, 1756 MemInitializers.data(), MemInitializers.size(), 1757 AnyErrors); 1758} 1759 1760/// ParseMemInitializer - Parse a C++ member initializer, which is 1761/// part of a constructor initializer that explicitly initializes one 1762/// member or base class (C++ [class.base.init]). See 1763/// ParseConstructorInitializer for an example. 1764/// 1765/// [C++] mem-initializer: 1766/// mem-initializer-id '(' expression-list[opt] ')' 1767/// 1768/// [C++] mem-initializer-id: 1769/// '::'[opt] nested-name-specifier[opt] class-name 1770/// identifier 1771Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { 1772 // parse '::'[opt] nested-name-specifier[opt] 1773 CXXScopeSpec SS; 1774 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 1775 ParsedType TemplateTypeTy; 1776 if (Tok.is(tok::annot_template_id)) { 1777 TemplateIdAnnotation *TemplateId 1778 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1779 if (TemplateId->Kind == TNK_Type_template || 1780 TemplateId->Kind == TNK_Dependent_template_name) { 1781 AnnotateTemplateIdTokenAsType(&SS); 1782 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 1783 TemplateTypeTy = getTypeAnnotation(Tok); 1784 } 1785 } 1786 if (!TemplateTypeTy && Tok.isNot(tok::identifier)) { 1787 Diag(Tok, diag::err_expected_member_or_base_name); 1788 return true; 1789 } 1790 1791 // Get the identifier. This may be a member name or a class name, 1792 // but we'll let the semantic analysis determine which it is. 1793 IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0; 1794 SourceLocation IdLoc = ConsumeToken(); 1795 1796 // Parse the '('. 1797 if (Tok.isNot(tok::l_paren)) { 1798 Diag(Tok, diag::err_expected_lparen); 1799 return true; 1800 } 1801 SourceLocation LParenLoc = ConsumeParen(); 1802 1803 // Parse the optional expression-list. 1804 ExprVector ArgExprs(Actions); 1805 CommaLocsTy CommaLocs; 1806 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 1807 SkipUntil(tok::r_paren); 1808 return true; 1809 } 1810 1811 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1812 1813 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 1814 TemplateTypeTy, IdLoc, 1815 LParenLoc, ArgExprs.take(), 1816 ArgExprs.size(), RParenLoc); 1817} 1818 1819/// ParseExceptionSpecification - Parse a C++ exception-specification 1820/// (C++ [except.spec]). 1821/// 1822/// exception-specification: 1823/// 'throw' '(' type-id-list [opt] ')' 1824/// [MS] 'throw' '(' '...' ')' 1825/// 1826/// type-id-list: 1827/// type-id 1828/// type-id-list ',' type-id 1829/// 1830bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc, 1831 llvm::SmallVectorImpl<ParsedType> 1832 &Exceptions, 1833 llvm::SmallVectorImpl<SourceRange> 1834 &Ranges, 1835 bool &hasAnyExceptionSpec) { 1836 assert(Tok.is(tok::kw_throw) && "expected throw"); 1837 1838 SourceLocation ThrowLoc = ConsumeToken(); 1839 1840 if (!Tok.is(tok::l_paren)) { 1841 return Diag(Tok, diag::err_expected_lparen_after) << "throw"; 1842 } 1843 SourceLocation LParenLoc = ConsumeParen(); 1844 1845 // Parse throw(...), a Microsoft extension that means "this function 1846 // can throw anything". 1847 if (Tok.is(tok::ellipsis)) { 1848 hasAnyExceptionSpec = true; 1849 SourceLocation EllipsisLoc = ConsumeToken(); 1850 if (!getLang().Microsoft) 1851 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 1852 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1853 return false; 1854 } 1855 1856 // Parse the sequence of type-ids. 1857 SourceRange Range; 1858 while (Tok.isNot(tok::r_paren)) { 1859 TypeResult Res(ParseTypeName(&Range)); 1860 if (!Res.isInvalid()) { 1861 Exceptions.push_back(Res.get()); 1862 Ranges.push_back(Range); 1863 } 1864 if (Tok.is(tok::comma)) 1865 ConsumeToken(); 1866 else 1867 break; 1868 } 1869 1870 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1871 return false; 1872} 1873 1874/// \brief We have just started parsing the definition of a new class, 1875/// so push that class onto our stack of classes that is currently 1876/// being parsed. 1877void Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) { 1878 assert((NonNestedClass || !ClassStack.empty()) && 1879 "Nested class without outer class"); 1880 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass)); 1881} 1882 1883/// \brief Deallocate the given parsed class and all of its nested 1884/// classes. 1885void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 1886 for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I) 1887 DeallocateParsedClasses(Class->NestedClasses[I]); 1888 delete Class; 1889} 1890 1891/// \brief Pop the top class of the stack of classes that are 1892/// currently being parsed. 1893/// 1894/// This routine should be called when we have finished parsing the 1895/// definition of a class, but have not yet popped the Scope 1896/// associated with the class's definition. 1897/// 1898/// \returns true if the class we've popped is a top-level class, 1899/// false otherwise. 1900void Parser::PopParsingClass() { 1901 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 1902 1903 ParsingClass *Victim = ClassStack.top(); 1904 ClassStack.pop(); 1905 if (Victim->TopLevelClass) { 1906 // Deallocate all of the nested classes of this class, 1907 // recursively: we don't need to keep any of this information. 1908 DeallocateParsedClasses(Victim); 1909 return; 1910 } 1911 assert(!ClassStack.empty() && "Missing top-level class?"); 1912 1913 if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() && 1914 Victim->NestedClasses.empty()) { 1915 // The victim is a nested class, but we will not need to perform 1916 // any processing after the definition of this class since it has 1917 // no members whose handling was delayed. Therefore, we can just 1918 // remove this nested class. 1919 delete Victim; 1920 return; 1921 } 1922 1923 // This nested class has some members that will need to be processed 1924 // after the top-level class is completely defined. Therefore, add 1925 // it to the list of nested classes within its parent. 1926 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?"); 1927 ClassStack.top()->NestedClasses.push_back(Victim); 1928 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope(); 1929} 1930 1931/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only 1932/// parses standard attributes. 1933/// 1934/// [C++0x] attribute-specifier: 1935/// '[' '[' attribute-list ']' ']' 1936/// 1937/// [C++0x] attribute-list: 1938/// attribute[opt] 1939/// attribute-list ',' attribute[opt] 1940/// 1941/// [C++0x] attribute: 1942/// attribute-token attribute-argument-clause[opt] 1943/// 1944/// [C++0x] attribute-token: 1945/// identifier 1946/// attribute-scoped-token 1947/// 1948/// [C++0x] attribute-scoped-token: 1949/// attribute-namespace '::' identifier 1950/// 1951/// [C++0x] attribute-namespace: 1952/// identifier 1953/// 1954/// [C++0x] attribute-argument-clause: 1955/// '(' balanced-token-seq ')' 1956/// 1957/// [C++0x] balanced-token-seq: 1958/// balanced-token 1959/// balanced-token-seq balanced-token 1960/// 1961/// [C++0x] balanced-token: 1962/// '(' balanced-token-seq ')' 1963/// '[' balanced-token-seq ']' 1964/// '{' balanced-token-seq '}' 1965/// any token but '(', ')', '[', ']', '{', or '}' 1966CXX0XAttributeList Parser::ParseCXX0XAttributes(SourceLocation *EndLoc) { 1967 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) 1968 && "Not a C++0x attribute list"); 1969 1970 SourceLocation StartLoc = Tok.getLocation(), Loc; 1971 AttributeList *CurrAttr = 0; 1972 1973 ConsumeBracket(); 1974 ConsumeBracket(); 1975 1976 if (Tok.is(tok::comma)) { 1977 Diag(Tok.getLocation(), diag::err_expected_ident); 1978 ConsumeToken(); 1979 } 1980 1981 while (Tok.is(tok::identifier) || Tok.is(tok::comma)) { 1982 // attribute not present 1983 if (Tok.is(tok::comma)) { 1984 ConsumeToken(); 1985 continue; 1986 } 1987 1988 IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo(); 1989 SourceLocation ScopeLoc, AttrLoc = ConsumeToken(); 1990 1991 // scoped attribute 1992 if (Tok.is(tok::coloncolon)) { 1993 ConsumeToken(); 1994 1995 if (!Tok.is(tok::identifier)) { 1996 Diag(Tok.getLocation(), diag::err_expected_ident); 1997 SkipUntil(tok::r_square, tok::comma, true, true); 1998 continue; 1999 } 2000 2001 ScopeName = AttrName; 2002 ScopeLoc = AttrLoc; 2003 2004 AttrName = Tok.getIdentifierInfo(); 2005 AttrLoc = ConsumeToken(); 2006 } 2007 2008 bool AttrParsed = false; 2009 // No scoped names are supported; ideally we could put all non-standard 2010 // attributes into namespaces. 2011 if (!ScopeName) { 2012 switch(AttributeList::getKind(AttrName)) 2013 { 2014 // No arguments 2015 case AttributeList::AT_base_check: 2016 case AttributeList::AT_carries_dependency: 2017 case AttributeList::AT_final: 2018 case AttributeList::AT_hiding: 2019 case AttributeList::AT_noreturn: 2020 case AttributeList::AT_override: { 2021 if (Tok.is(tok::l_paren)) { 2022 Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments) 2023 << AttrName->getName(); 2024 break; 2025 } 2026 2027 CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 0, 2028 SourceLocation(), 0, 0, CurrAttr, false, 2029 true); 2030 AttrParsed = true; 2031 break; 2032 } 2033 2034 // One argument; must be a type-id or assignment-expression 2035 case AttributeList::AT_aligned: { 2036 if (Tok.isNot(tok::l_paren)) { 2037 Diag(Tok.getLocation(), diag::err_cxx0x_attribute_requires_arguments) 2038 << AttrName->getName(); 2039 break; 2040 } 2041 SourceLocation ParamLoc = ConsumeParen(); 2042 2043 ExprResult ArgExpr = ParseCXX0XAlignArgument(ParamLoc); 2044 2045 MatchRHSPunctuation(tok::r_paren, ParamLoc); 2046 2047 ExprVector ArgExprs(Actions); 2048 ArgExprs.push_back(ArgExpr.release()); 2049 CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 2050 0, ParamLoc, ArgExprs.take(), 1, CurrAttr, 2051 false, true); 2052 2053 AttrParsed = true; 2054 break; 2055 } 2056 2057 // Silence warnings 2058 default: break; 2059 } 2060 } 2061 2062 // Skip the entire parameter clause, if any 2063 if (!AttrParsed && Tok.is(tok::l_paren)) { 2064 ConsumeParen(); 2065 // SkipUntil maintains the balancedness of tokens. 2066 SkipUntil(tok::r_paren, false); 2067 } 2068 } 2069 2070 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2071 SkipUntil(tok::r_square, false); 2072 Loc = Tok.getLocation(); 2073 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2074 SkipUntil(tok::r_square, false); 2075 2076 CXX0XAttributeList Attr (CurrAttr, SourceRange(StartLoc, Loc), true); 2077 return Attr; 2078} 2079 2080/// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]] 2081/// attribute. 2082/// 2083/// FIXME: Simply returns an alignof() expression if the argument is a 2084/// type. Ideally, the type should be propagated directly into Sema. 2085/// 2086/// [C++0x] 'align' '(' type-id ')' 2087/// [C++0x] 'align' '(' assignment-expression ')' 2088ExprResult Parser::ParseCXX0XAlignArgument(SourceLocation Start) { 2089 if (isTypeIdInParens()) { 2090 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 2091 SourceLocation TypeLoc = Tok.getLocation(); 2092 ParsedType Ty = ParseTypeName().get(); 2093 SourceRange TypeRange(Start, Tok.getLocation()); 2094 return Actions.ActOnSizeOfAlignOfExpr(TypeLoc, false, true, 2095 Ty.getAsOpaquePtr(), TypeRange); 2096 } else 2097 return ParseConstantExpression(); 2098} 2099